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
swilliams/pathway
refs/heads/master
PathwayExampleApp/PathwayExampleApp/PersonStateMachine.swift
mit
1
// // PersonStateMachine.swift // PathwayExampleApp // // Created by Scott Williams on 2/23/15. // Copyright (c) 2015 Scott Williams. All rights reserved. // import UIKit // This combines both the app's state and the navigation states into a single class. Since the state is simple (2 fields) that's ok, but you'll want to split that out as things start to get a little more complex. class PersonStateMachine: ViewControllerStateMachine { var firstName: String = "" var lastName: String = "" init() { let del = UIApplication.sharedApplication().delegate as? AppDelegate let nav = del?.window?.rootViewController as UINavigationController let firstnameState = NavigationState(identifier: HomeViewController.self) { return HomeViewController(nibName: "HomeViewController", bundle: nil) } let lastnameState = NavigationState(identifier: LastNameViewController.self) { return LastNameViewController(nibName: "LastNameViewController", bundle: nil) } let finalState = NavigationState(identifier: EndViewController.self) { return EndViewController(nibName: "EndViewController", bundle: nil) } let linearDecider = LinearStateMachineLogic(states: [firstnameState, lastnameState, finalState]) super.init(navController: nav, stateMachineLogic: linearDecider) } }
61eb66035c79783f7823e7d47accf174
42.5
212
0.715517
false
false
false
false
quadro5/swift3_L
refs/heads/master
swift_question.playground/Pages/UnionFind - email entry.xcplaygroundpage/Contents.swift
unlicense
1
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) // Union find - model, // o(n) find // o(n) union class UnionFind1 { var dict = Dictionary<Int, Int>() /// search for top father /// /// - Parameter key: serach key /// - Returns: top father func find(key: Int) -> Int { // key existed in the father // we add one into guard var parent = dict[key] else { dict[key] = key return key } while dict[parent] != nil { // if fatherOfparent point to other if let fatherOfParent = dict[parent], parent != fatherOfParent { parent = fatherOfParent // if fatherOfparent point to itself // we find the top father } else { break } } return parent } /// connect left and right /// /// - Parameters: /// - left: left key /// - right: right key func union(left: Int, right: Int) { let leftFather = self.find(key: left) let rightFather = self.find(key: right) // if top father is not equal // we let rightFather as the new top father of left/right if leftFather != rightFather { dict[leftFather] = rightFather } } } /// UnionFind - improved model, compressed path /// o(1) avg find /// o(1) avg union class UnionFind2 { var dict = Dictionary<Int, Int>() /// search for top father /// /// - Parameter key: serach key /// - Returns: top father func find(key: Int) -> Int { // key existed in the father // we add one into guard var topFather = dict[key] else { dict[key] = key return key } // find top father while dict[topFather] != nil { // if fatherOfparent point to other if let fatherOfParent = dict[topFather], topFather != fatherOfParent { topFather = fatherOfParent // if fatherOfparent point to itself // we find the top father } else { break } } // compress path // refind all path of key's father // change all dict[path] = topFather var father = key while dict[father] != nil { if let fatherOfFather = dict[father], father != fatherOfFather { dict[father] = topFather father = fatherOfFather } else { break } } return topFather } /// connect left and right /// /// - Parameters: /// - left: left key /// - right: right key func union(left: Int, right: Int) { let leftFather = self.find(key: left) let rightFather = self.find(key: right) // if top father is not equal // we let rightFather as the new top father of left/right if leftFather != rightFather { dict[leftFather] = rightFather } } } /* Email problem - combine related entry input: name: "c1", emails: ["e1", "e2"] name: "c2", emails: ["e3", "e4"] name: "c3", emails: ["e5", "e6"] name: "c4", emails: ["e1", "e3"] return: [c1, c2, c4], [c3] */ struct EmailEntry { var name: String var emails: Array<String> init(name: String, emails: Array<String>) { self.name = name self.emails = emails } init() { self.name = "" self.emails = Array<String>() } } class UnionFind { // child email, parent email var dict = Dictionary<String, String>() // email, [userName] var emailBooks = Dictionary<String, Set<String>>() func add(entry: EmailEntry) -> Void { // combine with the same email combine(entry: entry) // find all related parents var fathers = Set<String>() for email in entry.emails { // if can find final father if let parent = dict[email] { let father = getFather(from: parent) fathers.insert(father) } } // if no fathers find / first entry if fathers.isEmpty { if let father = entry.emails.first { dict[father] = father for child in entry.emails { if child != father { dict[child] = father add(user: entry.name, toFatherEmail: father) } } } // all parents point to fahter } else { if let father = fathers.first { //print("final father: \(father)\n") for parent in fathers { if parent != father { dict[parent] = father combine(from: parent, to: father) } } for email in entry.emails { dict[email] = father add(user: entry.name, toFatherEmail: father) } } } } // print userList func userList() -> Array<Array<String>>? { if dict.isEmpty { return nil } var res = Array<Array<String>>() var usedEmailSet = Set<String>() for email in dict { // if cur email has parent if let parent = dict[email.key] { let father = getFather(from: parent) if usedEmailSet.contains(father) == false { let userSet = emailBooks[father]! res.append(Array(userSet)) usedEmailSet.insert(father) } } else { // if cur email has not parent if let userSet = emailBooks[email.key] { res.append(Array(userSet)) } } } return res } /// combine entry's email in to emailBooks /// /// - Parameter entry: input email entry private func combine(entry: EmailEntry) { // combine with the same email for email in entry.emails { if emailBooks[email] != nil { emailBooks[email]?.insert(entry.name) } else { emailBooks[email] = Set<String>([entry.name]) } } } /// add userName to the father /// /// - Parameters: /// - user: userName /// - father: father private func add(user: String, toFatherEmail father: String) { if emailBooks[father] == nil { emailBooks[father] = Set<String>([user]) } else { emailBooks[father]?.insert(user) } } /// combine userSet from child to father /// /// - Parameters: /// - child: child name /// - father: father name private func combine(from child: String, to father: String) { if let childSet = emailBooks[child] { emailBooks[father]?.formUnion(childSet) } } /// get final father /// /// - Parameter child: input child name /// - Returns: final father name private func getFather(from child: String) -> String { var father = child while (dict[father] != nil && dict[father] != father) { father = dict[father]! } return father } } // test let emailUnion = UnionFind() var entrys = Array<EmailEntry>() entrys.append(EmailEntry(name: "c1", emails: ["e1", "e2"])) entrys.append(EmailEntry(name: "c2", emails: ["e3", "e4"])) entrys.append(EmailEntry(name: "c3", emails: ["e5", "e6"])) entrys.append(EmailEntry(name: "c4", emails: ["e1", "e3"])) for entry in entrys { emailUnion.add(entry: entry) } print("input: \n\(entrys)\n") print("dict: \n\(emailUnion.dict)\n") print("emailBooks: \n\(emailUnion.emailBooks)\n") if let res = emailUnion.userList() { print("res: \(res)") } else { print("nil") }
39e57f33e10aae622230609ba0d34fdd
23.661677
68
0.496783
false
false
false
false
BurlApps/latch
refs/heads/master
Framework/LTPasscodeKey.swift
gpl-2.0
2
// // LTPasscodeKey.swift // Latch // // Created by Brian Vallelunga on 10/25/14. // Copyright (c) 2014 Brian Vallelunga. All rights reserved. // import UIKit protocol LTPasscodeKeyDelegate { func keyPressed(number: Int) } class LTPasscodeKey: UIButton { // MARK: Instance Variable var delegate: LTPasscodeKeyDelegate! var parentView: UIView! var background: UIColor! var border: UIColor! var backgroundTouch: UIColor! var borderTouch: UIColor! var numberLabel: UILabel! // MARK: Private Instance Variable var number: Int! private var row: CGFloat! private var column: CGFloat! // MARK: Instance Method convenience init(number: Int, alpha: String!, row: CGFloat, column: CGFloat) { self.init() // Assign Instance Variables self.row = row self.column = column self.number = number // Create Number Label self.numberLabel = UILabel() self.numberLabel.textAlignment = NSTextAlignment.Center if number >= 0 { self.numberLabel.font = UIFont(name: "HelveticaNeue-Thin", size: 28) self.numberLabel.numberOfLines = 2 if alpha != nil { var attributedText = NSMutableAttributedString(string: "\(number)") var alphaText = NSMutableAttributedString(string: "\n\(alpha)") alphaText.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Thin", size: 12)!, range: NSMakeRange(0, alphaText.length)) attributedText.appendAttributedString(alphaText) self.numberLabel.attributedText = attributedText } else { self.numberLabel.text = "\(number)" } } else { self.numberLabel.text = "Delete" self.numberLabel.font = UIFont(name: "HelveticaNeue", size: 18) } self.addSubview(self.numberLabel) // Attach Event Listner self.addTarget(self, action: Selector("holdHandle:"), forControlEvents: UIControlEvents.TouchDown) self.addTarget(self, action: Selector("tapHandle:"), forControlEvents: UIControlEvents.TouchUpInside) } // MARK: Gesture Handler @IBAction func holdHandle(gesture: UIPanGestureRecognizer) { if self.number >= 0 { self.backgroundColor = self.backgroundTouch self.layer.borderColor = self.borderTouch.CGColor self.numberLabel.textColor = self.borderTouch } else { self.numberLabel.alpha = 0.4 } } @IBAction func tapHandle(gesture: UIPanGestureRecognizer) { self.delegate!.keyPressed(self.number) UIView.animateWithDuration(0.4, delay: 0.05, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in if self.number >= 0 { self.backgroundColor = self.background self.layer.borderColor = self.border.CGColor self.numberLabel.textColor = self.border } else { self.numberLabel.alpha = 1 } }, completion: nil) } // MARK: Instance Methods func configureKey() { // Create Frame var keyWidth: CGFloat = 65 var keyHeight: CGFloat = 65 var keyPadding: CGFloat = 18 var keyCenterX = self.parentView.frame.width/2 - (keyWidth/2) var keyX = keyCenterX + ((keyWidth + keyPadding) * (self.column - 1)) var keyY = (keyHeight + keyPadding) * self.row self.frame = CGRectMake(keyX, keyY, keyWidth, keyHeight) // Update View Styling if self.number >= 0 { self.backgroundColor = self.background self.layer.borderColor = self.border.CGColor self.layer.borderWidth = 1 self.layer.cornerRadius = keyWidth/2 self.layer.masksToBounds = true } // Update Label Styling self.numberLabel.frame = CGRectMake(0, 0, keyWidth, keyHeight) self.numberLabel.textColor = self.border } }
35b8f94954fb7a49929aaca29b9dd5fb
33.53719
154
0.601819
false
false
false
false
Aioria1314/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/Views/Home/ZXCHomeController.swift
mit
1
// // ZXCHomeController.swift // WeiBo // // Created by Aioria on 2017/3/26. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit import YYModel class ZXCHomeController: ZXCVistorViewController { // lazy var statusList: [ZXCStatus] = [ZXCStatus]() fileprivate lazy var pullUpView: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) indicatorView.color = UIColor.red return indicatorView }() // fileprivate lazy var pullDownView: UIRefreshControl = { // // let refresh = UIRefreshControl() // // refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged) // // return refresh // }() fileprivate lazy var pullDownView: ZXCRefreshControl = { let refresh = ZXCRefreshControl() refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged) return refresh }() fileprivate lazy var labTip: UILabel = { let lab = UILabel() lab.text = "没有加载到最新数据" lab.isHidden = true lab.textColor = UIColor.white lab.backgroundColor = UIColor.orange lab.font = UIFont.systemFont(ofSize: 15) lab.textAlignment = .center return lab }() fileprivate lazy var homeViewModel: ZXCHomeViewModel = ZXCHomeViewModel() override func viewDidLoad() { super.viewDidLoad() if !isLogin { visitorView?.updateVisitorInfo(imgName: nil, message: nil) } else { loadData() setupUI() } } fileprivate func setupUI() { setupTableView() if let nav = self.navigationController { nav.view.insertSubview(labTip, belowSubview: nav.navigationBar) labTip.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.width, height: 35) } } fileprivate func setupTableView() { tableView.register(ZXCHomeTableViewCell.self, forCellReuseIdentifier: homeReuseID) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 tableView.separatorStyle = .none tableView.tableFooterView = pullUpView // self.refreshControl = pullDownView tableView.addSubview(pullDownView) } fileprivate func loadData() { // ZXCNetworkTools.sharedTools.requestHomeData(accessToken: ZXCUserAccountViewModel.sharedViewModel.accessToken!) { (response, error) in // // if error != nil { // } // // guard let dict = response as? [String: Any] else { // return // } // // let statusDic = dict["statuses"] as? [[String: Any]] // // let statusArray = NSArray.yy_modelArray(with: ZXCStatus.self, json: statusDic!) as! [ZXCStatus] // // self.statusList = statusArray // // self.tableView.reloadData() // } homeViewModel.requestHomeData(isPullup: pullUpView.isAnimating) { (isSuccess, message) in if self.pullUpView.isAnimating == false { if self.labTip.isHidden == false { return } self.tipAnimation(message: message) } self.endRefreshing() if isSuccess { self.tableView.reloadData() } } } fileprivate func endRefreshing() { pullUpView.stopAnimating() pullDownView.endRefreshing() } // MARK: DataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.homeViewModel.statusList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ZXCHomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: homeReuseID, for: indexPath) as! ZXCHomeTableViewCell cell.statusViewModel = homeViewModel.statusList[indexPath.row] // cell.textLabel?.text = homeViewModel.statusList[indexPath.row].user?.screen_name return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == homeViewModel.statusList.count - 1 && !pullUpView.isAnimating{ pullUpView.startAnimating() loadData() } } @objc fileprivate func pullDownrefreshAction () { loadData() } fileprivate func tipAnimation(message: String) { labTip.text = message labTip.isHidden = false UIView.animate(withDuration: 1, animations: { self.labTip.transform = CGAffineTransform(translationX: 0, y: self.labTip.height) }) { (_) in UIView.animate(withDuration: 1, animations: { self.labTip.transform = CGAffineTransform.identity }, completion: { (_) in self.labTip.isHidden = true }) } } }
54249e99eda0eae96f0e8daed92c33a6
27.405941
143
0.554549
false
false
false
false
rolson/arcgis-runtime-samples-ios
refs/heads/master
arcgis-ios-sdk-samples/Content Display Logic/Controllers/ContentCollectionViewController.swift
apache-2.0
1
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit private let reuseIdentifier = "CategoryCell" class ContentCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, CustomSearchHeaderViewDelegate { @IBOutlet private var collectionView:UICollectionView! private var headerView:CustomSearchHeaderView! var nodesArray:[Node]! private var transitionSize:CGSize! override func viewDidLoad() { super.viewDidLoad() //hide suggestions self.hideSuggestions() self.populateTree() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func populateTree() { let path = NSBundle.mainBundle().pathForResource("ContentPList", ofType: "plist") let content = NSArray(contentsOfFile: path!) self.nodesArray = self.populateNodesArray(content! as [AnyObject]) self.collectionView?.reloadData() } func populateNodesArray(array:[AnyObject]) -> [Node] { var nodesArray = [Node]() for object in array { let node = self.populateNode(object as! [String:AnyObject]) nodesArray.append(node) } return nodesArray } func populateNode(dict:[String:AnyObject]) -> Node { let node = Node() if let displayName = dict["displayName"] as? String { node.displayName = displayName } if let descriptionText = dict["descriptionText"] as? String { node.descriptionText = descriptionText } if let storyboardName = dict["storyboardName"] as? String { node.storyboardName = storyboardName } if let children = dict["children"] as? [AnyObject] { node.children = self.populateNodesArray(children) } return node } //MARK: - Suggestions related func showSuggestions() { // if !self.isSuggestionsTableVisible() { self.collectionView.performBatchUpdates({ [weak self] () -> Void in (self?.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).headerReferenceSize = CGSize(width: self!.collectionView.bounds.width, height: self!.headerView.expandedViewHeight) }, completion: nil) //show suggestions // } } func hideSuggestions() { // if self.isSuggestionsTableVisible() { self.collectionView.performBatchUpdates({ [weak self] () -> Void in (self?.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).headerReferenceSize = CGSize(width: self!.collectionView.bounds.width, height: self!.headerView.shrinkedViewHeight) }, completion: nil) //hide suggestions // } } //TODO: implement this // func isSuggestionsTableVisible() -> Bool { // return (self.headerView?.suggestionsTableHeightConstraint?.constant == 0 ? false : true) ?? false // } //MARK: - samples lookup by name func nodesByDisplayNames(names:[String]) -> [Node] { var nodes = [Node]() for node in self.nodesArray { let children = node.children let matchingNodes = children.filter({ return names.contains($0.displayName) }) nodes.appendContentsOf(matchingNodes) } return nodes } // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.nodesArray?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCell let node = self.nodesArray[indexPath.item] //mask to bounds cell.layer.masksToBounds = false //name cell.nameLabel.text = node.displayName.uppercaseString //icon let image = UIImage(named: "\(node.displayName)_icon") cell.iconImageView.image = image //background image let bgImage = UIImage(named: "\(node.displayName)_bg") cell.backgroundImageView.image = bgImage //cell shadow cell.layer.cornerRadius = 5 cell.layer.masksToBounds = true return cell } //supplementary view as search bar func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if self.headerView == nil { self.headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "CollectionHeaderView", forIndexPath: indexPath) as! CustomSearchHeaderView self.headerView.delegate = self } return self.headerView } //size for item func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if self.transitionSize != nil { return self.transitionSize } return self.itemSizeForCollectionViewSize(collectionView.frame.size) } //MARK: - UICollectionViewDelegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { //hide keyboard if visible self.view.endEditing(true) let node = self.nodesArray[indexPath.item] let controller = self.storyboard!.instantiateViewControllerWithIdentifier("ContentTableViewController") as! ContentTableViewController controller.nodesArray = node.children controller.title = node.displayName self.navigationController?.showViewController(controller, sender: self) } //MARK: - Transition //get the size of the new view to be transitioned to override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { let newFlowLayout = UICollectionViewFlowLayout() newFlowLayout.itemSize = self.itemSizeForCollectionViewSize(size) newFlowLayout.sectionInset = UIEdgeInsets(top: 5, left: 10, bottom: 10, right: 10) newFlowLayout.headerReferenceSize = CGSize(width: size.width, height: (self.headerView.isShowingSuggestions ? self.headerView.expandedViewHeight : self.headerView.shrinkedViewHeight)) self.transitionSize = newFlowLayout.itemSize self.collectionView?.setCollectionViewLayout(newFlowLayout, animated: false) self.transitionSize = nil } //item width based on the width of the collection view func itemSizeForCollectionViewSize(size:CGSize) -> CGSize { //first try for 3 items in a row var width = (size.width - 4*10)/3 if width < 150 { //if too small then go for 2 in a row width = (size.width - 3*10)/2 } return CGSize(width: width, height: width) } //MARK: - CustomSearchHeaderViewDelegate func customSearchHeaderView(customSearchHeaderView: CustomSearchHeaderView, didFindSamples sampleNames: [String]?) { if let sampleNames = sampleNames { let resultNodes = self.nodesByDisplayNames(sampleNames) if resultNodes.count > 0 { //show the results let controller = self.storyboard!.instantiateViewControllerWithIdentifier("ContentTableViewController") as! ContentTableViewController controller.nodesArray = resultNodes controller.title = "Search results" controller.containsSearchResults = true self.navigationController?.showViewController(controller, sender: self) return } } SVProgressHUD.showErrorWithStatus("No match found", maskType: .Gradient) } func customSearchHeaderViewWillHideSuggestions(customSearchHeaderView: CustomSearchHeaderView) { self.hideSuggestions() } func customSearchHeaderViewWillShowSuggestions(customSearchHeaderView: CustomSearchHeaderView) { self.showSuggestions() } }
dcb6254550cf52e179268023048ac8ec
38.343348
206
0.669139
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/Core/Ads/BannersCache.swift
apache-2.0
4
import FirebaseCrashlytics @objc(MWMBannersCache) final class BannersCache: NSObject { @objc static let cache = BannersCache() private override init() {} private enum LoadState: Equatable { case notLoaded(BannerType) case loaded(BannerType) case error(BannerType) static func ==(lhs: LoadState, rhs: LoadState) -> Bool { switch (lhs, rhs) { case let (.notLoaded(l), .notLoaded(r)): return l == r case let (.loaded(l), .loaded(r)): return l == r case let (.error(l), .error(r)): return l == r case (.notLoaded, _), (.loaded, _), (.error, _): return false } } } typealias Completion = (MWMBanner, Bool) -> Void private var cache: [BannerType: Banner] = [:] private var requests: [BannerType: Banner] = [:] private var completion: Completion? private var loadStates: [LoadState]! private var cacheOnly = false private func onCompletion(isAsync: Bool) { guard let completion = completion else { return } var banner: Banner? statesLoop: for loadState in loadStates { switch loadState { case let .notLoaded(type): banner = cache[type] break statesLoop case let .loaded(type): banner = cache[type] break statesLoop case .error: continue } } if let banner = banner { Statistics.logEvent(kStatPlacePageBannerShow, withParameters: banner.statisticsDescription) completion(banner, isAsync) banner.isBannerOnScreen = true self.completion = nil loadStates = nil } } @objc func get(coreBanners: [CoreBanner], cacheOnly: Bool, loadNew: Bool = true, completion: @escaping Completion) { self.completion = completion self.cacheOnly = cacheOnly setupLoadStates(coreBanners: coreBanners, loadNew: loadNew) onCompletion(isAsync: false) } @objc func refresh(coreBanners: [CoreBanner]) { setupLoadStates(coreBanners: coreBanners, loadNew: true) } fileprivate func setupLoadStates(coreBanners: [CoreBanner], loadNew: Bool) { loadStates = [] coreBanners.forEach { coreBanner in let bannerType = BannerType(type: coreBanner.mwmType, id: coreBanner.bannerID, query: coreBanner.query) if let banner = cache[bannerType], (!banner.isPossibleToReload || banner.isNeedToRetain) { appendLoadState(.loaded(bannerType)) } else { if loadNew { get(bannerType: bannerType) } appendLoadState(.notLoaded(bannerType)) } } } private func get(bannerType: BannerType) { guard requests[bannerType] == nil else { return } let banner = bannerType.banner! requests[bannerType] = banner banner.reload(success: { [unowned self] banner in self.setLoaded(banner: banner) }, failure: { [unowned self] bannerType, event, errorDetails, error in var statParams = errorDetails statParams[kStatErrorMessage] = (error as NSError).userInfo.reduce("") { $0 + "\($1.key) : \($1.value)\n" } Statistics.logEvent(event, withParameters: statParams) Crashlytics.crashlytics().record(error: error) self.setError(bannerType: bannerType) }, click: { banner in Statistics.logEvent(kStatPlacePageBannerClick, withParameters: banner.statisticsDescription) }) } private func appendLoadState(_ state: LoadState) { guard loadStates.firstIndex(of: state) == nil else { return } loadStates.append(state) } private func notLoadedIndex(bannerType: BannerType) -> Array<LoadState>.Index? { return loadStates.firstIndex(where: { if case let .notLoaded(type) = $0, type == bannerType { return true } return false }) } private func setLoaded(banner: Banner) { let bannerType = banner.type cache[bannerType] = banner requests[bannerType] = nil guard loadStates != nil else { return } if let notLoadedIndex = loadStates.firstIndex(of: .notLoaded(bannerType)) { loadStates[notLoadedIndex] = .loaded(bannerType) } if !cacheOnly { onCompletion(isAsync: true) } } private func setError(bannerType: BannerType) { requests[bannerType] = nil guard loadStates != nil else { return } if let notLoadedIndex = loadStates.firstIndex(of: .notLoaded(bannerType)) { loadStates[notLoadedIndex] = .error(bannerType) } if !cacheOnly { onCompletion(isAsync: true) } } @objc func bannerIsOutOfScreen(coreBanner: MWMBanner) { bannerIsOutOfScreen(bannerType: BannerType(type: coreBanner.mwmType, id: coreBanner.bannerID)) } func bannerIsOutOfScreen(bannerType: BannerType) { completion = nil if let cached = cache[bannerType], cached.isBannerOnScreen { cached.isBannerOnScreen = false } } }
e77e74de159200fa09018269efbd59cb
30.407895
118
0.667993
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/UI/LicenseViewController.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 UIKit import WebKit class LicenseViewController: MaterialHeaderViewController { // MARK: - Properties private let license: LicenseData private let webView = WKWebView() override var trackedScrollView: UIScrollView? { return webView.scrollView } // MARK: - Public init(license: LicenseData, analyticsReporter: AnalyticsReporter) { self.license = license super.init(analyticsReporter: analyticsReporter) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(webView) view.isAccessibilityElement = false webView.translatesAutoresizingMaskIntoConstraints = false webView.pinToEdgesOfView(view) if isPresented { appBar.hideStatusBarOverlay() } title = license.title let backMenuItem = MaterialBackBarButtonItem(target: self, action: #selector(backButtonPressed)) navigationItem.leftBarButtonItem = backMenuItem if let licenseFile = Bundle.currentBundle.path(forResource: license.filename, ofType: nil) { do { let licenseString = try String(contentsOfFile: licenseFile, encoding: String.Encoding.utf8) webView.loadHTMLString(licenseString, baseURL: nil) } catch { print("Could not read license file: \(license.filename).html, error: " + error.localizedDescription) } } } // MARK: - User Actions @objc private func backButtonPressed() { navigationController?.popViewController(animated: true) } }
1ca703dc00332ef774051de9702d2285
28.866667
100
0.705357
false
false
false
false
vapor/node
refs/heads/master
Sources/Node/Convertibles/Date+Convertible.swift
mit
1
import Foundation extension Date: NodeConvertible { internal static let lock = NSLock() /** If a date receives a numbered node, it will use this closure to convert that number into a Date as a timestamp By default, this timestamp uses seconds via timeIntervalSince1970. Override for custom implementations */ public static var incomingTimestamp: (Node.Number) throws -> Date = { return Date(timeIntervalSince1970: $0.double) } /** In default scenarios where a timestamp should be represented as a Number, this closure will be used. By default, uses seconds via timeIntervalSince1970. Override for custom implementations. */ public static var outgoingTimestamp: (Date) throws -> Node.Number = { return Node.Number($0.timeIntervalSince1970) } /** A prioritized list of date formatters to use when attempting to parse a String into a Date. Override for custom implementations, or to remove supported formats */ public static var incomingDateFormatters: [DateFormatter] = [ .iso8601, .mysql, .rfc1123 ] /** A default formatter to use when serializing a Date object to a String. Defaults to ISO 8601 Override for custom implementations. For complex scenarios where various string representations must be used, the user is responsible for handling their date formatting manually. */ public static var outgoingDateFormatter: DateFormatter = .iso8601 /** Initializes a Date object with another Node.date, a number representing a timestamp, or a formatted date string corresponding to one of the `incomingDateFormatters`. */ public init(node: Node) throws { switch node.wrapped { case let .date(date): self = date case let .number(number): self = try Date.incomingTimestamp(number) case let .string(string): Date.lock.lock() defer { Date.lock.unlock() } guard let date = Date.incomingDateFormatters .lazy .flatMap({ $0.date(from: string) }) .first else { fallthrough } self = date default: throw NodeError.unableToConvert( input: node, expectation: "\(Date.self), formatted time string, or timestamp", path: [] ) } } /// Creates a node representation of the date public func makeNode(in context: Context?) throws -> Node { return .date(self, in: context) } } extension StructuredData { public var date: Date? { return try? Date(node: self, in: nil) } } extension DateFormatter { /** ISO8601 Date Formatter -- preferred in JSON http://stackoverflow.com/a/28016692/2611971 */ @nonobjc public static let iso8601: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter }() } extension DateFormatter { /** A date formatter for mysql formatted types */ @nonobjc public static let mysql: DateFormatter = { let formatter = DateFormatter() formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() } extension DateFormatter { /** A date formatter conforming to RFC 1123 spec */ @nonobjc public static let rfc1123: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" return formatter }() }
f6203330a3958abdbaecbbbcab54060a
29.143939
92
0.60769
false
false
false
false
sarunw/SWAnimatedTabBarController
refs/heads/master
Example/SWAnimatedTabBarController/SWAnimatedTabBarController/Animations/SWPopAnimation.swift
mit
1
// // SWPopAnimation.swift // SWAnimatedTabBarController // // Created by Sarun Wongpatcharapakorn on 4/24/15. // Copyright (c) 2015 Sarun Wongpatcharapakorn. All rights reserved. // import UIKit class SWPopAnimation: SWItemAnimation { override func playAnimation(iconView: IconView) { let animatedView = iconView.icon let frameDuration = 1.0/2 let duration = 0.3 let delay: NSTimeInterval = 0 animatedView.transform = CGAffineTransformMakeScale(1, 1) UIView.animateKeyframesWithDuration(duration, delay: delay, options: nil, animations: { () -> Void in UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: frameDuration, animations: { () -> Void in animatedView.transform = CGAffineTransformMakeScale(1.2, 1.2) }) UIView.addKeyframeWithRelativeStartTime(1 * frameDuration, relativeDuration: frameDuration, animations: { () -> Void in animatedView.transform = CGAffineTransformMakeScale(1, 1) }) }, completion: nil) } override func selectedState(iconView: IconView) { self.playAnimation(iconView) } }
64f400c5ac294fd1535f7ba43c93f873
36.28125
131
0.664711
false
false
false
false
csnu17/My-Swift-learning
refs/heads/master
collection-data-structures-swift/DataStructures.playground/Contents.swift
mit
1
import Foundation let cats = [ "Ellen" : "Chaplin", "Lilia" : "George Michael", "Rose" : "Friend", "Bettina" : "Pai Mei"] cats["Ellen"] //returns Chaplin as an optional cats["Steve"] //Returns nil if let ellensCat = cats["Ellen"] { print("Ellen's cat is named \(ellensCat).") } else { print("Ellen's cat's name not found!") } let names = ["John", "Paul", "George", "Ringo", "Mick", "Keith", "Charlie", "Ronnie"] var stringSet = Set<String>() // 1 var loopsCount = 0 while stringSet.count < 4 { let randomNumber = arc4random_uniform(UInt32(names.count)) // 2 let randomName = names[Int(randomNumber)] // 3 print(randomName) // 4 stringSet.insert(randomName) // 5 loopsCount += 1 // 6 } // 7 print("Loops: " + loopsCount.description + ", Set contents: " + stringSet.description) let countedMutable = NSCountedSet() for name in names { countedMutable.add(name) countedMutable.add(name) } let ringos = countedMutable.count(for: "Ringo") print("Counted Mutable set: \(countedMutable)) with count for Ringo: \(ringos)") let items : NSArray = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] let indexSet = NSMutableIndexSet() indexSet.add(3) indexSet.add(8) indexSet.add(9) items.objects(at: indexSet as IndexSet) // returns ["four", "nine", "ten"]
c9573e1e3699aacd5945185c042880e9
29
103
0.657316
false
false
false
false
roecrew/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Analysis/Frequency Tracker/AKFrequencyTracker.swift
mit
1
// // AKFrequencyTracker.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This is based on an algorithm originally created by Miller Puckette. /// /// - Parameters: /// - input: Input node to process /// - hopSize: Hop size. /// - peakCount: Number of peaks. /// public class AKFrequencyTracker: AKNode, AKToggleable { // MARK: - Properties private var internalAU: AKFrequencyTrackerAudioUnit? private var token: AUParameterObserverToken? /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } /// Detected Amplitude (Use AKAmplitude tracker if you don't need frequency) public var amplitude: Double { return Double(self.internalAU!.getAmplitude()) / 2.0 // Stereo Hack } /// Detected frequency public var frequency: Double { return Double(self.internalAU!.getFrequency()) * 2.0 // Stereo Hack } // MARK: - Initialization /// Initialize this Pitch-tracker node /// /// - parameter input: Input node to process /// - parameter hopSize: Hop size. /// - parameter peakCount: Number of peaks. /// public init( _ input: AKNode, hopSize: Double = 512, peakCount: Double = 20) { var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = fourCC("ptrk") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKFrequencyTrackerAudioUnit.self, asComponentDescription: description, name: "Local AKFrequencyTracker", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKFrequencyTrackerAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
42ba4a3bf2993e585a1ffb6ec8af1e9d
28.76087
91
0.645727
false
false
false
false
ReiVerdugo/uikit-fundamentals
refs/heads/master
step4.8-roshamboWithHistory-solution/RockPaperScissors/RockPaperScissorsViewController.swift
mit
1
// // RockPaperScissorsViewController.swift // RockPaperScissors // // Created by Gabrielle Miller-Messner on 10/30/14. // Copyright (c) 2014 Gabrielle Miller-Messner. All rights reserved. // import UIKit // MARK: - RockPaperScissorsViewController: UIViewController class RockPaperScissorsViewController: UIViewController { // MARK: Properties var history = [RPSMatch]() // MARK: Outlets @IBOutlet weak var rockButton: UIButton! @IBOutlet weak var paperButton: UIButton! @IBOutlet weak var scissorsButton: UIButton! // MARK: Actions @IBAction func makeYourMove(sender: UIButton) { switch (sender) { case self.rockButton: throwDown(RPS.Rock) case self.paperButton: throwDown(RPS.Paper) case self.scissorsButton: throwDown(RPS.Scissors) default: assert(false, "An unknown button is invoking makeYourMove()") } } @IBAction func showHistory(sender: AnyObject) { let storyboard = self.storyboard let controller = storyboard?.instantiateViewControllerWithIdentifier("HistoryViewController")as! HistoryViewController controller.history = self.history self.presentViewController(controller, animated: true, completion: nil) } // MARK: Play! func throwDown(playersMove: RPS) { let computersMove = RPS() let match = RPSMatch(p1: playersMove, p2: computersMove) // Add match to the history history.append(match) // Get the Storyboard and ResultViewController let storyboard = UIStoryboard (name: "Main", bundle: nil) let resultVC = storyboard.instantiateViewControllerWithIdentifier("ResultViewController") as! ResultViewController // Communicate the match to the ResultViewController resultVC.match = match self.presentViewController(resultVC, animated: true, completion: nil) } }
079a20cea342947fd815c60fe0255ab6
27.861111
126
0.641001
false
false
false
false
CPRTeam/CCIP-iOS
refs/heads/master
Pods/thenPromise/Source/PromiseState.swift
gpl-3.0
3
// // PromiseState.swift // then // // Created by Sacha Durand Saint Omer on 08/08/16. // Copyright © 2016 s4cha. All rights reserved. // import Foundation public enum PromiseState<T> { case dormant case pending(progress: Float) case fulfilled(value: T) case rejected(error: Error) } extension PromiseState { var value: T? { if case let .fulfilled(value) = self { return value } return nil } var error: Error? { if case let .rejected(error) = self { return error } return nil } var isDormant: Bool { if case .dormant = self { return true } return false } var isPendingOrDormant: Bool { return !isFulfilled && !isRejected } var isFulfilled: Bool { if case .fulfilled = self { return true } return false } var isRejected: Bool { if case .rejected = self { return true } return false } }
ad394e02cb395f3ee3689a4b5e2a223d
17.517241
51
0.52514
false
false
false
false
mindforce/Projector
refs/heads/master
Projector/LoginViewController.swift
gpl-2.0
1
// // LoginViewController.swift // RedmineProject-3.0 // // Created by Volodymyr Tymofiychuk on 14.01.15. // Copyright (c) 2015 Volodymyr Tymofiychuk. All rights reserved. // import UIKit import Alamofire class LoginViewController: UIViewController { @IBOutlet weak var txtLink: UITextField! @IBOutlet weak var txtUsername: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var switchRememberMe: UISwitch! @IBAction func btnLogin(sender: UIButton) { var username = txtUsername.text var password = txtPassword.text var defaultData : NSUserDefaults = NSUserDefaults.standardUserDefaults() if (username != "" && password != "") { var baseUrl = txtLink.text defaultData.setObject(baseUrl, forKey: "BASE_URL") var urlPath = baseUrl + "/users/current.json" urlPath = urlPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! var url: NSURL = NSURL(string: urlPath)! println("Start login '\(username)'") Alamofire.request(.GET, url) .authenticate(user: username, password: password) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseJSON { (request, response, json, error) in if error == nil { var json = JSON(json!) var api_key = json["user"]["api_key"] defaultData.setObject(username, forKey: "USERNAME") defaultData.setObject(api_key.stringValue, forKey: "API_KEY") if self.switchRememberMe.on { defaultData.setBool(true, forKey: "REMEMBER_ME") } else { defaultData.setBool(false, forKey: "REMEMBER_ME") } defaultData.synchronize() self.dismissViewControllerAnimated(true, completion: nil) } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
12612998a6f1d563ce1d1a6fa5a8bf50
34.204819
106
0.562971
false
false
false
false
Webtrekk/webtrekk-ios-sdk
refs/heads/master
Source/Internal/Reachability/Reachability.swift
mit
1
/* Copyright (c) 2014, Ashley Mills 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // TODO: Although not part of watchOS target, still generates an error on cocoapods lib lint #if !os(watchOS) import SystemConfiguration import Foundation public enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue case UnableToGetInitialFlags } @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged") public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") public extension Notification.Name { static let reachabilityChanged = Notification.Name("reachabilityChanged") } public class Reachability { public typealias NetworkReachable = (Reachability) -> Void public typealias NetworkUnreachable = (Reachability) -> Void @available(*, unavailable, renamed: "Connection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public enum Connection: CustomStringConvertible { case none, wifi, cellular public var description: String { switch self { case .cellular: return "Cellular" case .wifi: return "WiFi" case .none: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? @available(*, deprecated, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default @available(*, deprecated, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } public var connection: Connection { if flags == nil { try? setReachabilityFlags() } switch flags?.connection { case .none?, nil: return .none case .cellular?: return allowsCellularConnection ? .cellular : .none case .wifi?: return .wifi } } fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue: DispatchQueue fileprivate(set) var flags: SCNetworkReachabilityFlags? { didSet { guard flags != oldValue else { return } reachabilityChanged() } } required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { self.allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) } public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } deinit { stopNotifier() } } public extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() reachability.flags = flags } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an initial check try setReachabilityFlags() notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** @available(*, message: "Please use `connection != .none`") var isReachable: Bool { return connection != .none } @available(*, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return connection == .cellular } @available(*, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { return connection == .wifi } var description: String { guard let flags = flags else { return "unavailable flags" } let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X" let R = flags.isReachableFlagSet ? "R" : "-" let c = flags.isConnectionRequiredFlagSet ? "c" : "-" let t = flags.isTransientConnectionFlagSet ? "t" : "-" let i = flags.isInterventionRequiredFlagSet ? "i" : "-" let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-" let D = flags.isConnectionOnDemandFlagSet ? "D" : "-" let l = flags.isLocalAddressFlagSet ? "l" : "-" let d = flags.isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func setReachabilityFlags() throws { try reachabilitySerialQueue.sync { [unowned self] in var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) { self.stopNotifier() throw ReachabilityError.UnableToGetInitialFlags } self.flags = flags } } func reachabilityChanged() { let block = connection != .none ? whenReachable : whenUnreachable DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } block?(strongSelf) strongSelf.notificationCenter.post(name: .reachabilityChanged, object: strongSelf) } } } extension SCNetworkReachabilityFlags { typealias Connection = Reachability.Connection var connection: Connection { guard isReachableFlagSet else { return .none } // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi #if targetEnvironment(simulator) return .wifi #else var connection = Connection.none if !isConnectionRequiredFlagSet { connection = .wifi } if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } if isOnWWANFlagSet { connection = .cellular } return connection #endif } var isOnWWANFlagSet: Bool { #if os(iOS) return contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return contains(.isLocalAddress) } var isDirectFlagSet: Bool { return contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } } #endif
06cf4ba8673348f1fb12d4295e3ef491
33.95283
135
0.674764
false
false
false
false
pfvernon2/swiftlets
refs/heads/master
iOSX/iOS/UIColor+Utilities.swift
apache-2.0
1
// // UIColor+Utilities.swift // swiftlets // // Created by Frank Vernon on 4/30/16. // Copyright © 2016 Frank Vernon. All rights reserved. // import UIKit extension UIColor { /** Convenience initializer for creating UIColor from HTML hex formats: #RRGGBB - parameters: - htmlHex: HTML style hex description of RGB color: [#]RRGGBB[AA] - note: The leading # and trailing alpha values are optional. - returns: The color specified by the hex string or nil in the event parsing fails. */ public convenience init?(htmlHex:String) { guard let color = htmlHex.colorForHex() else { return nil } self.init(cgColor: color.cgColor) } } //Custom Colors extension UIColor { public static var random: UIColor = { UIColor(red: CGFloat.random(in: 0.0...1.0), green: CGFloat.random(in: 0.0...1.0), blue: CGFloat.random(in: 0.0...1.0), alpha: 1.0) }() public static var eigengrau: UIColor = { UIColor(red: 0.09, green: 0.09, blue: 0.11, alpha: 1.00) }() } //Color operations public extension UIColor { func lightenColor(removeSaturation val: CGFloat, resultAlpha alpha: CGFloat = -1) -> UIColor { var h: CGFloat = .zero var s: CGFloat = .zero var b: CGFloat = .zero var a: CGFloat = .zero guard getHue(&h, saturation: &s, brightness: &b, alpha: &a) else { return self } return UIColor(hue: h, saturation: max(s - val, 0.0), brightness: b, alpha: alpha == -1 ? a : alpha) } } extension String { /** Convenience method for creating UIColor from HTML hex formats: [#]RRGGBB[AA] - note: The leading # and trailing alpha values are optional. - returns: The color specified by the hex string or nil in the event parsing fails. */ public func colorForHex() -> UIColor? { //creating temp string so we can manipulate as necessary var working = self //remove leading # if present if working.hasPrefix("#") { working.remove(at: startIndex) } //ensure string fits length requirements switch working.count { case 6: //RRGGBB //add default alpha for ease of processing below working.append("FF") case 8: //RRGGBBAA break default: //ilegal lengths return nil } guard let rgbaInt:UInt32 = UInt32(working, radix: 16) else { return nil } let bytes: [UInt8] = [ UInt8(rgbaInt.bigEndian & 0xFF), UInt8(rgbaInt.bigEndian >> 8 & 0xFF), UInt8(rgbaInt.bigEndian >> 16 & 0xFF), UInt8(rgbaInt.bigEndian >> 24 & 0xFF) ] return UIColor(red: CGFloat(bytes[0])/255.0, green: CGFloat(bytes[1])/255.0, blue: CGFloat(bytes[2])/255.0, alpha: CGFloat(bytes[3])/255.0) } }
05c2fc9e03719ee0471d4637207069c9
29.62037
105
0.52404
false
false
false
false
sdhjl2000/swiftdialog
refs/heads/master
SwiftDialogExample/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import UIKit import OAuthSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UIWebViewDelegate { var window: UIWindow? var clienttoken:String? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let viewController: ViewController = ViewController() let naviController: UINavigationController = UINavigationController(rootViewController: viewController) self.window!.rootViewController = naviController self.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:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { println(url) if (url.host == "oauth-callback") { if (url.path!.hasPrefix("/twitter") || url.path!.hasPrefix("/flickr") || url.path!.hasPrefix("/fitbit") || url.path!.hasPrefix("/withings") || url.path!.hasPrefix("/linkedin") || url.path!.hasPrefix("/bitbucket") || url.path!.hasPrefix("/smugmug") || url.path!.hasPrefix("/intuit") || url.path!.hasPrefix("/zaim") || url.path!.hasPrefix("/tumblr")) { OAuth1Swift.handleOpenURL(url) } if ( url.path!.hasPrefix("/github" ) || url.path!.hasPrefix("/instagram" ) || url.path!.hasPrefix("/foursquare") || url.path!.hasPrefix("/dropbox") || url.path!.hasPrefix("/dribbble") || url.path!.hasPrefix("/salesforce") || url.path!.hasPrefix("/google") || url.path!.hasPrefix("/linkedin2")) { OAuth2Swift.handleOpenURL(url) } } else { // Google provider is the only one wuth your.bundle.id url schema. OAuth2Swift.handleOpenURL(url) } return true } }
b31a96984e1a834ed6829396c77b238f
52.197183
307
0.694731
false
false
false
false
pandazheng/Spiral
refs/heads/master
Spiral/OrdinaryHelpScene.swift
mit
1
// // HelpScene.swift // Spiral // // Created by 杨萧玉 on 14/10/19. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import SpriteKit class OrdinaryHelpScene: SKScene { func lightWithFinger(point:CGPoint){ if let light = self.childNodeWithName("light") as? SKLightNode { light.lightColor = SKColor.whiteColor() light.position = self.convertPointFromView(point) } } func turnOffLight() { (self.childNodeWithName("light") as? SKLightNode)?.lightColor = SKColor.blackColor() } func back() { Data.sharedData.gameOver = false let scene = OrdinaryModeScene(size: self.size) let push = SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 1) push.pausesIncomingScene = false self.scene?.view?.presentScene(scene, transition: push) } override func didMoveToView(view: SKView) { let bg = childNodeWithName("background") as! SKSpriteNode let w = bg.size.width let h = bg.size.height let scale = max(view.frame.width/w, view.frame.height/h) bg.xScale = scale bg.yScale = scale } }
a0370521098d9c84a49567c4e384dc1b
28.55
92
0.634518
false
false
false
false
keyOfVv/Cusp
refs/heads/master
Cusp/Sources/Extensions.swift
mit
1
// // Extensions.swift // Pods // // Created by Ke Yang on 2/20/16. // // import Foundation import CoreBluetooth public typealias UUID = CBUUID public typealias CentralManager = CBCentralManager //public typealias Peripheral = CBPeripheral public typealias Service = CBService public typealias Characteristic = CBCharacteristic public typealias Descriptor = CBDescriptor public typealias CharacteristicWriteType = CBCharacteristicWriteType // MARK: - CBUUID extension Foundation.UUID { public var hash: Int { return uuidString.hashValue } public func isEqual(_ object: Any?) -> Bool { if let other = object as? Foundation.UUID { return self.hashValue == other.hashValue } return false } } // MARK: - CBUUID extension CBUUID { open override var hash: Int { return uuidString.hashValue } open override func isEqual(_ object: Any?) -> Bool { if let other = object as? CBUUID { return self.hashValue == other.hashValue } return false } } // MARK: - CBPeripheral extension CBPeripheral { open override var hash: Int { return identifier.hashValue } open override func isEqual(_ object: Any?) -> Bool { if let other = object as? CBPeripheral { return self.hashValue == other.hashValue } return false } /// 根据UUID字符串获取对应的服务 @available(*, deprecated, message: "use Peripheral's -serviceWith(UUIDString:) method instead") private func serviceWith(UUIDString: String) -> CBService? { if let services = self.services { for aService in services { if (aService.uuid.uuidString == UUIDString) { return aService } } } return nil } /// 根据UUID字符串获取对应的特征 @available(*, deprecated, message: "use Peripheral's -characteristicWith(UUIDString:) method instead") private func characteristicWith(UUIDString: String) -> CBCharacteristic? { if let services = self.services { for aService in services { if let characteristics = aService.characteristics { for aCharacteristics in characteristics { if (aCharacteristics.uuid.uuidString == UUIDString) { return aCharacteristics } } } } } return nil } } // MARK: - CBService extension CBService { open override var hash: Int { return uuid.hashValue } open override func isEqual(_ object: Any?) -> Bool { if let other = object as? CBService { return self.hashValue == other.hashValue } return false } } // MARK: - CBCharacteristic extension CBCharacteristic { open override var hash: Int { return uuid.hashValue } open override func isEqual(_ object: Any?) -> Bool { if let other = object as? CBCharacteristic { return self.hashValue == other.hashValue } return false } } // MARK: - CBDescriptor extension CBDescriptor { open override var hash: Int { return uuid.hashValue } open override func isEqual(_ object: Any?) -> Bool { if let other = object as? CBDescriptor { return self.hashValue == other.hashValue } return false } } // MARK: - String extension String { var isValidUUID: Bool { do { // check with short pattern let shortP = "^[A-F0-9]{4}$" let shortRegex = try NSRegularExpression(pattern: shortP, options: NSRegularExpression.Options.caseInsensitive) let shortMatchNum = shortRegex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, self.characters.count)) if shortMatchNum.count == 1 { return true } // check with full pattern let fullP = "^[A-F0-9\\-]{36}$" let fullRegex = try NSRegularExpression(pattern: fullP, options: NSRegularExpression.Options.caseInsensitive) let fullMatchNum = fullRegex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, self.characters.count)) if fullMatchNum.count == 1 { return true } } catch { } return false } }
9cfef8d8c75f0eb51a82bf8175c0785e
21.074286
158
0.701786
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Morphing Oscillator.xcplaygroundpage/Contents.swift
mit
1
//: ## Morphing Oscillator //: Oscillator with four different waveforms built in. import AudioKitPlaygrounds import AudioKit import AudioKitUI var morph = AKMorphingOscillator(waveformArray: [AKTable(.sine), AKTable(.triangle), AKTable(.sawtooth), AKTable(.square)]) morph.frequency = 400 morph.amplitude = 0.1 morph.index = 0.8 AudioKit.output = morph AudioKit.start() morph.start() class LiveView: AKLiveViewController { var frequencyLabel: AKLabel? var amplitudeLabel: AKLabel? var morphIndexLabel: AKLabel? override func viewDidLoad() { addTitle("Morphing Oscillator") addView(AKButton(title: "Stop Oscillator") { button in morph.isStarted ? morph.stop() : morph.play() button.title = morph.isStarted ? "Stop Oscillator" : "Start Oscillator" }) addView(AKSlider(property: "Frequency", value: morph.frequency, range: 220 ... 880, format: "%0.2f Hz" ) { frequency in morph.frequency = frequency }) addView(AKSlider(property: "Amplitude", value: morph.amplitude) { amplitude in morph.amplitude = amplitude }) addLabel("Index: Sine = 0, Triangle = 1, Sawtooth = 2, Square = 3") addView(AKSlider(property: "Morph Index", value: morph.index, range: 0 ... 3) { index in morph.index = index }) addView(AKOutputWaveformPlot.createView(width: 440, height: 400)) } func start() { morph.play() } func stop() { morph.stop() } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
3c3f07cda5d8ef15a5b98c5d46ecdbac
28.046154
96
0.57786
false
false
false
false
A-Kod/vkrypt
refs/heads/master
Pods/SwiftyVK/Library/Sources/Errors/ApiErrorHandler.swift
apache-2.0
2
protocol ApiErrorHandler { func handle(error: ApiError) throws -> ApiErrorHandlerResult } final class ApiErrorHandlerImpl: ApiErrorHandler { private let executor: ApiErrorExecutor init(executor: ApiErrorExecutor) { self.executor = executor } func handle(error: ApiError) throws -> ApiErrorHandlerResult { switch error.code { case 5: _ = try executor.logIn(revoke: false) return .none case 14: guard let sid = error.otherInfo["captcha_sid"], let imgRawUrl = error.otherInfo["captcha_img"] else { throw VKError.api(error) } let key = try executor.captcha(rawUrlToImage: imgRawUrl, dismissOnFinish: false) return .captcha(Captcha(sid, key)) case 17: guard let rawUrl = error.otherInfo["redirect_uri"], let url = URL(string: rawUrl) else { throw VKError.api(error) } try executor.validate(redirectUrl: url) return .none default: throw VKError.api(error) } } } enum ApiErrorHandlerResult { case captcha(Captcha) case none }
de60b63bc1bef33cbb5d018aef525f3a
27.042553
92
0.538695
false
false
false
false
didisouzacosta/ASAlertViewController
refs/heads/master
ASAlertViewController/Classes/AlertController/ASHandlerButton.swift
mit
1
// // ASHandlerButton.swift // Pods // // Created by Adriano Souza Costa on 4/1/17. // // import Foundation import UIKit class ASHandlerButton: UIButton { // MARK: - Variables var onAction: (()->())? var closeOnAction: Bool = true fileprivate var alertHandler: ASAlertHandler? // MARK: - Lifecircle Class required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(frame: CGRect, handler: ASAlertHandler? = nil) { super.init(frame: frame) alertHandler = handler closeOnAction = handler?.closeOnAction ?? true updateUI() setupAction() } // MARK: - Private Methods fileprivate func updateUI() { setTitle(alertHandler?.title, for: .normal) setTitleColor(alertHandler?.type.fontStyle.color, for: .normal) titleLabel?.font = alertHandler?.type.fontStyle.font backgroundColor = .white translatesAutoresizingMaskIntoConstraints = false; heightAnchor.constraint(equalToConstant: 45).isActive = true } fileprivate func setupAction() { addTarget(self, action: #selector(callHandler), for: .touchUpInside) addTarget(self, action: #selector(drag), for: .touchDown) addTarget(self, action: #selector(drag), for: .touchDragEnter) addTarget(self, action: #selector(exitDrag), for: .touchDragExit) } @objc fileprivate func callHandler() { onAction?() alertHandler?.handler?() exitDrag() } @objc fileprivate func drag() { UIView.animate(withDuration: 0.26) { self.backgroundColor = UIColor(red: 234/255, green: 234/255, blue: 234/255, alpha: 1) } } @objc fileprivate func exitDrag() { UIView.animate(withDuration: 0.26) { self.backgroundColor = .white } } }
996ff65a2689e065f5c69e4333e59b8b
24.22973
97
0.627209
false
false
false
false
rlisle/Patriot-iOS
refs/heads/master
PatriotTests/MockHwManager.swift
bsd-3-clause
1
// // MockHwManager.swift // Patriot // // Created by Ron Lisle on 5/5/17. // Copyright © 2017 Ron Lisle. All rights reserved. // import Foundation import PromiseKit class MockHwManager: HwManager { var deviceDelegate: DeviceNotifying? var activityDelegate: ActivityNotifying? var photons: [String: Photon] = [: ] var eventName: String = "unspecified" var deviceNames: Set<String> = [] var supportedNames = Set<String>() var currentActivities: [String: Int] = [: ] func login(user: String, password: String) -> Promise<Void> { return Promise(value: ()) } func discoverDevices() -> Promise<Void> { return Promise(value: ()) } func sendCommand(activity: String, percent: Int) { } } //MARK: Testing Methods extension MockHwManager { func sendDelegateSupportedListChanged(names: Set<String>) { supportedNames = names activityDelegate?.supportedListChanged() } }
cdf1e204af7dbe850e8af514c937eb3c
19.660377
67
0.580822
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothGATT/GATTAge.swift
mit
1
// // GATTAge.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Age Age of the User. - SeeAlso: [ Age](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.age.xml) */ @frozen public struct GATTAge: GATTCharacteristic, Equatable { internal static var length: Int { return MemoryLayout<UInt8>.size } public static var uuid: BluetoothUUID { return .age } public var year: Year public init(year: Year) { self.year = year } public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let year = Year(rawValue: data[0]) self.init(year: year) } public var data: Data { return Data([year.rawValue]) } } public extension GATTAge { struct Year: BluetoothUnit, Equatable { public static var unitType: UnitIdentifier { return .year } public var rawValue: UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } } } extension GATTAge.Year: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTAge.Year: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt8) { self.init(rawValue: value) } } extension GATTAge: CustomStringConvertible { public var description: String { return year.description } }
9e9c0c37f431e9dc0d66b6617d29ddc9
19.180723
126
0.598209
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/CryptoAssets/Sources/EthereumKit/Models/Transactions/EthereumJsonRpcTransaction.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation /// A representation of a transaction that can be passed to Ethereum JSON RPC methods. /// /// All parameters are hexadecimal String values. public struct EthereumJsonRpcTransaction: Codable { /// from: DATA, 20 Bytes - The address the transaction is send from. let from: String /// to: DATA, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. let to: String? /// data: DATA - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see Ethereum Contract ABI let data: String /// gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas. let gas: String? /// gasPrice: QUANTITY - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas let gasPrice: String? /// value: QUANTITY - (optional) Integer of the value sent with this transaction let value: String? /// nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. let nonce: String? public init( from: String, to: String?, data: String, gas: String?, gasPrice: String?, value: String?, nonce: String? ) { self.from = from self.to = to self.data = data self.gas = gas self.gasPrice = gasPrice self.value = value self.nonce = nonce } }
239e61d06dc894c5851db7d0a53e17ab
32.979167
158
0.662784
false
false
false
false
WhatsTaste/WTImagePickerController
refs/heads/master
Vendor/Controllers/WTImagePickerController.swift
mit
1
// // WTImagePickerController.swift // WTImagePickerController // // Created by Jayce on 2017/2/8. // Copyright © 2017年 WhatsTaste. All rights reserved. // import UIKit public typealias WTImagePickerControllerDidFinishHandler = (_ picker: WTImagePickerController, _ images: [UIImage]) -> Void public typealias WTImagePickerControllerDidCancelHandler = (_ picker: WTImagePickerController) -> Void public let WTImagePickerControllerDisableAlphaComponent: CGFloat = 0.3 private let pickLimitDefault: Int = 0 @objc public protocol WTImagePickerControllerDelegate: NSObjectProtocol { @objc optional func imagePickerController(_ picker: WTImagePickerController, didFinishWithImages images: [UIImage]) @objc optional func imagePickerControllerDidCancel(_ picker: WTImagePickerController) } open class WTImagePickerController: UIViewController, WTAlbumViewControllerDelegate { convenience init() { self.init(nibName: nil, bundle: nil) } // MARK: - Life cycle override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.addChildViewController(contentViewController) self.view.addSubview(contentViewController.view) contentViewController.view.frame = self.view.bounds contentViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] contentViewController.didMove(toParentViewController: self) } open override var preferredStatusBarStyle: UIStatusBarStyle { return contentViewController.preferredStatusBarStyle } open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } open override var childViewControllerForStatusBarHidden: UIViewController? { let topViewController = contentViewController.topViewController return topViewController } open override var childViewControllerForStatusBarStyle: UIViewController? { let topViewController = contentViewController.topViewController return topViewController } // MARK: - WTAlbumViewControllerDelegate func albumViewController(_ controller: WTAlbumViewController, didFinishWithImages images: [UIImage]) { delegate?.imagePickerController?(self, didFinishWithImages: images) didFinishHandler?(self, images) } func albumViewControllerDidCancel(_ controller: WTAlbumViewController) { delegate?.imagePickerControllerDidCancel?(self) didCancelHandler?(self) } // MARK: - Properties @objc weak public var delegate: WTImagePickerControllerDelegate? @objc public var didFinishHandler: WTImagePickerControllerDidFinishHandler? @objc public var didCancelHandler: WTImagePickerControllerDidCancelHandler? @objc public var tintColor: UIColor = .init(red: 0, green: 122 / 255, blue: 255 / 255, alpha: 1) @objc public var pickLimit: Int = pickLimitDefault //Default is 0, which means no limit lazy private var contentViewController: UINavigationController = { let rootViewController = WTAlbumViewController(style: .plain) rootViewController.delegate = self rootViewController.tintColor = tintColor rootViewController.pickLimit = self.pickLimit let navigationController = UINavigationController(rootViewController: rootViewController) navigationController.isToolbarHidden = true navigationController.navigationBar.isTranslucent = false return navigationController }() } // MARK: - Localization public extension NSObject { func WTIPLocalizedString(_ key: String) -> String { return NSLocalizedString(key, tableName: "WTImagePickerController", bundle: Bundle(path: Bundle.main.path(forResource: "WTImagePickerController", ofType: "bundle")!)!, value: "", comment: "") } } public extension UIView { func WTIPLayoutGuide() -> Any { if #available(iOS 11.0, *) { return safeAreaLayoutGuide } else { return self } } } public extension UIColor { func WTIPReverse(alpha: CGFloat?) -> UIColor { var localAlpha: CGFloat = 0 var white: CGFloat = 0 if getWhite(&white, alpha: &localAlpha) { return UIColor(white: 1 - white, alpha: alpha ?? localAlpha) } var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &localAlpha) { return UIColor(hue: 1 - hue, saturation: 1 - saturation, brightness: 1 - brightness, alpha: alpha ?? localAlpha) } var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if getRed(&red, green: &green, blue: &blue, alpha: &localAlpha) { return UIColor(red: 1 - red, green: 1 - green, blue: 1 - blue, alpha: alpha ?? localAlpha) } return UIColor.clear } }
b75bb0d426fd49ec9ee3f6a7e925ef60
36.592593
199
0.696749
false
false
false
false
honishi/Hakumai
refs/heads/main
Hakumai/Managers/HandleNameManager/DatabaseValueCacher.swift
mit
1
// // DatabaseValueCacher.swift // Hakumai // // Created by Hiroyuki Onishi on 2021/12/28. // Copyright © 2021 Hiroyuki Onishi. All rights reserved. // import Foundation class DatabaseValueCacher<T: Equatable> { enum CacheStatus: Equatable { case cached(T?) // `.cached(nil)` means the value is cached as `nil`. case notCached } private var cache: [String: CacheStatus] = [:] func update(value: T?, for userId: String, in communityId: String) { objc_sync_enter(self) defer { objc_sync_exit(self) } let key = cacheKey(userId, communityId) let _value: CacheStatus = { guard let value = value else { return .cached(nil) } return .cached(value) }() cache[key] = _value } func updateValueAsNil(for userId: String, in communityId: String) { update(value: nil, for: userId, in: communityId) } func cachedValue(for userId: String, in communityId: String) -> CacheStatus { objc_sync_enter(self) defer { objc_sync_exit(self) } let key = cacheKey(userId, communityId) return cache[key] ?? .notCached } private func cacheKey(_ userId: String, _ communityId: String) -> String { return "\(userId):\(communityId)" } }
b455da932b598d73702384eec0ac0a3e
28.431818
81
0.615444
false
false
false
false
rugheid/Swift-MathEagle
refs/heads/master
MathEagleTests/Protocols/ExtensionsTests.swift
mit
1
// // ExtensionsTests.swift // SwiftMath // // Created by Rugen Heidbuchel on 27/01/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Cocoa import XCTest import MathEagle class ExtensionsTests: XCTestCase { func testIsNegative() { XCTAssertFalse(2.0.isNegative) XCTAssertFalse(0.0.isNegative) XCTAssertFalse(1023432.0.isNegative) XCTAssertFalse(1.4532.isNegative) XCTAssertTrue((-1.4532).isNegative) XCTAssertTrue((-1.0).isNegative) } func testIsPositive() { XCTAssertTrue(2.0.isPositive) XCTAssertFalse(0.0.isPositive) XCTAssertTrue(1023432.0.isPositive) XCTAssertTrue(1.4532.isPositive) XCTAssertFalse((-1.4532).isPositive) XCTAssertFalse((-1.0).isPositive) } func testIsNatural() { XCTAssertTrue(2.0.isNatural) XCTAssertTrue(0.0.isNatural) XCTAssertTrue(1023432.0.isNatural) XCTAssertFalse(1.4532.isNatural) XCTAssertFalse((-1.4532).isNatural) XCTAssertFalse((-1.0).isNatural) } func testIsInteger() { XCTAssertTrue(2.0.isInteger) XCTAssertTrue(0.0.isInteger) XCTAssertTrue((-2.0).isInteger) XCTAssertFalse(2.12.isInteger) XCTAssertFalse((-2.12).isInteger) } func testExtensionsDouble() { do { let x : Double = 1.0 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Double = -1.0 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Double = 3.14159 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertFalse(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Double = 0.0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsFloat() { do { let x : Float = 1.0 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Float = -1.0 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Float = 3.14159 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertFalse(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Float = 0.0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsCGFloat() { do { let x : CGFloat = 1.0 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : CGFloat = -1.0 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : CGFloat = 3.14159 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertFalse(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : CGFloat = 0.0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsInt() { do { let x : Int = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Int = -1 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Int = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsInt8() { do { let x : Int8 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Int8 = -1 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Int8 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsInt16() { do { let x : Int16 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Int16 = -1 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Int16 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsInt32() { do { let x : Int32 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Int32 = -1 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Int32 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsInt64() { do { let x : Int64 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : Int64 = -1 XCTAssertTrue(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertFalse(x.isNatural) } do { let x : Int64 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsUInt() { do { let x : UInt = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : UInt = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsUInt8() { do { let x : UInt8 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : UInt8 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsUInt16() { do { let x : UInt16 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : UInt16 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsUInt32() { do { let x : UInt32 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : UInt32 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } func testExtensionsUInt64() { do { let x : UInt64 = 1 XCTAssertFalse(x.isNegative) XCTAssertTrue(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } do { let x : UInt64 = 0 XCTAssertFalse(x.isNegative) XCTAssertFalse(x.isPositive) XCTAssertTrue(x.isInteger) XCTAssertTrue(x.isNatural) } } }
36ba1993350536b9a88a59e873789a86
28.527273
63
0.531507
false
true
false
false
AnnMic/FestivalArchitect
refs/heads/master
FestivalArchitect/Classes/Systems/PhysicalNeedSystem.swift
mit
1
// // UpdateNeedSystem.swift // FestivalArchitect // // Created by Ann Michelsen on 12/11/14. // Copyright (c) 2014 AnnMi. All rights reserved. // import Foundation class PhysicalNeedSystem : System { //TODO rename to something better let environment:Environment init (env:Environment) { environment = env } func update(dt: Float) { let entites:[Entity] = environment.entitiesWithComponent(AIComponent.self) if entites.count == 0 { return } for entity in entites { decreaseVisitorNeeds(entity) } } func decreaseVisitorNeeds(entity:Entity){ var visitor:PhysicalNeedComponent = entity.component(PhysicalNeedComponent)! if visitor.hunger > -100 { visitor.hunger-- } if visitor.fatigue > -100 { visitor.fatigue-- } if visitor.thirst > -100 { visitor.thirst-- } println("hunger \(visitor.hunger) thirst \(visitor.thirst) fatigue \(visitor.fatigue)") } }
d4a0bb6ae72c6cc4ef5789777388d5ce
19.722222
95
0.572833
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
refs/heads/master
Source/Auth/AccessToken.swift
mit
1
// Copyright 2016 Cisco Systems Inc // // 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 ObjectMapper class AccessToken: NSObject, NSCoding, Mappable { var accessTokenString: String? var accessTokenExpiration: TimeInterval? var refreshTokenString: String? var refreshTokenExpiration: TimeInterval? var accessTokenCreation: TimeInterval? var accessTokenExpirationDate: Date { return Date(timeInterval: accessTokenExpiration!, since: accessTokenCreationDate) } var accessTokenCreationDate: Date { return Date(timeIntervalSinceReferenceDate: accessTokenCreation!) } private let accessTokenKey = "accessTokenKey" private let accessTokenExpirationKey = "accessTokenExpirationKey" private let refreshTokenKey = "refreshTokenKey" private let refreshTokenExpirationKey = "refreshTokenExpirationKey" private let accessTokenCreationKey = "accessTokenCreationKey" init(accessToken: String) { self.accessTokenString = accessToken } // MARK:- Mappable required init?(map: Map) { accessTokenCreation = Date().timeIntervalSinceReferenceDate } func mapping(map: Map) { accessTokenString <- map["access_token"] accessTokenExpiration <- map["expires_in"] refreshTokenString <- map["refresh_token"] refreshTokenExpiration <- map["refresh_token_expires_in"] } // MARK:- NSCoding required init?(coder aDecoder: NSCoder) { accessTokenString = aDecoder.decodeObject(forKey: accessTokenKey) as? String accessTokenExpiration = aDecoder.decodeDouble(forKey: accessTokenExpirationKey) refreshTokenString = aDecoder.decodeObject(forKey: refreshTokenKey) as? String refreshTokenExpiration = aDecoder.decodeDouble(forKey: refreshTokenExpirationKey) accessTokenCreation = aDecoder.decodeDouble(forKey: accessTokenCreationKey) } func encode(with aCoder: NSCoder) { encodeObject(accessTokenString, forKey: accessTokenKey, aCoder: aCoder) encodeDouble(accessTokenExpiration, forKey: accessTokenExpirationKey, aCoder: aCoder) encodeObject(refreshTokenString, forKey: refreshTokenKey, aCoder: aCoder) encodeDouble(refreshTokenExpiration, forKey: refreshTokenExpirationKey, aCoder: aCoder) encodeDouble(accessTokenCreation, forKey: accessTokenCreationKey, aCoder: aCoder) } private func encodeObject(_ objv: Any?, forKey key: String, aCoder: NSCoder) { guard objv != nil else { return } aCoder.encode(objv, forKey: key) } private func encodeDouble(_ realv: Double?, forKey key: String, aCoder: NSCoder) { guard let realValue = realv else { return } aCoder.encode(realValue, forKey: key) } }
65cd8406f891ba81575920b077fc5ecd
39.854167
95
0.718001
false
false
false
false
oacastefanita/PollsFramework
refs/heads/master
Example/PollsFramework-watch Extension/PollsInterfaceController.swift
mit
1
// // InterfaceController.swift // PollsFramework-watch Extension // // Created by Stefanita Oaca on 10/09/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import WatchKit import Foundation import PollsFramework class PollsInterfaceController: WKInterfaceController { @IBOutlet var lblNoData: WKInterfaceLabel! @IBOutlet var pollsTable: WKInterfaceTable! var array: [Poll]! override func awake(withContext context: Any?) { super.awake(withContext: context) array = PollsFrameworkController.sharedInstance.dataController().getAllObjectsFor(entityName: "Poll") as! [Poll] pollsTable.setNumberOfRows(array.count, withRowType: "pollsRow") for index in 0..<array.count { if let controller = pollsTable.rowController(at: index) as? PollsRowController { controller.poll = array[index] } } lblNoData.setHidden(array.count != 0) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { let poll = array[rowIndex] if poll.pollTypeId == PollTypes.singleText.rawValue{ pushController(withName: "SingleTextPoll", context: poll) }else if poll.pollTypeId == PollTypes.bestText.rawValue{ pushController(withName: "BestTextPoll", context: poll) }else if poll.pollTypeId == PollTypes.singleImage.rawValue{ pushController(withName: "SingleImagePoll", context: poll) }else if poll.pollTypeId == PollTypes.bestImage.rawValue{ pushController(withName: "BestImagePoll", context: poll) } } }
1adaf3e69772e13a2ae18b937c9fc309
34.385965
120
0.667824
false
false
false
false
scotlandyard/expocity
refs/heads/master
expocity/Test/Model/Home/TMHome.swift
mit
1
import XCTest @testable import expocity class TMHome:XCTestCase { private var mHome:MHome? private let kRoomName:String = "MyWeirdRoomName with space" override func setUp() { super.setUp() mHome = MHome() } override func tearDown() { mHome = nil super.tearDown() } //MARK: - func testRoomOwner() { let firebaseRoom:FDatabaseModelRoom = mHome!.room() let userId:String = firebaseRoom.owner XCTAssertFalse(userId.isEmpty, "Room has no owner") } func testEmptyRoomName() { let firebaseRoom:FDatabaseModelRoom = mHome!.room() let roomName:String = firebaseRoom.name XCTAssertFalse(roomName.isEmpty, "Room name is empty") } func testRoomName() { mHome!.itemTitle.title = kRoomName let firebaseRoom:FDatabaseModelRoom = mHome!.room() let roomName:String = firebaseRoom.name XCTAssertEqual(roomName, kRoomName, "Room name mismatch") } func testAccessInvitationOnly() { let accessInvitationOnly:FDatabaseModelRoom.Access = FDatabaseModelRoom.Access.invitationOnly mHome!.itemAccess.access = accessInvitationOnly let firebaseRoom:FDatabaseModelRoom = mHome!.room() let roomAccess:FDatabaseModelRoom.Access = firebaseRoom.access XCTAssertEqual(roomAccess, accessInvitationOnly, "Room access mismatch") } func testAccessFreeJoin() { let accessFreeJoin:FDatabaseModelRoom.Access = FDatabaseModelRoom.Access.freeJoin mHome!.itemAccess.access = accessFreeJoin let firebaseRoom:FDatabaseModelRoom = mHome!.room() let roomAccess:FDatabaseModelRoom.Access = firebaseRoom.access XCTAssertEqual(roomAccess, accessFreeJoin, "Room access mismatch") } }
f632cb289e3af8212bdb45a1b97f22b0
26.884058
101
0.644491
false
true
false
false
studyYF/YueShiJia
refs/heads/master
YueShiJia/YueShiJia/Classes/Tools/YFHttpRequest.swift
apache-2.0
1
// // YFHttpRequest.swift // YueShiJia // // Created by YangFan on 2017/5/9. // Copyright © 2017年 YangFan. All rights reserved. //网络请求工具 /** 首页 https://interface.yueshichina.com/?act=app&op=index1&app_id=1002&channel=APPSTORE&client=ios&curpage=1&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&net_type=WIFI&page=10&push_id=4627676201928478325&req_time=1494315520869&token=&v=2.1.3&version=10.3.1 轮播图详情 https://interface.yueshichina.com/?act=app&op=goods_special_new&app_id=1002&channel=APPSTORE&client=ios&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&push_id=4627676201928478325&req_time=1494572577981&special_id=578&token=&v=2.1.3&version=10.3.1 */ import Foundation import Alamofire import SVProgressHUD import SwiftyJSON class YFHttpRequest { /// 单例 static let shareInstance = YFHttpRequest() /// 定义首页数据请求返回的类型 typealias homeData = ([YFHomeItem],[Banner],[YFHomeHeaderItem]) /// 网络请求基本方法 /// /// - Parameters: /// - method: 请求方式 /// - url: 地址 /// - param: 参数 /// - completion: 完成后回调 private func baseRequest(_ method: HTTPMethod = .get, url: String, param: [String: Any]? = nil, completion: @escaping(Any) -> ()) { Alamofire.request(url, method: method, parameters: param).responseJSON { (response) in //如果请求失败,则直接返回,并提示加载失败 guard response.result.isSuccess else { SVProgressHUD.showError(withStatus: "加载失败!") return } //如果有返回值,则回调 if let value = response.result.value { completion(value) } } } /// 获取首页数据 /// /// - Parameters: /// - page: 页数 /// - completion: 完成回调 public func loadHomeData(_ page: Int, completion: @escaping (homeData) -> ()) { let url = "https://interface.yueshichina.com/?act=app&op=index1&app_id=1002&channel=APPSTORE&client=ios&curpage=\(page)&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&net_type=WIFI&page=10&push_id=4627676201928478325&req_time=1494315520869&token=&v=2.1.3&version=10.3.1" baseRequest(url: url) { (response) in let dict = JSON(response) let code = dict["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showError(withStatus: "请求失败") return } if let dict = dict["datas"].dictionary { //商品数组 var homeItems = [YFHomeItem]() //广告 var banners = [Banner]() //四个分类 var headItems = [YFHomeHeaderItem]() if let home = dict["data_type"]?.arrayObject { for item in home { homeItems.append(YFHomeItem(dict: item as! [String : Any])) } } if let banner = dict["banner"]?.arrayObject { for item in banner { banners.append(Banner(dict: item as! [String : Any])) } } if let four = dict["relation_good_four"]?.arrayObject { for item in four { headItems.append(YFHomeHeaderItem(dict: item as! [String : Any])) } } completion((homeItems, banners, headItems)) } } } /// 请求专题详情数据 /// /// - Parameters: /// - special_id: 专题id /// - completion: 返回专题数据 public func loadSpecialGoodsData(_ special_id: String, completion: @escaping(YFSpecialGoodsItem) -> ()) { let url = "https://interface.yueshichina.com/?act=app&op=goods_special_new&app_id=1002&channel=APPSTORE&client=ios&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&push_id=4627676201928478325&req_time=1494572577981&special_id=\(special_id)&token=&v=2.1.3&version=10.3.1" baseRequest(url: url) { (response) in let dict = JSON(response) let code = dict["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showError(withStatus: "请求失败") return } if let dict = dict["datas"].dictionaryObject { completion(YFSpecialGoodsItem(dict: dict)) } } } /// 获取专题数据 /// /// - Parameters: /// - special_type: 专题id /// - completion: 返回专题数据 public func loadSubjectData(_ special_type: String, completion: @escaping ([NSObject]) -> ()) { let url = "https://interface.yueshichina.com/?act=app&op=special_programa&app_id=1002&channel=APPSTORE&client=ios&curpage=1&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&page=10&push_id=4627676201928478325&req_time=1494992191249&special_type=\(special_type)&token=&v=2.1.3&version=10.3.1" baseRequest(url: url) { (response) in let data = JSON(response) let code = data["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showError(withStatus: "请求失败") return } let dict = data["datas"].dictionary if let items = dict?["article_list"]?.arrayObject { var arr = [YFSubjectItem]() for item in items { arr.append(YFSubjectItem(dict: item as! [String : Any])) } completion(arr) } if let items = dict?["virtual"]?.arrayObject { var arr = [YFActiveItem]() for item in items { arr.append(YFActiveItem(dict: item as! [String : Any])) } completion(arr) } } } /// 获取店铺数据 /// /// - Parameter completion: 返回 public func loadShopData(_ completion: @escaping (ShopData) -> ()) { let url = "https://interface.yueshichina.com/?act=goods_cms_special&op=cms_special&app_id=1002&channel=APPSTORE&client=ios&curpage=1&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&push_id=4627676201928478325&req_time=1495435589585&token=&v=2.1.3&version=10.3.1" baseRequest(url: url) { (response) in let data = JSON(response) let code = data["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: "") return } if let dict = data["datas"].dictionary { var shopArr = [YFShopItem]() var bannerArr = [Banner]() var classifyArr = [ClassifyItem]() var channerItem: Channer? if let shopItems = dict["query"]?.arrayObject { for item in shopItems { shopArr.append(YFShopItem(dict: item as! [String : Any])) } } if let bannerItems = dict["banner"]?.arrayObject { for item in bannerItems { bannerArr.append(Banner(dict: item as! [String : Any])) } } if let classifyItems = dict["tag_classify"]?.arrayObject { for item in classifyItems { classifyArr.append(ClassifyItem(dict: item as! [String : Any])) } } if let channer = dict["channel"]?.dictionaryObject { channerItem = Channer(dict: channer) } completion((shopArr,bannerArr,classifyArr,channerItem!)) } } } }
712bf1a484afecd0fbcc22bcd39d582e
40.253968
343
0.552648
false
false
false
false
jovito-royeca/ManaKit
refs/heads/master
Example/ManaKit/Maintainer/Maintainer+CardsPostgres.swift
mit
1
// // Maintainer+CardsPostgres.swift // ManaKit_Example // // Created by Vito Royeca on 10/27/19. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import ManaKit import PostgresClientKit import PromiseKit extension Maintainer { func createArtistPromise(artist: String, connection: Connection) -> Promise<Void> { let names = artist.components(separatedBy: " ") var firstName = "" var lastName = "" var nameSection = "" if names.count > 1 { if let last = names.last { lastName = last nameSection = lastName } for i in 0...names.count - 2 { firstName.append("\(names[i])") if i != names.count - 2 && names.count >= 3 { firstName.append(" ") } } } else { firstName = names.first ?? "NULL" nameSection = firstName } nameSection = sectionFor(name: nameSection) ?? "NULL" let query = "SELECT createOrUpdateArtist($1,$2,$3,$4)" let parameters = [artist, firstName, lastName, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createRarityPromise(rarity: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: rarity)) let nameSection = sectionFor(name: rarity) ?? "NULL" let query = "SELECT createOrUpdateRarity($1,$2)" let parameters = [capName, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createLanguagePromise(code: String, displayCode: String, name: String, connection: Connection) -> Promise<Void> { let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateLanguage($1,$2,$3,$4)" let parameters = [code, displayCode, name, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createLayoutPromise(name: String, description_: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: name)) let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateLayout($1,$2,$3)" let parameters = [capName, nameSection, description_] return createPromise(with: query, parameters: parameters, connection: connection) } func createWatermarkPromise(name: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: name)) let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateWatermark($1,$2)" let parameters = [capName, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createFramePromise(name: String, description_: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: name)) let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateFrame($1,$2,$3)" let parameters = [capName, nameSection, description_] return createPromise(with: query, parameters: parameters, connection: connection) } func createFrameEffectPromise(id: String, name: String, description_: String, connection: Connection) -> Promise<Void> { let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateFrameEffect($1,$2,$3,$4)" let parameters = [id, name, nameSection, description_] return createPromise(with: query, parameters: parameters, connection: connection) } func createColorPromise(symbol: String, name: String, isManaColor: Bool, connection: Connection) -> Promise<Void> { let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateColor($1,$2,$3,$4)" let parameters = [symbol, name, nameSection, isManaColor] as [Any] return createPromise(with: query, parameters: parameters, connection: connection) } func createFormatPromise(name: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: name)) let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateFormat($1,$2)" let parameters = [capName, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createLegalityPromise(name: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: name)) let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateLegality($1,$2)" let parameters = [capName, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createCardTypePromise(name: String, parent: String, connection: Connection) -> Promise<Void> { let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateCardType($1,$2,$3)" let parameters = [name, nameSection, parent] return createPromise(with: query, parameters: parameters, connection: connection) } func createComponentPromise(name: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: name)) let nameSection = sectionFor(name: name) ?? "NULL" let query = "SELECT createOrUpdateComponent($1,$2)" let parameters = [capName, nameSection] return createPromise(with: query, parameters: parameters, connection: connection) } func createDeleteFacesPromise(connection: Connection) -> Promise<Void> { let query = "DELETE FROM cmcard_face" return createPromise(with: query, parameters: nil, connection: connection) } func createFacePromise(card: String, cardFace: String, connection: Connection) -> Promise<Void> { let query = "SELECT createOrUpdateCardFaces($1,$2)" let parameters = [card, cardFace] return createPromise(with: query, parameters: parameters, connection: connection) } func createDeletePartsPromise(connection: Connection) -> Promise<Void> { let query = "DELETE FROM cmcard_component_part" return createPromise(with: query, parameters: nil, connection: connection) } func createPartPromise(card: String, component: String, cardPart: String, connection: Connection) -> Promise<Void> { let capName = capitalize(string: displayFor(name: component)) let query = "SELECT createOrUpdateCardParts($1,$2,$3)" let parameters = [card, capName, cardPart] return createPromise(with: query, parameters: parameters, connection: connection) } func createOtherLanguagesPromise() -> Promise<Void> { return createPromise(with: "select createOrUpdateCardOtherLanguages()", parameters: nil, connection: nil) } func createOtherPrintingsPromise() -> Promise<Void> { return createPromise(with: "select createOrUpdateCardOtherPrintings()", parameters: nil, connection: nil) } func createVariationsPromise() -> Promise<Void> { return createPromise(with: "select createOrUpdateCardVariations()", parameters: nil, connection: nil) } func createCardPromise(dict: [String: Any], connection: Connection) -> Promise<Void> { let collectorNumber = dict["collector_number"] as? String ?? "NULL" let cmc = dict["cmc"] as? Double ?? Double(0) let flavorText = dict["flavor_text"] as? String ?? "NULL" let isFoil = dict["foil"] as? Bool ?? false let isFullArt = dict["full_art"] as? Bool ?? false let isHighresImage = dict["highres_image"] as? Bool ?? false let isNonfoil = dict["nonfoil"] as? Bool ?? false let isOversized = dict["oversized"] as? Bool ?? false let isReserved = dict["reserved"] as? Bool ?? false let isStorySpotlight = dict["story_spotlight"] as? Bool ?? false let loyalty = dict["loyalty"] as? String ?? "NULL" let manaCost = dict["mana_cost"] as? String ?? "NULL" var multiverseIds = "{}" if let a = dict["multiverse_ids"] as? [Int], !a.isEmpty { multiverseIds = "\(a)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } var myNameSection = "NULL" if let name = dict["name"] as? String { myNameSection = sectionFor(name: name) ?? "NULL" } var myNumberOrder = Double(0) if collectorNumber != "NULL" { myNumberOrder = order(of: collectorNumber) } let name = dict["name"] as? String ?? "NULL" let oracleText = dict["oracle_text"] as? String ?? "NULL" let power = dict["power"] as? String ?? "NULL" let printedName = dict["printed_name"] as? String ?? "NULL" let printedText = dict["printed_text"] as? String ?? "NULL" let toughness = dict["toughness"] as? String ?? "NULL" let arenaId = dict["arena_id"] as? String ?? "NULL" let mtgoId = dict["mtgo_id"] as? String ?? "NULL" let tcgplayerId = dict["tcgplayer_id"] as? Int ?? Int(0) let handModifier = dict["hand_modifier"] as? String ?? "NULL" let lifeModifier = dict["life_modifier"] as? String ?? "NULL" let isBooster = dict["booster"] as? Bool ?? false let isDigital = dict["digital"] as? Bool ?? false let isPromo = dict["promo"] as? Bool ?? false let releasedAt = dict["released_at"] as? String ?? "NULL" let isTextless = dict["textless"] as? Bool ?? false let mtgoFoilId = dict["mtgo_foil_id"] as? String ?? "NULL" let isReprint = dict["reprint"] as? Bool ?? false let id = dict["id"] as? String ?? "NULL" let cardBackId = dict["card_back_id"] as? String ?? "NULL" let oracleId = dict["oracle_id"] as? String ?? "NULL" let illustrationId = dict["illustration_id"] as? String ?? "NULL" let artist = dict["artist"] as? String ?? "NULL" let set = dict["set"] as? String ?? "NULL" let rarity = capitalize(string: dict["rarity"] as? String ?? "NULL") let language = dict["lang"] as? String ?? "NULL" let layout = capitalize(string: displayFor(name: dict["layout"] as? String ?? "NULL")) let watermark = capitalize(string: dict["watermark"] as? String ?? "NULL") let frame = capitalize(string: dict["frame"] as? String ?? "NULL") var frameEffects = "{}" if let a = dict["frame_effects"] as? [String], !a.isEmpty { frameEffects = "\(a)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } var colors = "{}" if let a = dict["colors"] as? [String], !a.isEmpty { colors = "\(a)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } var colorIdentities = "{}" if let a = dict["color_identity"] as? [String], !a.isEmpty { colorIdentities = "\(a)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } var colorIndicators = "{}" if let a = dict["color_indicator"] as? [String], !a.isEmpty { colorIndicators = "\(a)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } var legalities = "{}" if let legalitiesDict = dict["legalities"] as? [String: String] { var newLegalities = [String: String]() for (k,v) in legalitiesDict { newLegalities[capitalize(string: displayFor(name: k))] = capitalize(string: displayFor(name: v)) } legalities = "\(newLegalities)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } let typeLine = dict["type_line"] as? String ?? "NULL" let printedTypeLine = dict["printed_type_line"] as? String ?? "NULL" var cardtypeSubtypes = "{}" if let tl = dict["type_line"] as? String { let subtypes = extractSubtypesFrom(tl) cardtypeSubtypes = "\(subtypes)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } var cardtypeSupertypes = "{}" if let tl = dict["type_line"] as? String { let supertypes = extractSupertypesFrom(tl) cardtypeSupertypes = "\(supertypes)" .replacingOccurrences(of: "[", with: "{") .replacingOccurrences(of: "]", with: "}") } let faceOrder = dict["face_order"] as? Int ?? Int(0) // unhandled... // border_color // games // promo_types // preview.previewed_at // preview.source_uri // preview.source let query = "SELECT createOrUpdateCard($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$50,$51,$52,$53,$54)" let parameters = [collectorNumber, cmc, flavorText, isFoil, isFullArt, isHighresImage, isNonfoil, isOversized, isReserved, isStorySpotlight, loyalty, manaCost, multiverseIds, myNameSection, myNumberOrder, name, oracleText, power, printedName, printedText, toughness, arenaId, mtgoId, tcgplayerId, handModifier, lifeModifier, isBooster, isDigital, isPromo, releasedAt, isTextless, mtgoFoilId, isReprint, id, cardBackId, oracleId, illustrationId, artist, set, rarity, language, layout, watermark, frame, frameEffects, colors, colorIdentities, colorIndicators, legalities, typeLine, printedTypeLine, cardtypeSubtypes, cardtypeSupertypes, faceOrder] as [Any] return createPromise(with: query, parameters: parameters, connection: connection) } func extractImageUrls(set: String, language: String, id: String, imageUrisDict: [String: String]) -> [String: String] { var dict = [String: String]() if let artCrop = imageUrisDict["art_crop"], let u = artCrop.components(separatedBy: "?").first, let ext = u.components(separatedBy: ".").last { dict["art_crop"] = "\(set)/\(language)/\(id)/art_crop.\(ext)" } if let normal = imageUrisDict["normal"], let u = normal.components(separatedBy: "?").first, let ext = u.components(separatedBy: ".").last { dict["normal"] = "\(set)/\(language)/\(id)/normal.\(ext)" } return dict } }
a9f3be3d102a9a4c9ce4aa3fba074c86
41.413242
255
0.498089
false
false
false
false
alirsamar/BiOS
refs/heads/master
Alien Adventure/UDCollision.swift
mit
3
// // UDCollision.swift // Alien Adventure // // Created by Jarrod Parkes on 10/1/15. // Copyright © 2015 Udacity. All rights reserved. // import SpriteKit // MARK: - UDCollisionCategory enum UDCollisionCategory: UInt32 { case Player = 1 case World = 2 } // MARK: - UDCollision class UDCollision { class func setCollisionForPhysicsBody(physicsBody: SKPhysicsBody, belongsToMask: UDCollisionCategory, contactWithMask: UDCollisionCategory, dynamic: Bool = false) { physicsBody.dynamic = dynamic physicsBody.affectedByGravity = false physicsBody.allowsRotation = false physicsBody.usesPreciseCollisionDetection = true physicsBody.categoryBitMask = belongsToMask.rawValue physicsBody.collisionBitMask = 0 physicsBody.contactTestBitMask = contactWithMask.rawValue } }
87f757b7e6f2f3c50eeb199cb01e9fec
26.645161
168
0.716453
false
false
false
false
onmyway133/Xmas
refs/heads/master
Xmas/NSObject_Extension.swift
mit
1
// // NSObject_Extension.swift // // Created by Khoa Pham on 12/18/15. // Copyright © 2015 Fantageek. All rights reserved. // import Foundation extension NSObject { class func pluginDidLoad(bundle: NSBundle) { let appName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? NSString if appName == "Xcode" { if sharedPlugin == nil { sharedPlugin = Xmas(bundle: bundle) } } } }
806eda5c77d74dd24ccfca24302091fc
22.631579
88
0.620536
false
false
false
false
ragnar/VindsidenApp
refs/heads/develop
watchkitapp Extension/ExtensionDelegate.swift
bsd-2-clause
1
// // ExtensionDelegate.swift // VindsidenApp // // Created by Ragnar Henriksen on 10.06.15. // Copyright © 2015 RHC. All rights reserved. // import WatchKit import VindsidenWatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { var timestamp: TimeInterval = 0 func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { WCFetcher.sharedInstance.activate() scheduleRefresh() if Date().timeIntervalSinceReferenceDate < timestamp + 60 { return } timestamp = Date().timeIntervalSinceReferenceDate DataManager.shared.cleanupPlots { () -> Void in NotificationCenter.default.post(name: Notification.Name.FetchingPlots, object: nil) WindManager.sharedManager.fetch({ (result: WindManagerResult) -> Void in NotificationCenter.default.post(name: Notification.Name.ReceivedPlots, object: nil) }) } } func applicationWillResignActive() { PlotFetcher.invalidate() StationFetcher.invalidate() } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. for task in backgroundTasks { // Use a switch statement to check the task type switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: // Be sure to complete the background task once you’re done. if (WKExtension.shared().applicationState != .background) { if #available(watchOSApplicationExtension 4.0, *) { backgroundTask.setTaskCompletedWithSnapshot(false) } else { backgroundTask.setTaskCompleted() } return } WindManager.sharedManager.fetch({ (result: WindManagerResult) -> Void in NotificationCenter.default.post(name: Notification.Name.ReceivedPlots, object: nil) if #available(watchOSApplicationExtension 4.0, *) { backgroundTask.setTaskCompletedWithSnapshot(false) } else { backgroundTask.setTaskCompleted() } self.scheduleRefresh() }) // case let snapshotTask as WKSnapshotRefreshBackgroundTask: // // Snapshot tasks have a unique completion call, make sure to set your expiration date // snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) // case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: // // Be sure to complete the connectivity task once you’re done. // connectivityTask.setTaskCompleted() // case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // // Be sure to complete the URL session task once you’re done. // urlSessionTask.setTaskCompleted() default: // make sure to complete unhandled task types if #available(watchOSApplicationExtension 4.0, *) { task.setTaskCompletedWithSnapshot(false) } else { task.setTaskCompleted() } } } } func scheduleRefresh() { // let fireDate = Date(timeIntervalSinceNow: 60.0*30.0) // let userInfo = ["reason" : "background update"] as NSDictionary // // WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo) { (error) in // if error != nil { // DLOG("Schedule background failed: \(String(describing: error))") // } // } } }
9c07c2b0a2f2efef9b6f9cf66c075737
37.386792
160
0.605308
false
false
false
false
AmitaiB/MyPhotoViewer
refs/heads/master
Acornote_iOS/Pods/Cache/Source/Shared/Library/ImageWrapper.swift
apache-2.0
3
import Foundation public struct ImageWrapper: Codable { public let image: Image public enum CodingKeys: String, CodingKey { case image } public init(image: Image) { self.image = image } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let data = try container.decode(Data.self, forKey: CodingKeys.image) guard let image = Image(data: data) else { throw StorageError.decodingFailed } self.image = image } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) guard let data = image.cache_toData() else { throw StorageError.encodingFailed } try container.encode(data, forKey: CodingKeys.image) } }
5e4e725be5d3133604719842d2c15325
23.78125
72
0.696091
false
false
false
false
ekgorter/MyWikiTravel
refs/heads/master
MyWikiTravel/MyWikiTravel/SearchViewController.swift
unlicense
1
// // SearchViewController.swift // MyWikiTravel // // Created by Elias Gorter on 04-06-15. // Copyright (c) 2015 EliasGorter6052274. All rights reserved. // // Allows user to search wikitravel.org for articles. Search results are displayed in table. import UIKit class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, MediaWikiAPIProtocol { var searchResults = [Searchresult]() var guide: Guide! let cellIdentifier = "searchResultCell" var api: MediaWikiAPI! @IBOutlet weak var articleSearchBar: UISearchBar! @IBOutlet weak var searchResultsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Uses the MediaWiki API to get data from wikitravel.org. api = MediaWikiAPI(delegate: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } // Show search results in cells of tableview. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! UITableViewCell! let article = searchResults[indexPath.row] cell.textLabel?.text = article.title return cell } // Displays the the results of the inputted search term in the tableview. func searchAPIResults(searchResult: NSArray) { dispatch_async(dispatch_get_main_queue(), { self.searchResults = Searchresult.searchresultsFromJson(searchResult, guide: self.guide) self.searchResultsTableView!.reloadData() }) } // Searches wikitravel.org with inputted search term. func searchBarSearchButtonClicked(searchBar: UISearchBar) { api.searchWikiTravel(articleSearchBar.text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!) } // Displays selected article contents in new view. override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let articleViewController: ArticleViewController = segue.destinationViewController as? ArticleViewController { var articleIndex = searchResultsTableView!.indexPathForSelectedRow()!.row articleViewController.onlineSource = true articleViewController.article = searchResults[articleIndex] } } }
542a9c603f55a37271dfad89970cea76
37.746269
133
0.71379
false
false
false
false
bradhilton/OrderedSet
refs/heads/master
Sources/OrderedSet+Set.swift
mit
1
// // OrderedSet+Set.swift // OrderedSet // // Created by Bradley Hilton on 2/20/16. // Copyright © 2016 Brad Hilton. All rights reserved. // let set = Swift.Set<String>() extension OrderedSet { public init(minimumCapacity: Int) { self.array = [] self.set = Set(minimumCapacity: minimumCapacity) reserveCapacity(minimumCapacity) } /// Returns `true` if the ordered set contains a member. public func contains(_ member: Element) -> Bool { return set.contains(member) } /// Remove the member from the ordered set and return it if it was present. public mutating func remove(_ member: Element) -> Element? { guard let index = array.firstIndex(of: member) else { return nil } set.remove(member) return array.remove(at: index) } /// Returns true if the ordered set is a subset of a finite sequence as a `Set`. public func isSubset<S : Sequence>(of sequence: S) -> Bool where S.Iterator.Element == Element { return set.isSubset(of: sequence) } /// Returns true if the ordered set is a subset of a finite sequence as a `Set` /// but not equal. public func isStrictSubset<S : Sequence>(of sequence: S) -> Bool where S.Iterator.Element == Element { return set.isStrictSubset(of: sequence) } /// Returns true if the ordered set is a superset of a finite sequence as a `Set`. public func isSuperset<S : Sequence>(of sequence: S) -> Bool where S.Iterator.Element == Element { return set.isSuperset(of: sequence) } /// Returns true if the ordered set is a superset of a finite sequence as a `Set` /// but not equal. public func isStrictSuperset<S : Sequence>(of sequence: S) -> Bool where S.Iterator.Element == Element { return set.isStrictSuperset(of: sequence) } /// Returns true if no members in the ordered set are in a finite sequence as a `Set`. public func isDisjoint<S : Sequence>(with sequence: S) -> Bool where S.Iterator.Element == Element { return set.isDisjoint(with: sequence) } /// Return a new `OrderedSet` with items in both this set and a finite sequence. public func union<S : Sequence>(_ sequence: S) -> OrderedSet where S.Iterator.Element == Element { return copy(self) { (set: inout OrderedSet) in set.formUnion(sequence) } } /// Append elements of a finite sequence into this `OrderedSet`. public mutating func formUnion<S : Sequence>(_ sequence: S) where S.Iterator.Element == Element { append(contentsOf: sequence) } /// Return a new ordered set with elements in this set that do not occur /// in a finite sequence. public func subtracting<S : Sequence>(_ sequence: S) -> OrderedSet where S.Iterator.Element == Element { return copy(self) { (set: inout OrderedSet) in set.subtract(sequence) } } /// Remove all members in the ordered set that occur in a finite sequence. public mutating func subtract<S : Sequence>(_ sequence: S) where S.Iterator.Element == Element { set.subtract(sequence) array = array.filter { set.contains($0) } } /// Return a new ordered set with elements common to this ordered set and a finite sequence. public func intersection<S : Sequence>(_ sequence: S) -> OrderedSet where S.Iterator.Element == Element { return copy(self) { (set: inout OrderedSet) in set.formIntersection(sequence) } } /// Remove any members of this ordered set that aren't also in a finite sequence. public mutating func formIntersection<S : Sequence>(_ sequence: S) where S.Iterator.Element == Element { set.formIntersection(sequence) array = array.filter { set.contains($0) } } /// Return a new ordered set with elements that are either in the ordered set or a finite /// sequence but do not occur in both. public func symmetricDifference<S : Sequence>(_ sequence: S) -> OrderedSet where S.Iterator.Element == Element { return copy(self) { (set: inout OrderedSet) in set.formSymmetricDifference(sequence) } } /// For each element of a finite sequence, remove it from the ordered set if it is a /// common element, otherwise add it to the ordered set. Repeated elements of the /// sequence will be ignored. public mutating func formSymmetricDifference<S : Sequence>(_ sequence: S) where S.Iterator.Element == Element { set.formSymmetricDifference(sequence) let (array, _) = collapse(self.array + sequence) self.array = array.filter { set.contains($0) } } /// If `!self.isEmpty`, remove the first element and return it, otherwise /// return `nil`. public mutating func popFirst() -> Element { guard let first = array.first else { fatalError() } set.remove(first) return array.removeFirst() } }
f52d315878a4b2e4fd51f034f59ead4d
38.91129
116
0.655688
false
false
false
false
brocktonpoint/CawBoxKit
refs/heads/master
CawBoxKitTests/BinaryValueArrayTest.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 CawBox 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 XCTest import CoreLocation @testable import CawBoxKit class BinaryValueArrayTest: XCTestCase { func testCoreLocationBinaryArray () { var input = [ CLLocationCoordinate2D (latitude: 49.287, longitude: 123.12), CLLocationCoordinate2D (latitude: 49.3, longitude: 123.2), CLLocationCoordinate2D (latitude: 49.1, longitude: 123.0) ] let data = NSData (bytes: &input, length: input.count * sizeof (CLLocationCoordinate2D)) let output = BinaryValueArray<CLLocationCoordinate2D> (data: data, zeroValue: kCLLocationCoordinate2DInvalid).results XCTAssert (input.count == output.count, "Input != Output Count") for (index, location) in input.enumerated () { XCTAssert (location.latitude == output[index].latitude && location.longitude == output[index].longitude, "Input[\(index)] != Output[\(index)] Count") } } }
d466bfa774881e041a1a95e7450a81e3
42.212766
161
0.731034
false
true
false
false
looker-open-source/sdk-codegen
refs/heads/main
examples/swift/sample-swift-sdk/sample-swift-sdk/LookerSwiftSDK/partial.swift
mit
3
// from https://josephduffy.co.uk/partial-in-swift // TODO not currently used and not sure it makes sense import Foundation struct Partial<Wrapped>: CustomStringConvertible, CustomDebugStringConvertible { enum Error<ValueType>: Swift.Error { case missingKey(KeyPath<Wrapped, ValueType>) case invalidValueType(key: KeyPath<Wrapped, ValueType>, actualValue: Any) } private var values: [PartialKeyPath<Wrapped>: Any?] = [:] private var backingValue: Wrapped? = nil var description: String { let backingValueDescription: String if let backingValue = backingValue as? CustomStringConvertible { backingValueDescription = backingValue.description } else { backingValueDescription = String(describing: backingValue) } return "<\(type(of: self)) values=\(values.description); backingValue=\(backingValueDescription)>" } var debugDescription: String { if let backingValue = backingValue { return debugDescription(utilising: backingValue) } else { return "<\(type(of: self)) values=\(values.debugDescription); backingValue=\(backingValue.debugDescription))>" } } init(backingValue: Wrapped? = nil) { self.backingValue = backingValue } func value<ValueType>(for key: KeyPath<Wrapped, ValueType>) throws -> ValueType { if let value = values[key] { if let value = value as? ValueType { return value } else if let value = value { throw Error.invalidValueType(key: key, actualValue: value) } } else if let value = backingValue?[keyPath: key] { return value } throw Error.missingKey(key) } func value<ValueType>(for key: KeyPath<Wrapped, ValueType?>) throws -> ValueType { if let value = values[key] { if let value = value as? ValueType { return value } else if let value = value { throw Error.invalidValueType(key: key, actualValue: value) } } else if let value = backingValue?[keyPath: key] { return value } throw Error.missingKey(key) } func value<ValueType>(for key: KeyPath<Wrapped, ValueType>) throws -> ValueType where ValueType: PartialConvertible { if let value = values[key] { if let value = value as? ValueType { return value } else if let partial = value as? Partial<ValueType> { return try ValueType(partial: partial) } else if let value = value { throw Error.invalidValueType(key: key, actualValue: value) } } else if let value = backingValue?[keyPath: key] { return value } throw Error.missingKey(key) } func value<ValueType>(for key: KeyPath<Wrapped, ValueType?>) throws -> ValueType where ValueType: PartialConvertible { if let value = values[key] { if let value = value as? ValueType { return value } else if let partial = value as? Partial<ValueType> { return try ValueType(partial: partial) } else if let value = value { throw Error.invalidValueType(key: key, actualValue: value) } } else if let value = backingValue?[keyPath: key] { return value } throw Error.missingKey(key) } subscript<ValueType>(key: KeyPath<Wrapped, ValueType>) -> ValueType? { get { return try? value(for: key) } set { /** Uses `updateValue(_:forKey:)` to ensure the value is set to `nil`. When the subscript is used the key is removed from the dictionary. This ensures that the `backingValue`'s value will not be used when a `backingValue` is set and a key is explicitly set to `nil` */ values.updateValue(newValue, forKey: key) } } subscript<ValueType>(key: KeyPath<Wrapped, ValueType?>) -> ValueType? { get { return try? value(for: key) } set { values.updateValue(newValue, forKey: key) } } subscript<ValueType>(key: KeyPath<Wrapped, ValueType>) -> Partial<ValueType> where ValueType: PartialConvertible { get { if let value = try? self.value(for: key) { return Partial<ValueType>(backingValue: value) } else if let partial = values[key] as? Partial<ValueType> { return partial } else { return Partial<ValueType>() } } set { values.updateValue(newValue, forKey: key) } } subscript<ValueType>(key: KeyPath<Wrapped, ValueType?>) -> Partial<ValueType> where ValueType: PartialConvertible { get { if let value = try? self.value(for: key) { return Partial<ValueType>(backingValue: value) } else if let partial = values[key] as? Partial<ValueType> { return partial } else { return Partial<ValueType>() } } set { values.updateValue(newValue, forKey: key) } } } extension Partial { func debugDescription(utilising instance: Wrapped) -> String { var namedValues: [String: Any] = [:] var unnamedValues: [PartialKeyPath<Wrapped>: Any] = [:] let mirror = Mirror(reflecting: instance) for (key, value) in self.values { var foundKey = false for child in mirror.children { if let propertyName = child.label { foundKey = (value as AnyObject) === (child.value as AnyObject) if foundKey { namedValues[propertyName] = value break } } } if !foundKey { unnamedValues[key] = value } } return "<\(type(of: self)) values=\(namedValues.debugDescription), \(unnamedValues.debugDescription); backingValue=\(backingValue.debugDescription))>" } } extension Partial where Wrapped: PartialConvertible { var debugDescription: String { if let instance = try? Wrapped(partial: self) { return debugDescription(utilising: instance) } else { return "<\(type(of: self)) values=\(values.debugDescription); backingValue=\(backingValue.debugDescription))>" } } } protocol PartialConvertible { init(partial: Partial<Self>) throws }
13b91dd375be192c2fd8bdbb0b79bf99
31.781553
158
0.573375
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/IDE/print_omit_needless_words.swift
apache-2.0
9
// RUN: %empty-directory(%t) // REQUIRES: objc_interop // FIXME: this is failing on simulators // REQUIRES: OS=macosx // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ObjectiveC -function-definitions=false -prefer-type-repr=true > %t.ObjectiveC.txt // RUN: %FileCheck %s -check-prefix=CHECK-OBJECTIVEC -strict-whitespace < %t.ObjectiveC.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true -skip-unavailable -skip-parameter-names > %t.Foundation.txt // RUN: %FileCheck %s -check-prefix=CHECK-FOUNDATION -strict-whitespace < %t.Foundation.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/../ClangImporter/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=CoreCooling -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.CoreCooling.txt // RUN: %FileCheck %s -check-prefix=CHECK-CORECOOLING -strict-whitespace < %t.CoreCooling.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=OmitNeedlessWords -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.OmitNeedlessWords.txt 2> %t.OmitNeedlessWords.diagnostics.txt // RUN: %FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS -strict-whitespace < %t.OmitNeedlessWords.txt // RUN: %FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS-DIAGS -strict-whitespace < %t.OmitNeedlessWords.diagnostics.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=errors -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.errors.txt // RUN: %FileCheck %s -check-prefix=CHECK-ERRORS -strict-whitespace < %t.errors.txt // Note: SEL -> "Selector" // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector) // Note: "with" parameters. // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: Any?) // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: Any?, with: Any?) // Note: don't prefix-strip swift_bridged classes or their subclasses. // CHECK-FOUNDATION: func mutableCopy() -> NSMutableArray // Note: id -> "Object". // CHECK-FOUNDATION: func index(of: Any) -> Int // Note: Class -> "Class" // CHECK-OBJECTIVEC: func isKind(of aClass: AnyClass) -> Bool // Note: Pointer-to-struct name matching; preposition splitting. // // CHECK-FOUNDATION: func copy(with: NSZone? = nil) -> Any! // Note: Objective-C type parameter names. // CHECK-FOUNDATION: func object(forKey: NSCopying) -> Any? // CHECK-FOUNDATION: func removeObject(forKey: NSCopying) // Note: Don't drop the name of the first parameter in an initializer entirely. // CHECK-FOUNDATION: init(array: [Any]) // Note: struct name matching; don't drop "With". // CHECK-FOUNDATION: func withRange(_: NSRange) -> NSValue // Note: built-in types. // CHECK-FOUNDATION: func add(_: Double) -> NSNumber // Note: built-in types. // CHECK-FOUNDATION: func add(_: Bool) -> NSNumber // Note: builtin-types. // CHECK-FOUNDATION: func add(_: UInt16) -> NSNumber // Note: builtin-types. // CHECK-FOUNDATION: func add(_: Int32) -> NSNumber // Note: Typedefs with a "_t" suffix". // CHECK-FOUNDATION: func subtract(_: Int32) -> NSNumber // Note: Respect the getter name for BOOL properties. // CHECK-FOUNDATION: var isMakingHoney: Bool // Note: multi-word enum name matching; "with" splits the first piece. // CHECK-FOUNDATION: func someMethod(deprecatedOptions: NSDeprecatedOptions = []) // Note: class name matching; don't drop "With". // CHECK-FOUNDATION: func withString(_: String!) -> Self! // Note: lowercasing enum constants. // CHECK-FOUNDATION: enum CountStyle : Int { // CHECK-FOUNDATION: case file // CHECK-FOUNDATION-NEXT: case memory // CHECK-FOUNDATION-NEXT: case decimal // CHECK-FOUNDATION-NEXT: case binary // Note: Make sure NSURL works in various places // CHECK-FOUNDATION: open(_: NSURL!, completionHandler: ((Bool) -> Void)!) // Note: property name stripping property type. // CHECK-FOUNDATION: var uppercased: String // Note: ok to map base name down to a keyword. // CHECK-FOUNDATION: func `do`(_: Selector!) // Note: Strip names preceded by a gerund. // CHECK-FOUNDATION: func startSquashing(_: Bee) // CHECK-FOUNDATION: func startSoothing(_: Bee) // CHECK-FOUNDATION: func startShopping(_: Bee) // Note: Removing plural forms when working with collections // CHECK-FOUNDATION: func add(_: [Any]) // Note: Int and Index match. // CHECK-FOUNDATION: func slice(from: Int, to: Int) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func appending(_: String) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func withString(_: String) -> String // Note: Noun phrase puts preposition inside. // CHECK-FOUNDATION: func url(withAddedString: String) -> NSURL? // Note: NSCalendarUnits is not a set of "Options". // CHECK-FOUNDATION: func forCalendarUnits(_: NSCalendar.Unit) -> String! // Note: <property type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: var deletingLastPathComponent: NSURL? { get } // Note: <property type><preposition> --> <preposition>. // CHECK-FOUNDATION: var withHTTPS: NSURL { get } // Note: lowercasing option set values // CHECK-FOUNDATION: struct NSEnumerationOptions // CHECK-FOUNDATION: static var concurrent: NSEnumerationOptions // CHECK-FOUNDATION: static var reverse: NSEnumerationOptions // Note: usingBlock -> body // CHECK-FOUNDATION: func enumerateObjects(_: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // CHECK-FOUNDATION: func enumerateObjects(options: NSEnumerationOptions = [], using: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // Note: WithBlock -> body, nullable closures default to nil. // CHECK-FOUNDATION: func enumerateObjectsRandomly(block: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)? = nil) // Note: id<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomething(with: NSCopying) // Note: NSObject<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomethingElse(with: NSCopying & NSObjectProtocol) // Note: Function type -> "Function". // CHECK-FOUNDATION: func sort(_: @escaping @convention(c) (AnyObject, AnyObject) -> Int) // Note: Plural: NSArray without type arguments -> "Objects". // CHECK-FOUNDATION: func remove(_: [Any]) // Note: Skipping "Type" suffix. // CHECK-FOUNDATION: func doSomething(with: NSUnderlyingType) // Don't introduce default arguments for lone parameters to setters. // CHECK-FOUNDATION: func setDefaultEnumerationOptions(_: NSEnumerationOptions) // CHECK-FOUNDATION: func normalizingXMLPreservingComments(_: Bool) // Collection element types. // CHECK-FOUNDATION: func adding(_: Any) -> Set<AnyHashable> // Boolean properties follow the getter. // CHECK-FOUNDATION: var empty: Bool { get } // CHECK-FOUNDATION: func nonEmpty() -> Bool // CHECK-FOUNDATION: var isStringSet: Bool { get } // CHECK-FOUNDATION: var wantsAUnion: Bool { get } // CHECK-FOUNDATION: var watchesItsLanguage: Bool { get } // CHECK-FOUNDATION: var appliesForAJob: Bool { get } // CHECK-FOUNDATION: var setShouldBeInfinite: Bool { get } // "UTF8" initialisms. // CHECK-FOUNDATION: init?(utf8String: UnsafePointer<Int8>!) // Don't strip prefixes from globals. // CHECK-FOUNDATION: let NSGlobalConstant: String // CHECK-FOUNDATION: func NSGlobalFunction() // Cannot strip because we end up with something that isn't an identifier // CHECK-FOUNDATION: func NS123() // CHECK-FOUNDATION: func NSYELLING() // CHECK-FOUNDATION: func NS_SCREAMING() // CHECK-FOUNDATION: func NS_() // CHECK-FOUNDATION: let NSHTTPRequestKey: String // Lowercasing initialisms with plurals. // CHECK-FOUNDATION: var urlsInText: [NSURL] { get } // Don't strip prefixes from macro names. // CHECK-FOUNDATION: var NSTimeIntervalSince1970: Double { get } // CHECK-FOUNDATION: var NS_DO_SOMETHING: Int // Note: no lowercasing of initialisms when there might be a prefix. // CHECK-CORECOOLING: func CFBottom() -> // Note: Skipping over "Ref" // CHECK-CORECOOLING: func replace(_: CCPowerSupply!) // CHECK-OMIT-NEEDLESS-WORDS: struct OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var sideToSide: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var backAndForth: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var toXMLHex: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: func jump(to: NSURL) // CHECK-OMIT-NEEDLESS-WORDS: func objectIs(compatibleWith: Any) -> Bool // CHECK-OMIT-NEEDLESS-WORDS: func insetBy(x: Int, y: Int) // CHECK-OMIT-NEEDLESS-WORDS: func setIndirectlyToValue(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func jumpToTop(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func removeWithNoRemorse(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func bookmark(with: [NSURL]) // CHECK-OMIT-NEEDLESS-WORDS: func save(to: NSURL, forSaveOperation: Int) // CHECK-OMIT-NEEDLESS-WORDS: func index(withItemNamed: String) // CHECK-OMIT-NEEDLESS-WORDS: func methodAndReturnError(_: AutoreleasingUnsafeMutablePointer<NSError?>!) // CHECK-OMIT-NEEDLESS-WORDS: func type(of: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofNamedString: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofTypeNamed: String) // Look for preposition prior to "of". // CHECK-OMIT-NEEDLESS-WORDS: func append(withContentsOf: String) // Leave subscripts alone // CHECK-OMIT-NEEDLESS-WORDS: subscript(_: UInt) -> Any { get } // CHECK-OMIT-NEEDLESS-WORDS: func objectAtIndexedSubscript(_: UInt) -> Any // CHECK-OMIT-NEEDLESS-WORDS: func exportPresets(bestMatching: String) // CHECK-OMIT-NEEDLESS-WORDS: func `is`(compatibleWith: String) // CHECK-OMIT-NEEDLESS-WORDS: func add(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func slobbering(_: String) -> OmitNeedlessWords // Elements of C array types // CHECK-OMIT-NEEDLESS-WORDS: func drawPolygon(with: UnsafePointer<NSPoint>!, count: Int) // Typedef ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func drawFilledPolygon(with: NSPointArray!, count: Int) // Non-parameterized Objective-C class ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func draw(_: SEGreebieArray) // "bound by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(boundBy: Int) // "separated by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(separatedBy: Int) // "Property"-like stripping for "set" methods. // CHECK-OMIT-NEEDLESS-WORDS: class func current() -> OmitNeedlessWords // CHECK-OMIT-NEEDLESS-WORDS: class func setCurrent(_: OmitNeedlessWords) // Don't split "PlugIn". // CHECK-OMIT-NEEDLESS-WORDS: func compilerPlugInValue(_: Int) // Don't strip away argument label completely when there is a default // argument. // CHECK-OMIT-NEEDLESS-WORDS: func wobble(options: OMWWobbleOptions = []) // Property-name sensitivity in the base name "Self" stripping. // CHECK-OMIT-NEEDLESS-WORDS: func addDoodle(_: ABCDoodle) // Protocols as contexts // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWLanding { // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func flip() // Verify that we get the Swift name from the original declaration. // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWWiggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func wiggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "wiggle1()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func conflicting1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "wiggleProp1") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var conflictingProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWWaggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func waggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "waggle1()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func conflicting1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var waggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "waggleProp1") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var conflictingProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: class OMWSuper // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "jump()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jumpSuper() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: class OMWSub // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "jump()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jumpSuper() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C method 'conflicting1' in 'OMWSub' ('waggle1()' in 'OMWWaggle' vs. 'wiggle1()' in 'OMWWiggle') // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C property 'conflictingProp1' in 'OMWSub' ('waggleProp1' in 'OMWWaggle' vs. 'wiggleProp1' in 'OMWSuper') // Don't drop the 'error'. // CHECK-ERRORS: func tryAndReturnError(_: ()) throws
4b3fb8adc74a2a1a2f46c3f5f4576c3e
45.1
322
0.733116
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
refs/heads/master
TrolleyTracker/Controllers/UI/MapContainer/MapViewDelegate.swift
mit
1
// // MapViewDelegate.swift // TrolleyTracker // // Created by Austin Younts on 10/11/15. // Copyright © 2015 Code For Greenville. All rights reserved. // import MapKit class TrolleyMapViewDelegate: NSObject, MKMapViewDelegate { private enum Identifiers { static let trolley = "TrolleyAnnotation" static let stop = "StopAnnotation" static let user = "UserAnnotation" } typealias MapViewSelectionAction = (_ annotationView: MKAnnotationView) -> Void var annotationSelectionAction: MapViewSelectionAction? var annotationDeselectionAction: MapViewSelectionAction? var shouldShowCallouts: Bool = false var highlightedRoute: TrolleyRoute? var highlightedTrolley: Trolley? var shouldDimStops: Bool = false func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // User if (annotation is MKUserLocation) { let view = mapView.dequeueAnnotationView(ofType: MKAnnotationView.self, for: annotation) let image = UIImage.ttUserPin view.image = image view.centerOffset = CGPoint(x: 0, y: -(image.size.height / 2)) view.annotation = annotation return view } // Trolley Stops if annotation is TrolleyStop { let view = mapView.dequeueAnnotationView(ofType: TrolleyStopAnnotationView.self, for: annotation) view.frame = CGRect(x: 0, y: 0, width: 22, height: 22) view.canShowCallout = shouldShowCallouts view.annotation = annotation view.tintColor = UIColor(white: 0.3, alpha: 1) view.alpha = shouldDimStops ? .fadedStop : .unfadedStop return view } // Trolleys if let trolleyAnnotation = annotation as? Trolley { let view = mapView.dequeueAnnotationView(ofType: TrolleyAnnotationView.self, for: annotation) view.frame = CGRect(x: 0, y: 0, width: 60, height: 60) view.tintColor = trolleyAnnotation.tintColor view.trolleyName = trolleyAnnotation.displayNameShort view.annotation = trolleyAnnotation if let highlighted = highlightedTrolley { view.alpha = highlighted.ID == trolleyAnnotation.ID ? .unfadedTrolley : .fadedTrolley } else { // No highlighted Trolley, all should be equal view.alpha = .unfadedTrolley } return view } return nil } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.lineWidth = 4.0 guard let routeOverlay = overlay as? TrolleyRouteOverlay else { return renderer } renderer.strokeColor = routeOverlay.color if let highlighted = highlightedRoute { renderer.alpha = highlighted.color == routeOverlay.color ? .unfadedRoute : .fadedRoute } return renderer } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { annotationSelectionAction?(view) } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { self.deSelectIfNeeded(mapView, view: view) } } private func deSelectIfNeeded(_ mapView: MKMapView, view: MKAnnotationView) { guard mapView.selectedAnnotations.isEmpty else { return } annotationDeselectionAction?(view) } } extension MKMapView { func dequeueAnnotationView<T>(ofType type: T.Type, for annotation: MKAnnotation) -> T where T: MKAnnotationView { let id = String(describing: type) let view = dequeueReusableAnnotationView(withIdentifier: id) if let typedView = view as? T { return typedView } return T(annotation: annotation, reuseIdentifier: id) } }
962076cfcbc205aa706bc97eb1d7bc24
30.891304
101
0.591911
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPosix/SelectableEventLoop.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Dispatch import NIOCore import NIOConcurrencyHelpers import _NIODataStructures import Atomics /// Execute the given closure and ensure we release all auto pools if needed. @inlinable internal func withAutoReleasePool<T>(_ execute: () throws -> T) rethrows -> T { #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) return try autoreleasepool { try execute() } #else return try execute() #endif } /// `EventLoop` implementation that uses a `Selector` to get notified once there is more I/O or tasks to process. /// The whole processing of I/O and tasks is done by a `NIOThread` that is tied to the `SelectableEventLoop`. This `NIOThread` /// is guaranteed to never change! @usableFromInline internal final class SelectableEventLoop: EventLoop { static let strictModeEnabled: Bool = { switch getenv("SWIFTNIO_STRICT").map({ String.init(cString: $0).lowercased() }) { case "true", "y", "yes", "on", "1": return true default: return false } }() /// The different state in the lifecycle of an `EventLoop` seen from _outside_ the `EventLoop`. private enum ExternalState { /// `EventLoop` is open and so can process more work. case open /// `EventLoop` is currently in the process of closing. case closing /// `EventLoop` is closed. case closed /// `EventLoop` is closed and is currently trying to reclaim resources (such as the EventLoop thread). case reclaimingResources /// `EventLoop` is closed and all the resources (such as the EventLoop thread) have been reclaimed. case resourcesReclaimed } /// The different state in the lifecycle of an `EventLoop` seen from _inside_ the `EventLoop`. private enum InternalState { case runningAndAcceptingNewRegistrations case runningButNotAcceptingNewRegistrations case noLongerRunning case exitingThread } /* private but tests */ internal let _selector: NIOPosix.Selector<NIORegistration> private let thread: NIOThread @usableFromInline // _pendingTaskPop is set to `true` if the event loop is about to pop tasks off the task queue. // This may only be read/written while holding the _tasksLock. internal var _pendingTaskPop = false @usableFromInline internal var scheduledTaskCounter = ManagedAtomic<UInt64>(0) @usableFromInline internal var _scheduledTasks = PriorityQueue<ScheduledTask>() // We only need the ScheduledTask's task closure. However, an `Array<() -> Void>` allocates // for every appended closure. https://bugs.swift.org/browse/SR-15872 private var tasksCopy = ContiguousArray<ScheduledTask>() @usableFromInline internal var _succeededVoidFuture: Optional<EventLoopFuture<Void>> = nil { didSet { self.assertInEventLoop() } } private let canBeShutdownIndividually: Bool @usableFromInline internal let _tasksLock = NIOLock() private let _externalStateLock = NIOLock() private var externalStateLock: NIOLock { // The assert is here to check that we never try to read the external state on the EventLoop unless we're // shutting down. assert(!self.inEventLoop || self.internalState != .runningAndAcceptingNewRegistrations, "lifecycle lock taken whilst up and running and in EventLoop") return self._externalStateLock } private var internalState: InternalState = .runningAndAcceptingNewRegistrations // protected by the EventLoop thread private var externalState: ExternalState = .open // protected by externalStateLock private let _iovecs: UnsafeMutablePointer<IOVector> private let _storageRefs: UnsafeMutablePointer<Unmanaged<AnyObject>> let iovecs: UnsafeMutableBufferPointer<IOVector> let storageRefs: UnsafeMutableBufferPointer<Unmanaged<AnyObject>> // Used for gathering UDP writes. private let _msgs: UnsafeMutablePointer<MMsgHdr> private let _addresses: UnsafeMutablePointer<sockaddr_storage> let msgs: UnsafeMutableBufferPointer<MMsgHdr> let addresses: UnsafeMutableBufferPointer<sockaddr_storage> // Used for UDP control messages. private(set) var controlMessageStorage: UnsafeControlMessageStorage // The `_parentGroup` will always be set unless this is a thread takeover or we shut down. @usableFromInline internal var _parentGroup: Optional<MultiThreadedEventLoopGroup> /// Creates a new `SelectableEventLoop` instance that is tied to the given `pthread_t`. private let promiseCreationStoreLock = NIOLock() private var _promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:] @usableFromInline internal func _promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) { precondition(_isDebugAssertConfiguration()) self.promiseCreationStoreLock.withLock { self._promiseCreationStore[futureIdentifier] = (file: file, line: line) } } @usableFromInline internal func _promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? { precondition(_isDebugAssertConfiguration()) return self.promiseCreationStoreLock.withLock { self._promiseCreationStore.removeValue(forKey: futureIdentifier) } } @usableFromInline internal func _preconditionSafeToWait(file: StaticString, line: UInt) { let explainer: () -> String = { """ BUG DETECTED: wait() must not be called when on an EventLoop. Calling wait() on any EventLoop can lead to - deadlocks - stalling processing of other connections (Channels) that are handled on the EventLoop that wait was called on Further information: - current eventLoop: \(MultiThreadedEventLoopGroup.currentEventLoop.debugDescription) - event loop associated to future: \(self) """ } precondition(!self.inEventLoop, explainer(), file: file, line: line) precondition(MultiThreadedEventLoopGroup.currentEventLoop == nil, explainer(), file: file, line: line) } @usableFromInline internal var _validInternalStateToScheduleTasks: Bool { switch self.internalState { case .exitingThread: return false case .runningAndAcceptingNewRegistrations, .runningButNotAcceptingNewRegistrations, .noLongerRunning: return true } } // access with `externalStateLock` held private var validExternalStateToScheduleTasks: Bool { switch self.externalState { case .open, .closing: return true case .closed, .reclaimingResources, .resourcesReclaimed: return false } } internal var testsOnly_validExternalStateToScheduleTasks: Bool { return self.externalStateLock.withLock { return self.validExternalStateToScheduleTasks } } internal init(thread: NIOThread, parentGroup: MultiThreadedEventLoopGroup?, /* nil iff thread take-over */ selector: NIOPosix.Selector<NIORegistration>, canBeShutdownIndividually: Bool) { self._parentGroup = parentGroup self._selector = selector self.thread = thread self._iovecs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) self._storageRefs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) self.iovecs = UnsafeMutableBufferPointer(start: self._iovecs, count: Socket.writevLimitIOVectors) self.storageRefs = UnsafeMutableBufferPointer(start: self._storageRefs, count: Socket.writevLimitIOVectors) self._msgs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) self._addresses = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors) self.msgs = UnsafeMutableBufferPointer(start: _msgs, count: Socket.writevLimitIOVectors) self.addresses = UnsafeMutableBufferPointer(start: _addresses, count: Socket.writevLimitIOVectors) self.controlMessageStorage = UnsafeControlMessageStorage.allocate(msghdrCount: Socket.writevLimitIOVectors) // We will process 4096 tasks per while loop. self.tasksCopy.reserveCapacity(4096) self.canBeShutdownIndividually = canBeShutdownIndividually // note: We are creating a reference cycle here that we'll break when shutting the SelectableEventLoop down. // note: We have to create the promise and complete it because otherwise we'll hit a loop in `makeSucceededFuture`. This is // fairly dumb, but it's the only option we have. let voidPromise = self.makePromise(of: Void.self) voidPromise.succeed(()) self._succeededVoidFuture = voidPromise.futureResult } deinit { assert(self.internalState == .exitingThread, "illegal internal state on deinit: \(self.internalState)") assert(self.externalState == .resourcesReclaimed, "illegal external state on shutdown: \(self.externalState)") _iovecs.deallocate() _storageRefs.deallocate() _msgs.deallocate() _addresses.deallocate() self.controlMessageStorage.deallocate() } /// Is this `SelectableEventLoop` still open (ie. not shutting down or shut down) internal var isOpen: Bool { self.assertInEventLoop() switch self.internalState { case .noLongerRunning, .runningButNotAcceptingNewRegistrations, .exitingThread: return false case .runningAndAcceptingNewRegistrations: return true } } /// Register the given `SelectableChannel` with this `SelectableEventLoop`. After this point all I/O for the `SelectableChannel` will be processed by this `SelectableEventLoop` until it /// is deregistered by calling `deregister`. internal func register<C: SelectableChannel>(channel: C) throws { self.assertInEventLoop() // Don't allow registration when we're closed. guard self.isOpen else { throw EventLoopError.shutdown } try channel.register(selector: self._selector, interested: channel.interestedEvent) } /// Deregister the given `SelectableChannel` from this `SelectableEventLoop`. internal func deregister<C: SelectableChannel>(channel: C, mode: CloseMode = .all) throws { self.assertInEventLoop() guard self.isOpen else { // It's possible the EventLoop was closed before we were able to call deregister, so just return in this case as there is no harm. return } try channel.deregister(selector: self._selector, mode: mode) } /// Register the given `SelectableChannel` with this `SelectableEventLoop`. This should be done whenever `channel.interestedEvents` has changed and it should be taken into account when /// waiting for new I/O for the given `SelectableChannel`. internal func reregister<C: SelectableChannel>(channel: C) throws { self.assertInEventLoop() try channel.reregister(selector: self._selector, interested: channel.interestedEvent) } /// - see: `EventLoop.inEventLoop` @usableFromInline internal var inEventLoop: Bool { return thread.isCurrent } /// - see: `EventLoop.scheduleTask(deadline:_:)` @inlinable internal func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> { let promise: EventLoopPromise<T> = self.makePromise() let task = ScheduledTask(id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), { do { promise.succeed(try task()) } catch let err { promise.fail(err) } }, { error in promise.fail(error) }, deadline) let taskId = task.id let scheduled = Scheduled(promise: promise, cancellationTask: { self._tasksLock.withLock { () -> Void in self._scheduledTasks.removeFirst(where: { $0.id == taskId }) } // We don't need to wake up the selector here, the scheduled task will never be picked up. Waking up the // selector would mean that we may be able to recalculate the shutdown to a later date. The cost of not // doing the recalculation is one potentially unnecessary wakeup which is exactly what we're // saving here. So in the worst case, we didn't do a performance optimisation, in the best case, we saved // one wakeup. }) do { try self._schedule0(task) } catch { promise.fail(error) } return scheduled } /// - see: `EventLoop.scheduleTask(in:_:)` @inlinable internal func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> { return scheduleTask(deadline: .now() + `in`, task) } // - see: `EventLoop.execute` @inlinable internal func execute(_ task: @escaping () -> Void) { // nothing we can do if we fail enqueuing here. try? self._schedule0(ScheduledTask(id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), task, { error in // do nothing }, .now())) } /// Add the `ScheduledTask` to be executed. @usableFromInline internal func _schedule0(_ task: ScheduledTask) throws { if self.inEventLoop { precondition(self._validInternalStateToScheduleTasks, "BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop.") self._tasksLock.withLock { () -> Void in self._scheduledTasks.push(task) } } else { let shouldWakeSelector: Bool = self.externalStateLock.withLock { guard self.validExternalStateToScheduleTasks else { if Self.strictModeEnabled { fatalError("Cannot schedule tasks on an EventLoop that has already shut down.") } fputs( """ ERROR: Cannot schedule tasks on an EventLoop that has already shut down. \ This will be upgraded to a forced crash in future SwiftNIO versions.\n """, stderr ) return false } return self._tasksLock.withLock { self._scheduledTasks.push(task) if self._pendingTaskPop == false { // Our job to wake the selector. self._pendingTaskPop = true return true } else { // There is already an event-loop-tick scheduled, we don't need to wake the selector. return false } } } // We only need to wake up the selector if we're not in the EventLoop. If we're in the EventLoop already, we're // either doing IO tasks (which happens before checking the scheduled tasks) or we're running a scheduled task // already which means that we'll check at least once more if there are other scheduled tasks runnable. While we // had the task lock we also checked whether the loop was _already_ going to be woken. This saves us a syscall on // hot loops. // // In the future we'll use an MPSC queue here and that will complicate things, so we may get some spurious wakeups, // but as long as we're using the big dumb lock we can make this optimization safely. if shouldWakeSelector { try self._wakeupSelector() } } } /// Wake the `Selector` which means `Selector.whenReady(...)` will unblock. @usableFromInline internal func _wakeupSelector() throws { try _selector.wakeup() } /// Handle the given `SelectorEventSet` for the `SelectableChannel`. internal final func handleEvent<C: SelectableChannel>(_ ev: SelectorEventSet, channel: C) { guard channel.isOpen else { return } // process resets first as they'll just cause the writes to fail anyway. if ev.contains(.reset) { channel.reset() } else { if ev.contains(.writeEOF) { channel.writeEOF() guard channel.isOpen else { return } } else if ev.contains(.write) { channel.writable() guard channel.isOpen else { return } } if ev.contains(.readEOF) { channel.readEOF() } else if ev.contains(.read) { channel.readable() } } } private func currentSelectorStrategy(nextReadyTask: ScheduledTask?) -> SelectorStrategy { guard let sched = nextReadyTask else { // No tasks to handle so just block. If any tasks were added in the meantime wakeup(...) was called and so this // will directly unblock. return .block } let nextReady = sched.readyIn(.now()) if nextReady <= .nanoseconds(0) { // Something is ready to be processed just do a non-blocking select of events. return .now } else { return .blockUntilTimeout(nextReady) } } /// Start processing I/O and tasks for this `SelectableEventLoop`. This method will continue running (and so block) until the `SelectableEventLoop` is closed. internal func run() throws { self.preconditionInEventLoop() defer { var scheduledTasksCopy = ContiguousArray<ScheduledTask>() var iterations = 0 repeat { // We may need to do multiple rounds of this because failing tasks may lead to more work. scheduledTasksCopy.removeAll(keepingCapacity: true) self._tasksLock.withLock { () -> Void in // In this state we never want the selector to be woken again, so we pretend we're permanently running. self._pendingTaskPop = true // reserve the correct capacity so we don't need to realloc later on. scheduledTasksCopy.reserveCapacity(self._scheduledTasks.count) while let sched = self._scheduledTasks.pop() { scheduledTasksCopy.append(sched) } } // Fail all the scheduled tasks. for task in scheduledTasksCopy { task.fail(EventLoopError.shutdown) } iterations += 1 } while scheduledTasksCopy.count > 0 && iterations < 1000 precondition(scheduledTasksCopy.count == 0, "EventLoop \(self) didn't quiesce after 1000 ticks.") assert(self.internalState == .noLongerRunning, "illegal state: \(self.internalState)") self.internalState = .exitingThread } var nextReadyTask: ScheduledTask? = nil self._tasksLock.withLock { if let firstTask = self._scheduledTasks.peek() { // The reason this is necessary is a very interesting race: // In theory (and with `makeEventLoopFromCallingThread` even in practise), we could publish an // `EventLoop` reference _before_ the EL thread has entered the `run` function. // If that is the case, we need to schedule the first wakeup at the ready time for this task that was // enqueued really early on, so let's do that :). nextReadyTask = firstTask } } while self.internalState != .noLongerRunning && self.internalState != .exitingThread { // Block until there are events to handle or the selector was woken up /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ try withAutoReleasePool { try self._selector.whenReady( strategy: currentSelectorStrategy(nextReadyTask: nextReadyTask), onLoopBegin: { self._tasksLock.withLock { () -> Void in self._pendingTaskPop = true } } ) { ev in switch ev.registration.channel { case .serverSocketChannel(let chan): self.handleEvent(ev.io, channel: chan) case .socketChannel(let chan): self.handleEvent(ev.io, channel: chan) case .datagramChannel(let chan): self.handleEvent(ev.io, channel: chan) case .pipeChannel(let chan, let direction): var ev = ev if ev.io.contains(.reset) { // .reset needs special treatment here because we're dealing with two separate pipes instead // of one socket. So we turn .reset input .readEOF/.writeEOF. ev.io.subtract([.reset]) ev.io.formUnion([direction == .input ? .readEOF : .writeEOF]) } self.handleEvent(ev.io, channel: chan) } } } // We need to ensure we process all tasks, even if a task added another task again while true { // TODO: Better locking self._tasksLock.withLock { () -> Void in if !self._scheduledTasks.isEmpty { // We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway. let now: NIODeadline = .now() // Make a copy of the tasks so we can execute these while not holding the lock anymore while tasksCopy.count < tasksCopy.capacity, let task = self._scheduledTasks.peek() { if task.readyIn(now) <= .nanoseconds(0) { self._scheduledTasks.pop() self.tasksCopy.append(task) } else { nextReadyTask = task break } } } else { // Reset nextReadyTask to nil which means we will do a blocking select. nextReadyTask = nil } if self.tasksCopy.isEmpty { // We will not continue to loop here. We need to be woken if a new task is enqueued. self._pendingTaskPop = false } } // all pending tasks are set to occur in the future, so we can stop looping. if self.tasksCopy.isEmpty { break } // Execute all the tasks that were submitted for task in self.tasksCopy { /* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */ withAutoReleasePool { task.task() } } // Drop everything (but keep the capacity) so we can fill it again on the next iteration. self.tasksCopy.removeAll(keepingCapacity: true) } } // This EventLoop was closed so also close the underlying selector. try self._selector.close() // This breaks the retain cycle created in `init`. self._succeededVoidFuture = nil } internal func initiateClose(queue: DispatchQueue, completionHandler: @escaping (Result<Void, Error>) -> Void) { func doClose() { self.assertInEventLoop() self._parentGroup = nil // break the cycle // There should only ever be one call into this function so we need to be up and running, ... assert(self.internalState == .runningAndAcceptingNewRegistrations) self.internalState = .runningButNotAcceptingNewRegistrations self.externalStateLock.withLock { // ... but before this call happened, the lifecycle state should have been changed on some other thread. assert(self.externalState == .closing) } self._selector.closeGently(eventLoop: self).whenComplete { result in self.assertInEventLoop() assert(self.internalState == .runningButNotAcceptingNewRegistrations) self.internalState = .noLongerRunning self.execute {} // force a new event loop tick, so the event loop definitely stops looping very soon. self.externalStateLock.withLock { assert(self.externalState == .closing) self.externalState = .closed } queue.async { completionHandler(result) } } } if self.inEventLoop { queue.async { self.initiateClose(queue: queue, completionHandler: completionHandler) } } else { let goAhead = self.externalStateLock.withLock { () -> Bool in if self.externalState == .open { self.externalState = .closing return true } else { return false } } guard goAhead else { queue.async { completionHandler(Result.failure(EventLoopError.shutdown)) } return } self.execute { doClose() } } } internal func syncFinaliseClose(joinThread: Bool) { // This may not be true in the future but today we need to join all ELs that can't be shut down individually. assert(joinThread != self.canBeShutdownIndividually) let goAhead = self.externalStateLock.withLock { () -> Bool in switch self.externalState { case .closed: self.externalState = .reclaimingResources return true case .resourcesReclaimed, .reclaimingResources: return false default: preconditionFailure("illegal lifecycle state in syncFinaliseClose: \(self.externalState)") } } guard goAhead else { return } if joinThread { self.thread.join() } self.externalStateLock.withLock { precondition(self.externalState == .reclaimingResources) self.externalState = .resourcesReclaimed } } @usableFromInline func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { if self.canBeShutdownIndividually { self.initiateClose(queue: queue) { result in self.syncFinaliseClose(joinThread: false) // This thread was taken over by somebody else switch result { case .success: callback(nil) case .failure(let error): callback(error) } } } else { // This function is never called legally because the only possibly owner of an `SelectableEventLoop` is // `MultiThreadedEventLoopGroup` which calls `initiateClose` followed by `syncFinaliseClose`. queue.async { callback(EventLoopError.unsupportedOperation) } } } @inlinable public func makeSucceededVoidFuture() -> EventLoopFuture<Void> { guard self.inEventLoop, let voidFuture = self._succeededVoidFuture else { // We have to create the promise and complete it because otherwise we'll hit a loop in `makeSucceededFuture`. This is // fairly dumb, but it's the only option we have. This one can only happen after the loop is shut down, or when calling from off the loop. let voidPromise = self.makePromise(of: Void.self) voidPromise.succeed(()) return voidPromise.futureResult } return voidFuture } @inlinable internal func parentGroupCallableFromThisEventLoopOnly() -> MultiThreadedEventLoopGroup? { self.assertInEventLoop() return self._parentGroup } } extension SelectableEventLoop: CustomStringConvertible, CustomDebugStringConvertible { @usableFromInline var description: String { return "SelectableEventLoop { selector = \(self._selector), thread = \(self.thread) }" } @usableFromInline var debugDescription: String { return self._tasksLock.withLock { return "SelectableEventLoop { selector = \(self._selector), thread = \(self.thread), scheduledTasks = \(self._scheduledTasks.description) }" } } }
82964be8176629c23892fb6a26d92738
42.768559
189
0.607237
false
false
false
false
ruslanskorb/CoreStore
refs/heads/master
Sources/KeyPath+Querying.swift
mit
1
// // KeyPath+Querying.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 import Foundation // MARK: - KeyPath where Root: NSManagedObject, Value: QueryableAttributeType & Equatable /** Creates a `Where` clause by comparing if a property is equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname == "John")) ``` */ public func == <O: NSManagedObject, V: QueryableAttributeType & Equatable>(_ keyPath: KeyPath<O, V>, _ value: V) -> Where<O> { return Where<O>(keyPath._kvcKeyPathString!, isEqualTo: value) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname != "John")) ``` */ public func != <O: NSManagedObject, V: QueryableAttributeType & Equatable>(_ keyPath: KeyPath<O, V>, _ value: V) -> Where<O> { return !Where<O>(keyPath._kvcKeyPathString!, isEqualTo: value) } /** Creates a `Where` clause by checking if a sequence contains the value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ public func ~= <O: NSManagedObject, V: QueryableAttributeType & Equatable, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, V>) -> Where<O> where S.Iterator.Element == V { return Where<O>(keyPath._kvcKeyPathString!, isMemberOf: sequence) } // MARK: - KeyPath where Root: NSManagedObject, Value: Optional<QueryableAttributeType & Equatable> /** Creates a `Where` clause by comparing if a property is equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname == "John")) ``` */ public func == <O: NSManagedObject, V: QueryableAttributeType & Equatable>(_ keyPath: KeyPath<O, Optional<V>>, _ value: V?) -> Where<O> { return Where<O>(keyPath._kvcKeyPathString!, isEqualTo: value) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname != "John")) ``` */ public func != <O: NSManagedObject, V: QueryableAttributeType & Equatable>(_ keyPath: KeyPath<O, Optional<V>>, _ value: V?) -> Where<O> { return !Where<O>(keyPath._kvcKeyPathString!, isEqualTo: value) } /** Creates a `Where` clause by checking if a sequence contains the value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ public func ~= <O: NSManagedObject, V: QueryableAttributeType & Equatable, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, Optional<V>>) -> Where<O> where S.Iterator.Element == V { return Where<O>(keyPath._kvcKeyPathString!, isMemberOf: sequence) } // MARK: - KeyPath where Root: NSManagedObject, Value: QueryableAttributeType & Comparable /** Creates a `Where` clause by comparing if a property is less than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age < 20)) ``` */ public func < <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, V>, _ value: V) -> Where<O> { return Where<O>("%K < %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } /** Creates a `Where` clause by comparing if a property is greater than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age > 20)) ``` */ public func > <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, V>, _ value: V) -> Where<O> { return Where<O>("%K > %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } /** Creates a `Where` clause by comparing if a property is less than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age <= 20)) ``` */ public func <= <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, V>, _ value: V) -> Where<O> { return Where<O>("%K <= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } /** Creates a `Where` clause by comparing if a property is greater than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age >= 20)) ``` */ public func >= <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, V>, _ value: V) -> Where<O> { return Where<O>("%K >= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } // MARK: - KeyPath where Root: NSManagedObject, Value: Optional<QueryableAttributeType & Comparable> /** Creates a `Where` clause by comparing if a property is less than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age < 20)) ``` */ public func < <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K < %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } else { return Where<O>("%K < nil", keyPath._kvcKeyPathString!) } } /** Creates a `Where` clause by comparing if a property is greater than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age > 20)) ``` */ public func > <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K > %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } else { return Where<O>("%K > nil", keyPath._kvcKeyPathString!) } } /** Creates a `Where` clause by comparing if a property is less than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age <= 20)) ``` */ public func <= <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K <= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } else { return Where<O>("%K <= nil", keyPath._kvcKeyPathString!) } } /** Creates a `Where` clause by comparing if a property is greater than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age >= 20)) ``` */ public func >= <O: NSManagedObject, V: QueryableAttributeType & Comparable>(_ keyPath: KeyPath<O, Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K >= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) } else { return Where<O>("%K >= nil", keyPath._kvcKeyPathString!) } } // MARK: - KeyPath where Root: NSManagedObject, Value: NSManagedObject /** Creates a `Where` clause by comparing if a property is equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master == john)) ``` */ public func == <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, D>, _ object: D) -> Where<O> { return Where<O>(keyPath._kvcKeyPathString!, isEqualTo: object) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master != john)) ``` */ public func != <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, D>, _ object: D) -> Where<O> { return !Where<O>(keyPath._kvcKeyPathString!, isEqualTo: object) } /** Creates a `Where` clause by checking if a sequence contains a value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where([john, bob, joe] ~= \.master)) ``` */ public func ~= <O: NSManagedObject, D: NSManagedObject, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, D>) -> Where<O> where S.Iterator.Element == D { return Where<O>(keyPath._kvcKeyPathString!, isMemberOf: sequence) } /** Creates a `Where` clause by comparing if a property is equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master == john)) ``` */ public func == <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, D>, _ objectID: NSManagedObjectID) -> Where<O> { return Where<O>(keyPath._kvcKeyPathString!, isEqualTo: objectID) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master != john)) ``` */ public func != <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, D>, _ objectID: NSManagedObjectID) -> Where<O> { return !Where<O>(keyPath._kvcKeyPathString!, isEqualTo: objectID) } /** Creates a `Where` clause by checking if a sequence contains a value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where([john, bob, joe] ~= \.master)) ``` */ public func ~= <O: NSManagedObject, D: NSManagedObject, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, D>) -> Where<O> where S.Iterator.Element == NSManagedObjectID { return Where<O>(keyPath._kvcKeyPathString!, isMemberOf: sequence) } // MARK: - KeyPath where Root: NSManagedObject, Value: Optional<NSManagedObject> /** Creates a `Where` clause by comparing if a property is equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master == john)) ``` */ public func == <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, Optional<D>>, _ object: D?) -> Where<O> { return Where<O>(keyPath._kvcKeyPathString!, isEqualTo: object) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master != john)) ``` */ public func != <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, Optional<D>>, _ object: D?) -> Where<O> { return !Where<O>(keyPath._kvcKeyPathString!, isEqualTo: object) } /** Creates a `Where` clause by checking if a sequence contains a value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where([john, bob, joe] ~= \.master)) ``` */ public func ~= <O: NSManagedObject, D: NSManagedObject, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, Optional<D>>) -> Where<O> where S.Iterator.Element == D { return Where<O>(keyPath._kvcKeyPathString!, isMemberOf: sequence) } /** Creates a `Where` clause by comparing if a property is equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master == john)) ``` */ public func == <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, Optional<D>>, _ objectID: NSManagedObjectID) -> Where<O> { return Where<O>(keyPath._kvcKeyPathString!, isEqualTo: objectID) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master != john)) ``` */ public func != <O: NSManagedObject, D: NSManagedObject>(_ keyPath: KeyPath<O, Optional<D>>, _ objectID: NSManagedObjectID) -> Where<O> { return !Where<O>(keyPath._kvcKeyPathString!, isEqualTo: objectID) } /** Creates a `Where` clause by checking if a sequence contains a value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where([john, bob, joe] ~= \.master)) ``` */ public func ~= <O: NSManagedObject, D: NSManagedObject, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, Optional<D>>) -> Where<O> where S.Iterator.Element == NSManagedObjectID { return Where<O>(keyPath._kvcKeyPathString!, isMemberOf: sequence) } // MARK: - KeyPath where Root: CoreStoreObject, Value: ValueContainer<Root>.Required<QueryableAttributeType & Equatable> /** Creates a `Where` clause by comparing if a property is equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname == "John")) ``` */ public func == <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>, _ value: V) -> Where<O> { return Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: value) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname != "John")) ``` */ public func != <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>, _ value: V) -> Where<O> { return !Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: value) } /** Creates a `Where` clause by checking if a sequence contains the value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ public func ~= <O, V, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>) -> Where<O> where S.Iterator.Element == V { return Where<O>(O.meta[keyPath: keyPath].keyPath, isMemberOf: sequence) } // MARK: - KeyPath where Root: CoreStoreObject, Value: ValueContainer<Root>.Optional<QueryableAttributeType & Equatable> /** Creates a `Where` clause by comparing if a property is equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname == "John")) ``` */ public func == <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>, _ value: V?) -> Where<O> { return Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: value) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.nickname != "John")) ``` */ public func != <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>, _ value: V?) -> Where<O> { return !Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: value) } /** Creates a `Where` clause by checking if a sequence contains the value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ public func ~= <O, V, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>) -> Where<O> where S.Iterator.Element == V { return Where<O>(O.meta[keyPath: keyPath].keyPath, isMemberOf: sequence) } // MARK: - KeyPath where Root: CoreStoreObject, Value: ValueContainer<Root>.Required<QueryableAttributeType & Comparable> /** Creates a `Where` clause by comparing if a property is less than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age < 20)) ``` */ public func < <O, V: Comparable>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>, _ value: V) -> Where<O> { return Where<O>("%K < %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } /** Creates a `Where` clause by comparing if a property is greater than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age > 20)) ``` */ public func > <O, V: Comparable>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>, _ value: V) -> Where<O> { return Where<O>("%K > %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } /** Creates a `Where` clause by comparing if a property is less than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age <= 20)) ``` */ public func <= <O, V: Comparable>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>, _ value: V) -> Where<O> { return Where<O>("%K <= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } /** Creates a `Where` clause by comparing if a property is greater than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age >= 20)) ``` */ public func >= <O, V: Comparable>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<V>>, _ value: V) -> Where<O> { return Where<O>("%K >= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } // MARK: - KeyPath where Root: CoreStoreObject, Value: ValueContainer<Root>.Optional<QueryableAttributeType & Comparable> /** Creates a `Where` clause by comparing if a property is less than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age < 20)) ``` */ public func < <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K < %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } else { return Where<O>("%K < nil", O.meta[keyPath: keyPath].keyPath) } } /** Creates a `Where` clause by comparing if a property is greater than a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age > 20)) ``` */ public func > <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K > %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } else { return Where<O>("%K > nil", O.meta[keyPath: keyPath].keyPath) } } /** Creates a `Where` clause by comparing if a property is less than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age <= 20)) ``` */ public func <= <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K <= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } else { return Where<O>("%K <= nil", O.meta[keyPath: keyPath].keyPath) } } /** Creates a `Where` clause by comparing if a property is greater than or equal to a value ``` let person = dataStack.fetchOne(From<Person>().where(\.age >= 20)) ``` */ public func >= <O, V>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<V>>, _ value: V?) -> Where<O> { if let value = value { return Where<O>("%K >= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toQueryableNativeType()) } else { return Where<O>("%K >= nil", O.meta[keyPath: keyPath].keyPath) } } // MARK: - KeyPath where Root: CoreStoreObject, Value: RelationshipContainer<Root>.ToOne<CoreStoreObject> /** Creates a `Where` clause by comparing if a property is equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master == john)) ``` */ public func == <O, D>(_ keyPath: KeyPath<O, RelationshipContainer<O>.ToOne<D>>, _ object: D) -> Where<O> { return Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: object) } /** Creates a `Where` clause by comparing if a property is equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master == john)) ``` */ public func == <O, D>(_ keyPath: KeyPath<O, RelationshipContainer<O>.ToOne<D>>, _ object: D?) -> Where<O> { return Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: object) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master != john)) ``` */ public func != <O, D>(_ keyPath: KeyPath<O, RelationshipContainer<O>.ToOne<D>>, _ object: D) -> Where<O> { return !Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: object) } /** Creates a `Where` clause by comparing if a property is not equal to a value ``` let dog = dataStack.fetchOne(From<Dog>().where(\.master != john)) ``` */ public func != <O, D>(_ keyPath: KeyPath<O, RelationshipContainer<O>.ToOne<D>>, _ object: D?) -> Where<O> { return !Where<O>(O.meta[keyPath: keyPath].keyPath, isEqualTo: object) } /** Creates a `Where` clause by checking if a sequence contains a value of a property ``` let dog = dataStack.fetchOne(From<Dog>().where([john, bob, joe] ~= \.master)) ``` */ public func ~= <O, D, S: Sequence>(_ sequence: S, _ keyPath: KeyPath<O, RelationshipContainer<O>.ToOne<D>>) -> Where<O> where S.Iterator.Element == D { return Where<O>(O.meta[keyPath: keyPath].keyPath, isMemberOf: sequence) }
c2eb9468df81fc8f5faae4a5d37f55ba
33.05401
182
0.654876
false
false
false
false
mittsuu/MarkedView-for-iOS
refs/heads/master
Pod/Classes/WKMarkedView.swift
mit
1
// // WKMarkedView.swift // Markdown preview for WKWebView // // Created by mittsu on 2016/04/19. // import UIKit import WebKit @objc public protocol WKMarkViewDelegate: NSObjectProtocol { @objc optional func markViewRedirect(url: URL) } open class WKMarkedView: UIView { fileprivate var webView: WKWebView! fileprivate var mdContents: String? fileprivate var requestHtml: URLRequest? fileprivate var codeScrollDisable = false weak open var delegate: WKMarkViewDelegate? convenience init () { self.init(frame:CGRect.zero) } override init (frame : CGRect) { super.init(frame : frame) initView() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView() { let bundle = Bundle(for: WKMarkedView.self) let path = bundle.path(forResource: "MarkedView.bundle/md_preview", ofType:"html") requestHtml = URLRequest(url: URL(fileURLWithPath: path!)) // Disables pinch to zoom let source: String = "var meta = document.createElement('meta');" + "meta.name = 'viewport';" + "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" + "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);" + "document.documentElement.style.webkitTouchCallout = 'none';"; let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) // Create the configuration let userContentController = WKUserContentController() userContentController.addUserScript(script) let configuration = WKWebViewConfiguration() configuration.userContentController = userContentController webView = WKWebView(frame: self.frame, configuration: configuration) webView.translatesAutoresizingMaskIntoConstraints = false webView.navigationDelegate = self addSubview(webView) // The size of the custom View to the same size as himself let bindings: [String : UIView] = ["view": webView] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) // Hide background webView.backgroundColor = UIColor.clear } /** Load from markdown file - parameter filePath: markdown file path */ public func loadFile(_ filePath: String?) { guard let mdData = try? Data(contentsOf: URL(fileURLWithPath: filePath!)) else { return } textToMark(String().data2String(mdData)) } /** To set the text to display - parameter mdText: markdown text */ public func textToMark(_ mdText: String?) { guard let url = requestHtml, let contents = mdText else { return; } mdContents = toMarkdownFormat(contents) webView.load(url) } fileprivate func toMarkdownFormat(_ contents: String) -> String { let conversion = ConversionMDFormat(); let imgChanged = conversion.imgToBase64(contents) return conversion.escapeForText(imgChanged) } /** option **/ open func setCodeScrollDisable() { codeScrollDisable = true } } // MARK: - <#WKNavigationDelegate#> extension WKMarkedView: WKNavigationDelegate { public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) { guard let url = navigationAction.request.url else { decisionHandler(.cancel) return; } if url.scheme == "file" { decisionHandler(.allow) } else if url.scheme == "https" { delegate?.markViewRedirect?(url: url) decisionHandler(.cancel) } else { decisionHandler(.cancel) } } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { guard let contents = mdContents else { return; } let script = "preview('\(contents)', \(codeScrollDisable));" webView.evaluateJavaScript(script, completionHandler: { (html, error) -> Void in } ) } }
b205386c160e1c6ab2fb9d884b906589
31.62069
170
0.627061
false
false
false
false
khizkhiz/swift
refs/heads/master
test/SILOptimizer/let_properties_opts_runtime.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -O %s -o %t/a.out // RUN: %target-run %t/a.out | FileCheck %s -check-prefix=CHECK-OUTPUT // REQUIRES: executable_test // Check that in optimized builds the compiler generates correct code for // initializations of let properties, which is assigned multiple times inside // initializers. public class Foo1 { internal let Prop1: Int32 internal let Prop2: Int32 // Initialize Prop3 as part of declaration. internal let Prop3: Int32 = 20 internal let Prop4: Int32 @inline(never) init(_ count: Int32) { // Initialize Prop4 unconditionally and only once. Prop4 = 300 // There are two different assignments to Prop1 and Prop2 // on different branches of the if-statement. if count < 2 { // Initialize Prop1 and Prop2 conditionally. // Use other properties in the definition of Prop1 and Prop2. Prop1 = 5 Prop2 = 10 - Prop1 + Prop4 - Prop3 } else { // Initialize Prop1 and Prop2 conditionally. // Use other properties in the definition of Prop1 and Prop2. Prop1 = 100 Prop2 = 200 + Prop1 - Prop4 - Prop3 } } } public func testClassLet(f: Foo1) -> Int32 { return f.Prop1 + f.Prop2 + f.Prop3 + f.Prop4 } // Prop1 = 5, Prop2 = (10-5+300-20) = 285, Prop3 = 20, Prop4 = 300 // Hence Prop1 + Prop2 + Prop3 + Prop4 = 610 // CHECK-OUTPUT: 610 print(testClassLet(Foo1(1))) // Prop1 = 100, Prop2 = (200+100-300-20) = -20, Prop3 = 20, Prop4 = 300 // Hence Prop1 + Prop2 + Prop3 + Prop4 = 610 // CHECK-OUTPUT: 400 print(testClassLet(Foo1(10)))
9f0bcfa6c71cf868d404046cbb5e1f5e
30.76
77
0.65932
false
true
false
false
psmortal/Berry
refs/heads/master
Pod/Classes/RainbowString/RainbowString.swift
mit
1
// // RainbowString.swift // tianshidaoyi // // Created by ydf on 2017/8/11. // Copyright © 2017年 zengdaqian. All rights reserved. // import Foundation public extension String { public var rb:Rainbow{ return Rainbow(self) } } public extension String{ public subscript(_ range:CountableClosedRange<Int>)->String{ return (self as NSString).substring(with: NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound + 1)) } public func locations(of:String)->[Int]{ var result = [Int]() if !contains(of) || of.characters.count == 0 || self.characters.count < of.characters.count {return []} for i in 0...(characters.count - of.characters.count){ if self[i...(i + of.characters.count - 1)] == of { result.append(i) } } return result } } public class Rainbow { public let base:String private let attributedString:NSMutableAttributedString var operatingString:String? // 当前操作的子字符串 var operatingRanges:[NSRange] //当前操作的range var attributes:[String:Any] = [:] public func match(_ subString:String)->Rainbow{ self.operatingString = subString if base.contains(subString){ self.operatingRanges = base.locations(of: subString).map{NSMakeRange($0, subString.characters.count)} }else{ self.operatingRanges = [] } return self } public func all()->Rainbow{ return match(base) } public subscript(_ range:CountableClosedRange<Int>)->Rainbow{ self.operatingRanges = [NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound + 1)] return self } public func range(_ range:CountableClosedRange<Int>)->Rainbow{ self.operatingRanges = [NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound + 1)] return self } init(_ base:String) { self.base = base self.attributedString = NSMutableAttributedString(string: base) self.operatingRanges = [NSMakeRange(0, base.characters.count)] } public var done:NSMutableAttributedString{ return attributedString } public func fontSize(_ size:CGFloat)->Rainbow{ for range in operatingRanges{ attributedString.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: size)], range:range) } return self } public func font(_ font:UIFont)->Rainbow{ for range in operatingRanges{ attributedString.addAttributes([NSFontAttributeName:font], range:range) } return self } public func color(_ color:UIColor)->Rainbow{ for range in operatingRanges{ attributedString.addAttributes([NSForegroundColorAttributeName:color], range:range) } return self } }
2355deec04979062a28fbb4a12eba328
23.444444
121
0.595779
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
Client/Frontend/Settings/AppSettingsOptions.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 Shared import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.startsWith("browser.") || file.startsWith("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.startsWith("browser.") || file.startsWith("logins.") } } catch { print("Couldn't export browser data: \(error).") } } } // Opens the the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var url: URL? { return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.ShowTour, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.DefaultSearchEngine, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile weak var navigationController: UINavigationController? override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.navigationController = settings.navigationController let loginsTitle = Strings.Logins super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), delegate: delegate) } fileprivate func navigateToLoginsList() { let viewController = LoginListViewController(profile: profile) viewController.settingsDelegate = delegate navigationController?.pushViewController(viewController, animated: true) } } class SyncDevicesSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Sync" } init(settings: SettingsTableViewController) { self.profile = settings.profile let clearTitle = Strings.Sync super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { if Sync.shared.isInSyncGroup { let syncSettingsView = SyncSettingsViewController(style: .grouped) syncSettingsView.profile = getApp().profile navigationController?.pushViewController(syncSettingsView, animated: true) } else { let view = SyncWelcomeViewController() navigationController?.pushViewController(view, animated: true) } } } class SyncDeviceSetting: Setting { let profile: Profile var onTap: (()->Void)? internal var device: Device internal var displayTitle: String { return device.name ?? "" } override var accessoryType: UITableViewCellAccessoryType { return .none } override var accessibilityIdentifier: String? { return "SyncDevice" } init(profile: Profile, device: Device) { self.profile = profile self.device = device super.init(title: NSAttributedString(string: device.name ?? "", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { onTap?() } } class ClearPrivateDataSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile let clearTitle = Strings.ClearPrivateData super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: Strings.Privacy_Policy, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: "https://www.brave.com/ios_privacy.html") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChangePinSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ChangePin" } init(settings: SettingsTableViewController) { self.profile = settings.profile let clearTitle = Strings.Change_Pin super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { if profile.prefs.boolForKey(kPrefKeyBrowserLock) == true { getApp().requirePinIfNeeded(profile: profile) getApp().securityViewController?.auth() } let view = PinViewController() navigationController?.pushViewController(view, animated: true) } }
3fd9481c865659250529d6a76be7a663
36.35
164
0.711358
false
false
false
false
libec/StackOverflow
refs/heads/master
05-GenericTableViewControllers/GenericPicker/ViewController.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2015 Libor Huspenina // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class ViewController: UIViewController { private var payees: [Payee] { var retVal = [Payee]() retVal.append(Payee(payee: "Pepa")) retVal.append(Payee(payee: "Kodl")) retVal.append(Payee(payee: "Igec")) retVal.append(Payee(payee: "Zdenal")) retVal.append(Payee(payee: "Pavka")) return retVal } private var operators: [Operator] { var retVal = [Operator]() retVal.append(Operator(name: "Vodaphone")) retVal.append(Operator(name: "O2")) retVal.append(Operator(name: "T-Mobile")) return retVal } @IBAction func openOperators(sender: AnyObject) { let controller = PickerViewController<Operator>(style: .Plain) controller.items = operators navigationController?.pushViewController(controller, animated: true) } @IBAction func openPayees(sender: AnyObject) { let controller = PickerViewController<Payee>(style: .Plain) controller.items = payees navigationController?.pushViewController(controller, animated: true) } }
af72a49c6ba9cb23cc2d9eb15926a4db
37.2
82
0.690663
false
false
false
false
Hendrik44/pi-weather-app
refs/heads/master
Carthage/Checkouts/Charts/Source/Charts/Charts/CombinedChartView.swift
apache-2.0
8
// // CombinedChartView.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. open class CombinedChartView: BarLineChartViewBase, CombinedChartDataProvider { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: IFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc(CombinedChartDrawOrder) public enum DrawOrder: Int { case bar case bubble case line case candle case scatter } open override func initialize() { super.initialize() self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self) // Old default behaviour self.highlightFullBarEnabled = true _fillFormatter = DefaultFillFormatter() renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } open override var data: ChartData? { get { return super.data } set { super.data = newValue self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self) (renderer as? CombinedChartRenderer)?.createRenderers() renderer?.initBuffers() } } @objc open var fillFormatter: IFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if _fillFormatter == nil { _fillFormatter = DefaultFillFormatter() } } } /// - Returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the CombinedChart. open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y) else { return nil } if !isHighlightFullBarEnabled { return h } // For isHighlightFullBarEnabled, remove stackIndex return Highlight( x: h.x, y: h.y, xPx: h.xPx, yPx: h.yPx, dataIndex: h.dataIndex, dataSetIndex: h.dataSetIndex, stackIndex: -1, axis: h.axis) } // MARK: - CombinedChartDataProvider open var combinedData: CombinedChartData? { get { return _data as? CombinedChartData } } // MARK: - LineChartDataProvider open var lineData: LineChartData? { get { return combinedData?.lineData } } // MARK: - BarChartDataProvider open var barData: BarChartData? { get { return combinedData?.barData } } // MARK: - ScatterChartDataProvider open var scatterData: ScatterChartData? { get { return combinedData?.scatterData } } // MARK: - CandleChartDataProvider open var candleData: CandleChartData? { get { return combinedData?.candleData } } // MARK: - BubbleChartDataProvider open var bubbleData: BubbleChartData? { get { return combinedData?.bubbleData } } // MARK: - Accessors /// if set to true, all values are drawn above their bars, instead of below their top @objc open var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled } set { (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled = newValue } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value @objc open var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer).drawBarShadowEnabled } set { (renderer as! CombinedChartRenderer).drawBarShadowEnabled = newValue } } /// `true` if drawing values above bars is enabled, `false` ifnot open var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled } /// `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot open var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer).drawBarShadowEnabled } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. @objc open var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer).drawOrder = newValue.map { DrawOrder(rawValue: $0)! } } } /// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values @objc open var highlightFullBarEnabled: Bool = false /// `true` the highlight is be full-bar oriented, `false` ifsingle-value open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled } // MARK: - ChartViewBase /// draws all MarkerViews on the highlighted positions override func drawMarkers(context: CGContext) { guard let marker = marker, isDrawMarkersEnabled && valuesToHighlight() else { return } for i in 0 ..< _indicesToHighlight.count { let highlight = _indicesToHighlight[i] guard let set = combinedData?.getDataSetByHighlight(highlight), let e = _data?.entryForHighlight(highlight) else { continue } let entryIndex = set.entryIndex(entry: e) if entryIndex > Int(Double(set.entryCount) * _animator.phaseX) { continue } let pos = getMarkerPosition(highlight: highlight) // check bounds if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y) { continue } // callbacks to update the content marker.refreshContent(entry: e, highlight: highlight) // draw the marker marker.draw(context: context, point: pos) } } }
e69a7e34551146073a2a9dcdb8648cb1
28.373984
149
0.582895
false
false
false
false
banxi1988/BXAppKit
refs/heads/master
BXiOSUtils/NSDateExtenstions.swift
mit
1
// File.swift // ExSwift // // Created by Piergiuseppe Longo on 23/11/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension Date { // MARK: NSDate Manipulation // MARK: Date comparison /** Checks if self is after input NSDate :param: date NSDate to compare :returns: True if self is after the input NSDate, false otherwise */ public func isAfter(_ date: Date) -> Bool{ return self > date } /** Checks if self is before input NSDate :param: date NSDate to compare :returns: True if self is before the input NSDate, false otherwise */ public func isBefore(_ date: Date) -> Bool{ return self < date } // MARK: Getter /** Date year */ public var year : Int { get { return getComponent(.year) } } /** Date month */ public var month : Int { get { return getComponent(.month) } } /** Date weekday */ public var weekday : Int { get { return getComponent(.weekday) } } /** Date weekMonth */ public var weekMonth : Int { get { return getComponent(.weekOfMonth) } } /** Date days */ public var days : Int { get { return getComponent(.day) } } /** Date hours */ public var hours : Int { get { return getComponent(.hour) } } /** Date minuts */ public var minutes : Int { get { return getComponent(.minute) } } /** Date seconds */ public var seconds : Int { get { return getComponent(.second) } } /** Returns the value of the NSDate component :param: component NSCalendarUnit :returns: the value of the component */ public func getComponent (_ component : Calendar.Component) -> Int { let calendar = Calendar.current return calendar.component(component, from:self) } } func -(date: Date, otherDate: Date) -> TimeInterval { return date.timeIntervalSince(otherDate) } extension Date{ public var bx_shortDateString:String{ return bx_dateTimeStringWithFormatStyle(.short, timeStyle: .none) } public var bx_longDateString:String{ return bx_dateTimeStringWithFormatStyle(.medium, timeStyle: .none) } public var bx_shortTimeString:String{ return bx_dateTimeStringWithFormatStyle(.none, timeStyle: .short) } public var bx_dateTimeString:String{ return bx_dateTimeStringWithFormatStyle(.medium, timeStyle: .medium) } public var bx_shortDateTimeString:String{ return bx_dateTimeStringWithFormatStyle(.short, timeStyle: .short) } public func bx_dateTimeStringWithFormatStyle(_ dateStyle:DateFormatter.Style,timeStyle:DateFormatter.Style) -> String{ let dateFormatter = DateFormatter() dateFormatter.dateStyle = dateStyle dateFormatter.timeStyle = timeStyle return dateFormatter.string(from: self) } public var bx_relativeDateTimeString:String{ let secondsToNow = abs(Int(timeIntervalSinceNow)) let now = Date() let calendar = Calendar.current switch secondsToNow{ case 0..<60: return i18n("刚刚") case 60..<300: return str(i18n("%d分钟前"),secondsToNow / 60) default: if calendar.isDateInYesterday(self){ return i18n("昨天") + " " + bx_shortTimeString }else if calendar.isDateInToday(self){ return bx_shortTimeString }else if now.year == year{ return bx_shortDateString }else{ return self.bx_longDateString } } } }
11324c6371e63d4511728e3d96236d48
18.38587
120
0.631904
false
false
false
false
einsteinx2/iSub
refs/heads/master
Classes/Data Model/IgnoredArticlesRepository.swift
gpl-3.0
1
// // IgnoredArticlesRepository.swift // iSub Beta // // Created by Benjamin Baron on 9/17/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation struct IgnoredArticleRepository: ItemRepository { static let si = IgnoredArticleRepository() fileprivate let gr = GenericItemRepository.si let table = "ignoredArticles" let cachedTable = "ignoredArticles" let itemIdField = "articleId" func article(articleId: Int64, serverId: Int64) -> IgnoredArticle? { return gr.item(repository: self, itemId: articleId, serverId: serverId) } func allArticles(serverId: Int64? = nil) -> [IgnoredArticle] { return gr.allItems(repository: self, serverId: serverId) } @discardableResult func deleteAllArticles(serverId: Int64?) -> Bool { return gr.deleteAllItems(repository: self, serverId: serverId) } func isPersisted(article: IgnoredArticle) -> Bool { return gr.isPersisted(repository: self, item: article) } func isPersisted(articleId: Int64, serverId: Int64) -> Bool { return gr.isPersisted(repository: self, itemId: articleId, serverId: serverId) } func delete(article: IgnoredArticle) -> Bool { return gr.delete(repository: self, item: article) } func articles(serverId: Int64) -> [IgnoredArticle] { var articles = [IgnoredArticle]() Database.si.read.inDatabase { db in let table = tableName(repository: self) let query = "SELECT * FROM \(table) WHERE serverId = ?" do { let result = try db.executeQuery(query, serverId) while result.next() { let article = IgnoredArticle(result: result) articles.append(article) } result.close() } catch { printError(error) } } return articles } func insert(serverId: Int64, name: String) -> Bool { var success = true Database.si.write.inDatabase { db in do { let table = tableName(repository: self) let query = "INSERT INTO \(table) VALUES (?, ?, ?)" try db.executeUpdate(query, NSNull(), serverId, name) } catch { success = false printError(error) } } return success } func replace(article: IgnoredArticle) -> Bool { var success = true Database.si.write.inDatabase { db in do { let table = tableName(repository: self) let query = "REPLACE INTO \(table) VALUES (?, ?, ?)" try db.executeUpdate(query, article.articleId, article.serverId, article.name) } catch { success = false printError(error) } } return success } } extension IgnoredArticle: PersistedItem { convenience init(result: FMResultSet, repository: ItemRepository = IgnoredArticleRepository.si) { let articleId = result.longLongInt(forColumnIndex: 0) let serverId = result.longLongInt(forColumnIndex: 1) let name = result.string(forColumnIndex: 1) ?? "" let repository = repository as! IgnoredArticleRepository self.init(articleId: articleId, serverId: serverId, name: name, repository: repository) } class func item(itemId: Int64, serverId: Int64, repository: ItemRepository = IgnoredArticleRepository.si) -> Item? { return (repository as? IgnoredArticleRepository)?.article(articleId: itemId, serverId: serverId) } var isPersisted: Bool { return repository.isPersisted(article: self) } var hasCachedSubItems: Bool { return false } @discardableResult func replace() -> Bool { return repository.replace(article: self) } @discardableResult func cache() -> Bool { return repository.replace(article: self) } @discardableResult func delete() -> Bool { return repository.delete(article: self) } @discardableResult func deleteCache() -> Bool { return repository.delete(article: self) } func loadSubItems() { } }
9c3ced115282f1d5b6984a642d0f8e97
31.631579
120
0.595622
false
false
false
false
boundsj/ObjectiveDDP
refs/heads/master
Example/swiftExample/swiftddp/AppDelegate.swift
mit
2
// // AppDelegate.swift // swiftddp // // Created by Michael Arthur on 7/6/14. // Copyright (c) 2014 . All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navController: UINavigationController! // Override point for customization after application launch. creates our singleton var meteorClient = initialiseMeteor("pre2", "wss://ddptester.meteor.com/websocket"); func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { meteorClient.addSubscription("things") meteorClient.addSubscription("lists") let loginController:LoginViewController = LoginViewController(nibName: "LoginViewController", bundle: nil) loginController.meteor = self.meteorClient self.navController = UINavigationController(rootViewController:loginController) self.navController.navigationBarHidden = true //This needs to be modified to fix the screen size issue. (Currently a Bug) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.rootViewController = self.navController self.window!.makeKeyAndVisible() print(self.window?.frame) NSNotificationCenter.defaultCenter().addObserver(self, selector: "reportConnection", name: MeteorClientDidConnectNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "reportDisconnection", name: MeteorClientDidDisconnectNotification, object: nil) return true } func reportConnection() { print("================> connected to server!") } func reportDisconnection() { print("================> disconnected from server!") } 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:. } }
1b09ef6fcc1f5d54cf6679e086dd40de
44.2125
285
0.709428
false
false
false
false
mariopavlovic/codility-lessons
refs/heads/master
codility-lessons/codility-lessons/Lesson5.swift
mit
1
import Foundation public class Lesson5 { /*! Counts passing cars - parameter A: non-empty array of cars, valid values are 0 and 1. 0: car driving from W -> E 1: car driving from E -> W - returns: number of passing cars. If result is greather then 1,000,000,000 return will be -1 */ public func countPassingCars(A: [Int]) -> Int { var carsOnRightSide = A.reduce(0, combine: +) var numPassedCars = 0 for car in A { switch car { case 0: numPassedCars += carsOnRightSide case 1: carsOnRightSide -= 1 default: print("Error case") } if numPassedCars > 1000000000 { return -1 } } return numPassedCars } /*! Returns number of dividable elements by K in [A, B] range - parameter A: range stat (inclusive) - parameter B: range end (inclusive) - parameter K: divider - returns: Number of dividiable elements */ public func countDivisible(A: Int, _ B: Int, _ K: Int) -> Int { //cover the edge case where A is 0 if A == 0 { return (B - (B % K)) / K + 1 } return (B - (B % K)) / K - (A - 1) / K } /*! Calculates minimal impact factor of nucleotides. Impact factor: A - 1 C - 2 G - 3 T - 4 - parameter S: DNA sequence - parameter P: analyzed nucleotides start index - parameter Q: analyzed nucleotides end index - returns: Array of minimal impacts for start/end indexes */ public func minimalImpactFactors(S : String, _ P : [Int], _ Q : [Int]) -> [Int] { //sanitize guard P.count == Q.count else { return [] } //map let impactFactors = S.characters.map { (nucleotid) -> Int in return impactForNucleotid(nucleotid) } //slice and find minimal var result = Array(count: P.count, repeatedValue: 0) for (index, start) in P.enumerate() { let end = Q[index] if let minimal = impactFactors[start...end].minElement() { result[index] = minimal } } return result } func impactForNucleotid(nucleotid: Character) -> Int { switch (nucleotid) { case "A": return 1 case "C": return 2 case "G": return 3 case "T": return 4 default: return 0 } } /*! Returns a start index of a minimal array slice. Minimal is measured as a average value of slice elements - parameter A: input Int array - returns: start index of a slice */ public func findStartOfMinimalSlice(A : [Int]) -> Int { var minStart = -1 var minAvg = Float(Int.max) for index in 0 ..< A.count - 1 { var numItems = 2 var sum = A[index] + A[index + 1] while Float(sum) / Float(numItems) < minAvg { minStart = index minAvg = Float(sum) / Float(numItems) if (index + numItems < A.count ) { sum += A[index + numItems] numItems += 1 } else { break } } } return minStart } }
21975c1a730cff1c4ccc7398b4add8de
24.707143
85
0.479022
false
false
false
false
ilyapuchka/ViewControllerThinning
refs/heads/master
ViewControllerThinning/Views/ViewController.swift
mit
1
// // ViewController.swift // ViewControllerThinning // // Created by Ilya Puchka on 27.09.15. // Copyright © 2015 Ilya Puchka. All rights reserved. // import UIKit import SwiftNetworking class ViewController: UIViewController { override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override var nibName: String? { return "AuthView" } var authView: AuthView! { return view as! AuthView } @IBOutlet var formBehaviour: AuthFormBehaviour! { didSet { formBehaviour?.onLoggedIn = {[unowned self] in self.handleLogin($0, performedRequest: $1)} } } func handleLogin(error: NSError?, performedRequest: Bool) { if let error = error { authView.userNameInput.invalidInput = error.isInvalidUserNameError() authView.passwordInput.invalidInput = error.isInvalidPasswordError() if performedRequest { self.displayError(error) } } else { authView.userNameInput.invalidInput = false authView.passwordInput.invalidInput = false } } } extension APIClient { //Fake login func login(username: String!, password: String!, completion: (error: NSError?, performedRequest: Bool)->()) { var error: NSError? var performedRequest: Bool = false if username == nil || username.characters.count == 0 { error = NSError.errorWithUnderlyingError(NSError(code: .InvalidUserName), code: .InvalidCredentials) } else if password == nil || password.characters.count == 0 { error = NSError.errorWithUnderlyingError(NSError(code: .InvalidPassword), code: .InvalidCredentials) } else { error = NSError(code: NetworkErrorCode.BackendError, userInfo: [NSLocalizedDescriptionKey: "Failed to login."]) performedRequest = true } dispatch_after(1, dispatch_get_main_queue()) { completion(error: error, performedRequest: performedRequest) } } }
b64d061b1413e92cfd08d2adb956176e
28.930556
123
0.625986
false
false
false
false
vrrathod/codepath.twitter
refs/heads/master
codepath.twitter/codepath.twitter/TweetDetailsViewController.swift
mit
1
// // TweetDetailsViewController.swift // codepath.twitter // // Created by vr on 9/28/14. // Copyright (c) 2014 vr. All rights reserved. // import UIKit class TweetDetailsViewController: UIViewController { //MARK: UI Elements @IBOutlet weak private var profileImage: UIImageView! @IBOutlet weak private var userName: UILabel! @IBOutlet weak private var userHandle: UILabel! @IBOutlet weak private var tweetMessage: UILabel! @IBOutlet weak private var tweetTime: UILabel! @IBOutlet weak private var tweetRT: UILabel! @IBOutlet weak private var tweetFav: UILabel! // MARK: Private Data var tweetInfo:Tweet = Tweet() func setTweetInfo( tweet:Tweet ) { tweetInfo = tweet; dispatch_async(dispatch_get_main_queue(), { self.userName.text = self.tweetInfo.userName() self.userName.sizeToFit() self.userHandle.text = "@\(self.tweetInfo.userHandle())" self.userHandle.sizeToFit() self.tweetMessage.text = self.tweetInfo.tweetText() self.tweetMessage.sizeToFit() self.tweetTime.text = self.tweetInfo.tweetTime() self.tweetTime.sizeToFit() self.tweetRT.text = self.tweetInfo.tweetRT() self.tweetRT.sizeToFit() self.tweetFav.text = self.tweetInfo.favoriteCount() self.tweetFav.sizeToFit() }) } func setUserProfilePic( pic:UIImage ){ dispatch_async(dispatch_get_main_queue(), { self.profileImage.image = pic self.profileImage.sizeToFit() }); } // MARK: overrides override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Interactions @IBAction func doRetweet(sender: UIButton) { TwitterClient.sharedClient.retweet(tweetInfo.tweetID()); } @IBAction func doFav(sender: AnyObject) { TwitterClient.sharedClient.favorite(tweetInfo.tweetID()) } /* // 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. } */ }
f970ae702ca44596f0cb497e613833cd
28.898876
106
0.626832
false
false
false
false
aquarchitect/MyKit
refs/heads/master
Sources/macOS/Extensions/AppKit/NSImage+.swift
mit
1
// // NSImage+.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2016 Hai Nguyen. // import AppKit public extension NSImage { func image(withTintColor color: NSColor) -> NSImage { guard self.isTemplate else { return self } return (self.copy() as? NSImage)?.then { $0.lockFocus() color.set() #if swift(>=4.0) NSRect(origin: .zero, size: $0.size).fill(using: .sourceAtop) #else NSRectFillUsingOperation(.init(origin: .zero, size: $0.size), .sourceAtop) #endif $0.unlockFocus() $0.isTemplate = false } ?? self } } public extension NSImage { class func render(_ attributedString: NSAttributedString, scale: CGFloat = 1.0) -> NSImage { let transform = CGAffineTransform(scaleX: scale, y: scale) let size = attributedString.size().applying(transform) let rect = CGRect(origin: .zero, size: size) return NSImage(size: size).then { $0.lockFocus() attributedString.draw(in: rect) $0.unlockFocus() } } }
bdc8b5cb8448f123da2230feec8e61c1
23.733333
96
0.58221
false
false
false
false
wmcginty/Shifty
refs/heads/main
Sources/Shifty/Model/Shared/ReplicationStrategy.swift
mit
1
// // ReplicationStrategy.swift // Shifty // // Created by William McGinty on 8/30/19. // Copyright © 2019 Will McGinty. All rights reserved. // import UIKit public enum ReplicationStrategy { public typealias Configurator = (_ baseView: UIView) -> UIView case snapshot case configured(Configurator) case none // MARK: - Interface var canVisuallyShift: Bool { switch self { case .snapshot: return false default: return true } } public func configuredShiftingView(for baseView: UIView, afterScreenUpdates: Bool) -> UIView { switch self { case .snapshot: return snapshot(of: baseView, afterScreenUpdates: afterScreenUpdates) case .configured(let configurator): return configurator(baseView) case .none: return baseView } } } // MARK: - Helper private extension ReplicationStrategy { func snapshot(of baseView: UIView, afterScreenUpdates: Bool) -> SnapshotView { //Ensure we take the snapshot with no corner radius, and then apply that radius to the snapshot (and reset the baseView). let cornerRadius = baseView.layer.cornerRadius baseView.layer.cornerRadius = 0 guard let contentView = baseView.snapshotView(afterScreenUpdates: afterScreenUpdates) else { fatalError("Unable to snapshot view: \(baseView)") } let snapshot = SnapshotView(contentView: contentView) //Apply the known corner radius to both the replicant view and the base view snapshot.layer.cornerRadius = cornerRadius snapshot.layer.masksToBounds = cornerRadius > 0 baseView.layer.cornerRadius = cornerRadius return snapshot } } // MARK: - Convenience public extension ReplicationStrategy { static let replication = ReplicationStrategy.configured { baseView -> UIView in return baseView.replicant } static func debug(with backgroundColor: UIColor = .red, alpha: CGFloat = 0.5) -> ReplicationStrategy { return ReplicationStrategy.configured { baseView -> UIView in let copy = UIView(frame: baseView.frame) copy.backgroundColor = backgroundColor.withAlphaComponent(alpha) copy.layer.cornerRadius = baseView.layer.cornerRadius copy.layer.masksToBounds = baseView.layer.masksToBounds return copy } } }
adfc7e964e19d84988bfa6034b3de33a
32.520548
153
0.66653
false
true
false
false
arietis/codility-swift
refs/heads/master
4.3.swift
mit
1
public func solution(inout A : [Int]) -> Int { // write your code in Swift 2.2 var a: [Int:Bool] = [:] for i in A { a[i] = true } var i = 1 while true { if a[i] == nil { return i } i += 1 } }
80d8addcc9f7b244401a3661775cdd69
15
46
0.368056
false
false
false
false
tristanchu/FlavorFinder
refs/heads/master
FlavorFinder/FlavorFinder/SettingsPageController.swift
mit
1
// // SettingsPageController.swift // FlavorFinder // // Created by Courtney Ligh on 2/10/16. // Copyright © 2016 TeamFive. All rights reserved. // import Foundation import UIKit import Parse class SettingsPageController : LoginModuleParentViewController { // MARK: Properties: -------------------------------------------------- // Labels: @IBOutlet weak var pagePromptLabel: UILabel! @IBOutlet weak var passwordSentLabel: UILabel! @IBOutlet weak var containerView: UIView! var loggedOutMessage : UILabel? // Segues: let segueLoginEmbedded = "embedSettingsToLogin" // Text: let pageTitle = "Settings" let loggedOutText = "You must be logged in to have settings." let LOGOUT_TEXT = "Logged out of " // Placement: let loggedOutPlacementHeightMultiplier : CGFloat = 0.5 // Buttons: @IBOutlet weak var resetPasswordButton: UIButton! @IBOutlet weak var logoutButton: UIButton! // Button actions: @IBAction func resetPasswordBtn(sender: UIButton) { passwordSentLabel.hidden = false // Commented out because it actually sents an email: // requestPasswordReset() } @IBAction func logoutBtn(sender: UIButton) { if isUserLoggedIn() { let userName = currentUser!.username! let ToastText = "\(LOGOUT_TEXT)\(userName)" PFUser.logOutInBackground() currentUser = nil displayLoggedOut() self.view.makeToast(ToastText, duration: TOAST_DURATION, position: .Bottom) } } // MARK: Override methods: ---------------------------------------------- /* viewDidLoad: - Setup when view is loaded into memory */ override func viewDidLoad() { super.viewDidLoad() // set button borders: setDefaultButtonUI(logoutButton) setSecondaryButtonUI(resetPasswordButton) view.backgroundColor = BACKGROUND_COLOR } /* viewDidAppear: - Setup when user goes into page. */ override func viewDidAppear(animated: Bool) { // Get navigation bar on top: if let navi = self.tabBarController?.navigationController as? MainNavigationController { self.tabBarController?.navigationItem.setLeftBarButtonItems( [], animated: true) self.tabBarController?.navigationItem.setRightBarButtonItems( [], animated: true) navi.reset_navigationBar() self.tabBarController?.navigationItem.title = pageTitle } super.viewDidAppear(animated) if let _ = loggedOutMessage { // avoid stacking labels loggedOutMessage?.hidden = true loggedOutMessage?.removeFromSuperview() } loggedOutMessage = emptyBackgroundText(loggedOutText, view: self.view) // move message up to make room loggedOutMessage?.frame.size.height = self.view.frame.size.height * loggedOutPlacementHeightMultiplier self.view.addSubview(loggedOutMessage!) setUpLoginContainerUI() if isUserLoggedIn() { displayLoggedIn() } else { displayLoggedOut() } } /* prepareForSegue: - setup before seguing - prior to container's embed segue, will set up parent class variable to have access to contained VC */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if self.segueEmbeddedContent == nil { self.setValue(segueLoginEmbedded, forKey: "segueEmbeddedContent") } super.prepareForSegue(segue, sender: sender) } /* loginSucceeded: - handle successful login via module */ override func loginSucceeded() { super.loginSucceeded() // hides module displayLoggedIn() } // MARK: Other functions ------------------------------------------------- /* displayLoggedIn - hides or unhides subviews for the logged-in display */ func displayLoggedIn() { // Logged-in UI logoutButton.hidden = false resetPasswordButton.hidden = false passwordSentLabel.hidden = true pagePromptLabel.hidden = false // Logged-out UI loggedOutMessage?.hidden = true containerVC?.view.hidden = true // embedded login module } /* displayLoggedOut - hides or unhides subviews for the logged-out display */ func displayLoggedOut() { // Logged-in UI logoutButton.hidden = true resetPasswordButton.hidden = true passwordSentLabel.hidden = true pagePromptLabel.hidden = true // Logged-out UI loggedOutMessage?.hidden = false containerVC?.view.hidden = false // embedded login module goToLogin() } }
05bf639dbc21fd211b76001f66ffc031
30
110
0.604557
false
false
false
false
soapyigu/LeetCode_Swift
refs/heads/master
Stack/SimplifyPath.swift
mit
1
/** * Question Link: https://leetcode.com/problems/simplify-path/ * Primary idea: Use a stack, normal to push, .. to pop * Time Complexity: O(n), Space Complexity: O(n) */ class SimplifyPath { func simplifyPath(_ path: String) -> String { let dirs = path.components(separatedBy: "/") var stack = [String]() for dir in dirs { if dir == "." { continue } else if dir == ".." { if !stack.isEmpty { stack.removeLast() } } else { if dir != "" { stack.append(dir) } } } let res = stack.reduce("") { total, dir in "\(total)/\(dir)" } return res.isEmpty ? "/" : res } }
177ea015caf6308be31e1e9a9cd64899
26.266667
70
0.432069
false
false
false
false
gribozavr/swift
refs/heads/master
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-class-1argument-1distinct_use.swift
apache-2.0
1
// RUN: %swift -target %module-target-future -emit-ir -prespecialize-generic-metadata %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceC5ValueVySS_SiGMf" = internal constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceC5ValueVySS_SiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main9NamespaceC5ValueVMn" to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] final class Namespace<Arg> { struct Value<First> { let first: First } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main9NamespaceC5ValueVySS_SiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Namespace<String>.Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]], %swift.type*, %swift.type*) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]] // CHECK: [[TYPE_COMPARISON_1]]: // CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]] // CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]] // CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]] // CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]] // CHECK: br i1 [[EQUAL_TYPES_1_2]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED_1]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main9NamespaceC5ValueVySS_SiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* [[ERASED_TYPE_2]], i8* undef, %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main9NamespaceC5ValueVMn" to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
568d59e4b9fb054977018ddc59b7e4b7
56.269841
360
0.611419
false
false
false
false
AirChen/ACSwiftDemoes
refs/heads/master
Target13-Machine/ViewController.swift
mit
1
// // ViewController.swift // Target13-Machine // // Created by Air_chen on 2016/11/7. // Copyright © 2016年 Air_chen. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var picker:UIPickerView! @IBOutlet weak var beginBtn:UIButton! @IBOutlet weak var lab:UILabel! var imageArray = [String]() var dataArray1 = [Int]() var dataArray2 = [Int]() var dataArray3 = [Int]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imageArray = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"] for _ in 0...99 { dataArray1.append((Int)(arc4random() % 10 )) dataArray2.append((Int)(arc4random() % 10 )) dataArray3.append((Int)(arc4random() % 10 )) } lab.text = "" picker.delegate = self picker.dataSource = self beginBtn.addTarget(self, action: #selector(ViewController.touchBeginAction), for: UIControlEvents.touchUpInside) } func touchBeginAction() { picker.selectRow((Int)(arc4random() % 10 ), inComponent: 0, animated: true) picker.selectRow((Int)(arc4random() % 10 ), inComponent: 1, animated: true) picker.selectRow((Int)(arc4random() % 10 ), inComponent: 2, animated: true) if (dataArray1[picker.selectedRow(inComponent: 0)] == dataArray2[picker.selectedRow(inComponent: 1)]) && (dataArray2[picker.selectedRow(inComponent: 1)] == dataArray3[picker.selectedRow(inComponent: 2)]) { lab.text = "Bingo!!" }else{ lab.text = "💔" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate{ func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 100 } func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 100.0 } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 100.0 } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let pickerLab = UILabel() if component == 0{ pickerLab.text = imageArray[Int(dataArray1[row])] }else if component == 1{ pickerLab.text = imageArray[Int(dataArray2[row])] }else{ pickerLab.text = imageArray[Int(dataArray3[row])] } pickerLab.font = UIFont(name: "Apple Color Emoji", size: 80) pickerLab.textAlignment = NSTextAlignment.center return pickerLab } }
af6f9387a59726f73f2fb707192084dc
29.91
213
0.599159
false
false
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleLeftRight.Individual.swift
apache-2.0
1
// // MiddleLeftRight.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct MiddleLeftRight { let middleLeft: LayoutElement.Point let right: LayoutElement.Horizontal } } // MARK: - Make Frame extension IndividualProperty.MiddleLeftRight { private func makeFrame(middleLeft: Point, right: Float, top: Float) -> Rect { let height = (middleLeft.y - top).double return self.makeFrame(middleLeft: middleLeft, right: right, height: height) } private func makeFrame(middleLeft: Point, right: Float, bottom: Float) -> Rect { let height = (bottom - middleLeft.y).double return self.makeFrame(middleLeft: middleLeft, right: right, height: height) } private func makeFrame(middleLeft: Point, right: Float, height: Float) -> Rect { let x = middleLeft.x let y = middleLeft.y - height.half let width = right - middleLeft.x let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Line - // MARK: Top extension IndividualProperty.MiddleLeftRight: LayoutPropertyCanStoreTopToEvaluateFrameType { public func evaluateFrame(top: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect { let middleLeft = self.middleLeft.evaluated(from: parameters) let right = self.right.evaluated(from: parameters) let top = top.evaluated(from: parameters) return self.makeFrame(middleLeft: middleLeft, right: right, top: top) } } // MARK: Bottom extension IndividualProperty.MiddleLeftRight: LayoutPropertyCanStoreBottomToEvaluateFrameType { public func evaluateFrame(bottom: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect { let middleLeft = self.middleLeft.evaluated(from: parameters) let right = self.right.evaluated(from: parameters) let bottom = bottom.evaluated(from: parameters) return self.makeFrame(middleLeft: middleLeft, right: right, bottom: bottom) } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.MiddleLeftRight: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let middleLeft = self.middleLeft.evaluated(from: parameters) let right = self.right.evaluated(from: parameters) let width = right - middleLeft.x let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(middleLeft: middleLeft, right: right, height: height) } }
91f31cfcafb5a8e69318be0094ef8782
25.49505
118
0.738416
false
false
false
false
gscalzo/PrettyWeather
refs/heads/master
PrettyWeather/CurrentWeatherView.swift
mit
1
// // CurrentWeatherView.swift // PrettyWeather // // Created by Giordano Scalzo on 03/02/2015. // Copyright (c) 2015 Effective Code. All rights reserved. // import UIKit import Cartography import LatoFont import WeatherIconsKit class CurrentWeatherView: UIView { private var didSetupConstraints = false private let cityLbl = UILabel() private let maxTempLbl = UILabel() private let minTempLbl = UILabel() private let iconLbl = UILabel() private let weatherLbl = UILabel() private let currentTempLbl = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() style() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { if didSetupConstraints { super.updateConstraints() return } layoutView() super.updateConstraints() didSetupConstraints = true } } // MARK: Setup private extension CurrentWeatherView{ func setup(){ addSubview(cityLbl) addSubview(currentTempLbl) addSubview(maxTempLbl) addSubview(minTempLbl) addSubview(iconLbl) addSubview(weatherLbl) } } // MARK: Layout private extension CurrentWeatherView{ func layoutView(){ layout(self) { view in view.height == 160 } layout(iconLbl) { view in view.top == view.superview!.top view.left == view.superview!.left + 20 view.width == 30 view.width == view.height } layout(weatherLbl, iconLbl) { view, view2 in view.top == view2.top view.left == view2.right + 10 view.height == view2.height view.width == 200 } layout(currentTempLbl, iconLbl) { view, view2 in view.top == view2.bottom view.left == view2.left } layout(currentTempLbl, minTempLbl) { view, view2 in view.bottom == view2.top view.left == view2.left } layout(minTempLbl) { view in view.bottom == view.superview!.bottom view.height == 30 } layout(maxTempLbl, minTempLbl) { view, view2 in view.top == view2.top view.height == view2.height view.left == view2.right + 10 } layout(cityLbl) { view in view.bottom == view.superview!.bottom view.right == view.superview!.right - 10 view.height == 30 view.width == 200 } } } // MARK: Style private extension CurrentWeatherView{ func style(){ iconLbl.textColor = UIColor.whiteColor() weatherLbl.font = UIFont.latoLightFontOfSize(20) weatherLbl.textColor = UIColor.whiteColor() currentTempLbl.font = UIFont.latoLightFontOfSize(96) currentTempLbl.textColor = UIColor.whiteColor() maxTempLbl.font = UIFont.latoLightFontOfSize(18) maxTempLbl.textColor = UIColor.whiteColor() minTempLbl.font = UIFont.latoLightFontOfSize(18) minTempLbl.textColor = UIColor.whiteColor() cityLbl.font = UIFont.latoLightFontOfSize(18) cityLbl.textColor = UIColor.whiteColor() cityLbl.textAlignment = .Right } } // MARK: Render extension CurrentWeatherView{ func render(weatherCondition: WeatherCondition){ iconLbl.attributedText = iconStringFromIcon(weatherCondition.icon!, 20) weatherLbl.text = weatherCondition.weather var usesMetric = false if let localeSystem = NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem) as? Bool { usesMetric = localeSystem } if usesMetric { minTempLbl.text = "\(weatherCondition.minTempCelsius.roundToInt())°" maxTempLbl.text = "\(weatherCondition.maxTempCelsius.roundToInt())°" currentTempLbl.text = "\(weatherCondition.tempCelsius.roundToInt())°" } else { minTempLbl.text = "\(weatherCondition.minTempFahrenheit.roundToInt())°" maxTempLbl.text = "\(weatherCondition.maxTempFahrenheit.roundToInt())°" currentTempLbl.text = "\(weatherCondition.tempFahrenheit.roundToInt())°" } cityLbl.text = weatherCondition.cityName ?? "" } }
eae1a869f651e16442749e28909f1a1e
29.147651
104
0.601069
false
false
false
false
EvgeneOskin/animals-mobile
refs/heads/master
ios/HelloAnimals/AppDelegate.swift
apache-2.0
2
// // AppDelegate.swift // HelloAnimals // // Created by Eugene Oskin on 02.07.15. // Copyright (c) 2015 Eugene Oskin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self 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:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } }
7cf306dfe82f179623b8cda3f20bd149
52.206349
285
0.750895
false
false
false
false
zhubinchen/MarkLite
refs/heads/master
MarkLite/Utils/Localization.swift
gpl-3.0
2
// // Localization.swift // Markdown // // Created by zhubch on 2017/8/21. // Copyright © 2017年 zhubch. All rights reserved. // import UIKit fileprivate let ignoreTag = 4654 prefix operator / prefix func /(string: String) -> String { return string.localizations } extension String { var localizations: String { return NSLocalizedString(self, comment: "") } } protocol Localizable { func localize() } extension UIButton: Localizable { func localize() { setTitle(/(title(for: .normal) ?? ""), for: .normal) setTitle(/(title(for: .disabled) ?? ""), for: .disabled) setTitle(/(title(for: .selected) ?? ""), for: .selected) } } extension UITextField: Localizable { func localize() { text = /(text ?? "") placeholder = /(placeholder ?? "") } } extension UILabel: Localizable { func localize() { text = /(text ?? "") } } private let swizzling: (UIView.Type) -> () = { view in let originalSelector = #selector(view.awakeFromNib) let swizzledSelector = #selector(view.swizzled_localization_awakeFromNib) let originalMethod = class_getInstanceMethod(view, originalSelector) let swizzledMethod = class_getInstanceMethod(view, swizzledSelector) let didAddMethod = class_addMethod(view, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) if didAddMethod { class_replaceMethod(view, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) } else { method_exchangeImplementations(originalMethod!, swizzledMethod!) } } extension UIView { open class func initializeOnceMethod() { guard self === UIView.self else { return } swizzling(self) } @objc func swizzled_localization_awakeFromNib() { swizzled_localization_awakeFromNib() if let localizableView = self as? Localizable { if tag != ignoreTag { localizableView.localize() } } } }
149b863a8c32872b46696b51f7280a44
24.60241
146
0.637647
false
false
false
false
knutnyg/ios-iou
refs/heads/master
iou/LocaleUtils.swift
bsd-2-clause
1
import Foundation func localeStringFromNumber(locale:NSLocale, number:Double) -> String { let formatter:NSNumberFormatter = NSNumberFormatter() formatter.numberStyle = .CurrencyStyle formatter.locale = locale return formatter.stringFromNumber(number)! } func localeNumberFromString(string:String) -> Double{ let formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle return formatter.numberFromString(string)!.doubleValue }
35bbae378757310be0506c7a8e107886
25.277778
71
0.769556
false
false
false
false
victorchee/BluetoothPi
refs/heads/master
BluetoothPi/BluetoothPi/BeaconReceiverController.swift
mit
1
// // BeaconReceiver.swift // BluetoothPi // // Created by qihaijun on 1/30/15. // Copyright (c) 2015 VictorChee. All rights reserved. // import UIKit import CoreLocation class BeaconReceiverController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var statusLabel: UILabel! let locationManager: CLLocationManager = CLLocationManager() var beaconRegion:CLBeaconRegion! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationManager.requestWhenInUseAuthorization() // locationManager.requestAlwaysAuthorization() locationManager.delegate = self let uuid:NSUUID = NSUUID(UUIDString: "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0")! beaconRegion = CLBeaconRegion(proximityUUID: uuid, identifier: "") beaconRegion.notifyEntryStateOnDisplay = true beaconRegion.notifyOnEntry = true beaconRegion.notifyOnExit = true locationManager.startRangingBeaconsInRegion(beaconRegion) locationManager.startMonitoringForRegion(beaconRegion) // locationManager.stopMonitoringForRegion(beaconRegion) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // start ranging locationManager.startRangingBeaconsInRegion(beaconRegion) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // stop ranging locationManager.stopRangingBeaconsInRegion(beaconRegion) } /* // 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. } */ // MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { if !beacons.isEmpty { println("Beacons found") let nearestBeacon: CLBeacon = beacons.first as CLBeacon println("nearest uuid = \(nearestBeacon.proximityUUID)\nnearest major = \(nearestBeacon.major)\nnearest minor = \(nearestBeacon.minor)\nnearest rssi = \(nearestBeacon.rssi)\nnearest accuracy = \(nearestBeacon.accuracy)") switch nearestBeacon.proximity { case CLProximity.Unknown : println("Beacon proximity unknown") case .Far : println("Beacon proximity far") case .Near : println("Beacon proximity near") case .Immediate : println("Beacon proximity immediate") } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.statusLabel.text = "uuid = \(nearestBeacon.proximityUUID.UUIDString)\nmajor = \(nearestBeacon.major)\nminor = \(nearestBeacon.minor)\nrssi = \(nearestBeacon.rssi)\naccuracy = \(nearestBeacon.accuracy)" }) } else { println("No bvim eacons found") dispatch_async(dispatch_get_main_queue(), { () -> Void in self.statusLabel.text = nil }) } } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { if region.isKindOfClass(CLBeaconRegion) { var localNotification: UILocalNotification = UILocalNotification() localNotification.alertBody = "Will enter region" UIApplication.sharedApplication().presentLocalNotificationNow(localNotification) locationManager.startRangingBeaconsInRegion(region as CLBeaconRegion) } } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { if region.isKindOfClass(CLBeaconRegion) { var localNotification: UILocalNotification = UILocalNotification() localNotification.alertBody = "Will exit region" UIApplication.sharedApplication().presentLocalNotificationNow(localNotification) locationManager.stopRangingBeaconsInRegion(region as CLBeaconRegion) } } }
baa3bf1ebb9d23f5c86249dc5ab3dd82
39.429825
232
0.662834
false
false
false
false
sberrevoets/SDCAlertView
refs/heads/master
Source/Presentation/AnimationController.swift
mit
1
import UIKit private let kInitialScale: CGFloat = 1.2 private let kSpringDamping: CGFloat = 45.71 private let kSpringVelocity: CGFloat = 0 class AnimationController: NSObject, UIViewControllerAnimatedTransitioning { private var isPresentation = false init(presentation: Bool) { self.isPresentation = presentation } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.404 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let toController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let fromView = fromController.view, let toView = toController.view else { return } if self.isPresentation { transitionContext.containerView.addSubview(toView) } let animatingController = self.isPresentation ? toController : fromController let animatingView = animatingController.view animatingView?.frame = transitionContext.finalFrame(for: animatingController) if self.isPresentation { animatingView?.transform = CGAffineTransform(scaleX: kInitialScale, y: kInitialScale) animatingView?.alpha = 0 self.animate({ animatingView?.transform = CGAffineTransform(scaleX: 1, y: 1) animatingView?.alpha = 1 }, inContext: transitionContext, withCompletion: { finished in transitionContext.completeTransition(finished) }) } else { self.animate({ animatingView?.alpha = 0 }, inContext: transitionContext, withCompletion: { finished in fromView.removeFromSuperview() transitionContext.completeTransition(finished) }) } } private func animate(_ animations: @escaping (() -> Void), inContext context: UIViewControllerContextTransitioning, withCompletion completion: @escaping (Bool) -> Void) { UIView.animate(withDuration: self.transitionDuration(using: context), delay: 0, usingSpringWithDamping: kSpringDamping, initialSpringVelocity: kSpringVelocity, options: [], animations: animations, completion: completion) } }
c4198190ffc8ac2512f97e94849a991b
36.956522
109
0.642612
false
false
false
false
googleapis/google-api-swift-client
refs/heads/main
Sources/google-cli-swift-generator/main.swift
apache-2.0
1
// Copyright 2019 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 Discovery var stderr = FileHandle.standardError func printerr(_ s : String) { stderr.write(("google-cli-swift-generator WARNING: "+s+"\n").data(using:.utf8)!) } let ParameterPrefix = "" let RequestObjectPrefix = "request_" func optionDeclaration(_ prefix: String, _ name: String, _ schema: Schema) -> String { if schema.type == "string" { // https://github.com/kylef/Commander/issues/49 var s = "Options<String>(\"" s += prefix + name s += "\", default: [], count: 1, description: \"" if let d = schema.description { s += d.oneLine() } s += "\")," return s } else if schema.type == "integer" { var s = "Options<Int>(\"" s += prefix + name s += "\", default: [], count: 1, description: \"" if let d = schema.description { s += d.oneLine() } s += "\")," return s } else if let items = schema.items, schema.type == "array", items.type == "string" { var s = "VariadicOption<String>(\"" s += prefix + name s += "\", default: [], description: \"" if let d = schema.description { s += d.oneLine() } s += "\")," return s } else if let items = schema.items, schema.type == "array", items.type == "any" { var s = "VariadicOption<JSONAny>(\"" s += prefix + name s += "\", default: [], description: \"" if let d = schema.description { s += d.oneLine() } s += "\")," return s } else { let jsonData = try! JSONEncoder().encode(schema) let jsonString = String(data: jsonData, encoding: .utf8)! printerr("Unsupported schema for option \(prefix)\(name): \(jsonString)") return "" } } extension Discovery.Method { func parametersString() -> String { var s = "" if let parameters = parameters { for p in parameters.sorted(by: { $0.key < $1.key }) { if p.value.type == "string" || p.value.type == "integer" { if s != "" { s += ", " } s += ParameterPrefix + p.key } } } return s } func requestPropertiesString(requestSchema: Schema?) -> String { var s = "" if let requestSchema = requestSchema, let properties = requestSchema.properties { for p in properties.sorted(by: { $0.key < $1.key }) { if p.value.type == "string" || p.value.type == "integer" { if s != "" { s += ", " } s += RequestObjectPrefix + p.key } else if let items = p.value.items, p.value.type == "array", items.type == "string" { if s != "" { s += ", " } s += RequestObjectPrefix + p.key } else if let items = p.value.items, p.value.type == "array", items.type == "any" { if s != "" { s += ", " } s += RequestObjectPrefix + p.key } } } return s } func Invocation(serviceName: String, resourceName : String, resource: Discovery.Resource, methodName : String, method: Discovery.Method, requestSchema: Schema?) -> String { var s = "\n" s.addLine(indent:4, "$0.command(") s.addLine(indent:6, "\"" + resourceName + "." + methodName + "\",") if let parameters = parameters { for p in parameters.sorted(by: { $0.key < $1.key }) { let d = optionDeclaration(ParameterPrefix, p.key, p.value) if d.count > 0 { s.addLine(indent:6, d) } } } if let requestSchema = requestSchema, let properties = requestSchema.properties { for p in properties.sorted(by: { $0.key < $1.key }) { let d = optionDeclaration(RequestObjectPrefix, p.key, p.value) if d.count > 0 { s.addLine(indent:6, d) } } } if let description = method.description { s.addLine(indent:6, "description: \"" + description.oneLine() + "\") {") } else { s.addLine(indent:6, "description: \"\") {") } let p = self.parametersString() let r = self.requestPropertiesString(requestSchema: requestSchema) if p != "" && r != "" { s.addLine(indent:6, p + ", " + r + " in") } else if p != "" { s.addLine(indent:6, p + " in") } else if r != "" { s.addLine(indent:6, r + " in") } s.addLine(indent:6, "do {") if self.HasParameters() { s.addLine(indent:8, "var parameters = " + serviceName.capitalized() + "." + self.ParametersTypeName(resource:resourceName, method:methodName) + "()") if let parameters = parameters { for p in parameters.sorted(by: { $0.key < $1.key }) { if p.value.type == "string" || p.value.type == "integer" { s.addLine(indent:8, "if let " + ParameterPrefix + p.key + " = " + ParameterPrefix + p.key + ".first {") s.addLine(indent:10, "parameters." + p.key + " = " + ParameterPrefix + p.key) s.addLine(indent:8, "}") } } } } if self.HasRequest() { s.addLine(indent:8, "var request = " + serviceName.capitalized() + "." + self.RequestTypeName() + "()") if let requestSchema = requestSchema, let properties = requestSchema.properties { for p in properties.sorted(by: { $0.key < $1.key }) { if p.value.type == "string" || p.value.type == "integer" { s.addLine(indent:8, "if let " + RequestObjectPrefix + p.key + " = " + RequestObjectPrefix + p.key + ".first {") s.addLine(indent:10, "request." + p.key + " = " + RequestObjectPrefix + p.key) s.addLine(indent:8, "}") } else if let items = p.value.items, p.value.type == "array", items.type == "string" { s.addLine(indent:8, "if " + RequestObjectPrefix + p.key + ".count > 0 {") s.addLine(indent:10, "request." + p.key + " = " + RequestObjectPrefix + p.key) s.addLine(indent:8, "}") } } } } s.addLine(indent:8, "let sem = DispatchSemaphore(value: 0)") let fullMethodName = (resourceName + "_" + methodName) var invocation = "try " + serviceName + "." + fullMethodName + "(" if self.HasRequest() { if self.HasParameters() { invocation += "request: request, parameters:parameters" } else { invocation += "request:request" } } else { if self.HasParameters() { invocation += "parameters:parameters" } } invocation += ") {" s.addLine(indent:8, invocation) var arguments = "" if self.HasResponse() { arguments += "response, " } arguments += "error in" s.addLine(indent:10, arguments) if self.HasResponse() { s.addLine(indent:10, "if let response = response { print (\"RESPONSE: \\(response)\") }") } s.addLine(indent:10, "if let error = error { print (\"ERROR: \\(error)\") }") s.addLine(indent:10, "sem.signal()") s.addLine(indent:8, "}") s.addLine(indent:8, "_ = sem.wait()") s.addLine(indent:6, "} catch let error {") s.addLine(indent:8, "print (\"Client error: \\(error)\")") s.addLine(indent:6, "}") s.addLine(indent:4, "}") return s } } extension Discovery.Resource { func generate(service: Service, name: String) -> String { var s = "" if let methods = self.methods { for m in methods.sorted(by: { $0.key < $1.key }) { let requestSchema = service.schema(name: m.value.RequestTypeName()) s += m.value.Invocation(serviceName:service.serviceName(), resourceName:name, resource:self, methodName:m.key, method:m.value, requestSchema:requestSchema ) } } if let resources = self.resources { for r in resources.sorted(by: { $0.key < $1.key }) { s += r.value.generate(service: service, name: name + "_" + r.key) } } return s } } extension Discovery.Service { func serviceTitle() -> String { return self.name.capitalized() } func serviceName() -> String { return self.name } func scopes() -> [String] { var scopeSet = Set<String>() if let resources = resources { for r in resources { if let methods = r.value.methods { for m in methods { if let scopes = m.value.scopes { for scope in scopes { scopeSet.insert(scope) } } } } } } return scopeSet.sorted() } func generate() -> String { var s = Discovery.License s.addLine() for i in ["Foundation", "Dispatch", "OAuth2", "GoogleAPIRuntime", "Commander"] { s.addLine("import " + i) } s.addLine() s.addLine("let CLIENT_CREDENTIALS = \"" + serviceName() + ".json\"") s.addLine("let TOKEN = \"" + serviceName() + ".json\"") s.addLine() s.addLine("func main() throws {") let scopes = self.scopes() if scopes.count == 1 { s.addLine(indent:2, "let scopes = \(scopes)") } else { s.addLine(indent:2, "let scopes = [") s += " \"" + scopes.joined(separator:"\",\n \"") + "\"]\n" } s.addLine() s.addLine(indent:2, "guard let tokenProvider = BrowserTokenProvider(credentials:CLIENT_CREDENTIALS, token:TOKEN) else {") s.addLine(indent:4, "return") s.addLine(indent:2, "}") s.addLine(indent:2, "let \(self.serviceName()) = try \(self.serviceTitle())(tokenProvider:tokenProvider)") s.addLine() s.addLine(indent:2, "let group = Group {") s.addLine(indent:4, "$0.command(\"login\", description:\"Log in with browser-based authentication.\") {") s.addLine(indent:6, "try tokenProvider.signIn(scopes:scopes)") s.addLine(indent:6, "try tokenProvider.saveToken(TOKEN)") s.addLine(indent:4, "}") if let resources = resources { for r in resources.sorted(by: { $0.key < $1.key }) { s += r.value.generate(service: self, name: r.key) } } s.addLine(indent:2, "}") s.addLine(indent:2, "group.run()") s.addLine(indent:0, "}") s.addLine() s.addLine(indent:0, "do {") s.addLine(indent:2, "try main()") s.addLine(indent:0, "} catch (let error) {") s.addLine(indent:2, "print(\"Application error: \\(error)\")") s.addLine(indent:0, "}") return s } } func main() throws { let arguments = CommandLine.arguments let path = arguments[1] let data = try Data(contentsOf: URL(fileURLWithPath: path)) let decoder = JSONDecoder() do { let service = try decoder.decode(Service.self, from: data) let code = service.generate() print(code) } catch { print("error \(error)\n") } } do { try main() } catch (let error) { print("ERROR: \(error)\n") }
4fe274fc0d08b126fbd61ef5a1632402
31.74221
125
0.548192
false
false
false
false
a2/Kitty
refs/heads/master
Kitty Share Extension/ShareViewController.swift
mit
1
// // ShareViewController.swift // Kitty Share Extension // // Created by Alexsander Akers on 11/9/15. // Copyright © 2015 Rocket Apps Limited. All rights reserved. // import Cocoa import KittyKit class ShareViewController: NSViewController { @IBOutlet var resultTextField: NSTextField! @IBOutlet var slider: NSSlider! var APIClient: APIClientProtocol = KittyKit.APIClient() var URL: String! var shortenedURL: String! override var nibName: String? { return "ShareViewController" } override func loadView() { super.loadView() if let item = extensionContext!.inputItems.first as? NSExtensionItem, attachments = item.attachments, itemProvider = attachments.first as? NSItemProvider where itemProvider.hasItemConformingToTypeIdentifier(kUTTypeURL as String) { itemProvider.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil) { (URL: NSSecureCoding?, error: NSError?) in self.URL = (URL as! NSURL).absoluteString } } else { print("No attachments") } } @IBAction func send(sender: AnyObject?) { if resultTextField.hidden { APIClient.fetchAuthenticityToken { result in result.either(ifLeft: { token in let expiry: URLExpiry = { switch self.slider.integerValue { case 0: return .TenMins case 1: return .OneHour case 2: return .OneDay case 3: return .OneWeek default: fatalError("Unexpected slider value") } }() self.APIClient.submitURL(self.URL, expiry: expiry, token: token) { result in result.either(ifLeft: { URL in dispatch_async(dispatch_get_main_queue()) { self.slider.enabled = false self.resultTextField.stringValue = URL self.resultTextField.hidden = false self.resultTextField.selectText(self) self.shortenedURL = URL } }, ifRight: { error in self.extensionContext!.cancelRequestWithError(error as NSError) }) } }, ifRight: { error in self.extensionContext!.cancelRequestWithError(error as NSError) }) } } else { let outputItem = NSExtensionItem() outputItem.attachments = [shortenedURL] let outputItems = [outputItem] extensionContext!.completeRequestReturningItems(outputItems, completionHandler: nil) } } @IBAction func cancel(sender: AnyObject?) { let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) extensionContext!.cancelRequestWithError(cancelError) } }
b9e054a64cdcc572268d9cbf75d911c1
37.240964
140
0.549779
false
false
false
false
sfurlani/addsumfun
refs/heads/master
Add Sum Fun/Add Sum Fun/NumberView.swift
mit
1
// // NumberCollectionViewCell.swift // Add Sum Fun // // Created by SFurlani on 8/26/15. // Copyright © 2015 Dig-It! Games. All rights reserved. // import UIKit class NumberView: UIView { class func newWithNumber(number: UInt?) -> NumberView? { let nib = UINib(nibName: "NumberView", bundle: nil) let views = nib.instantiateWithOwner(nil, options: nil) guard views.count > 0 else { return nil } guard let numberView = views[0] as? NumberView else { return nil } numberView.number = number return numberView } @IBOutlet var label: UILabel! { didSet { update() } } @IBInspectable var number: UInt? { didSet { update() } } override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 8.0 layer.borderWidth = 1.0 layer.borderColor = UIColor.blackColor().CGColor } private func update() { guard let label = label else { return } if let number = number { backgroundColor = UIColor.whiteColor() label.text = "\(number)" } else { backgroundColor = UIColor(white: 0.9, alpha: 1.0) label.text = nil } setNeedsDisplay() } override func layoutSubviews() { super.layoutSubviews() label.font = label.font.fontWithSize(bounds.height) } }
a28d142a47ccd18e0f4809e567a7e7f8
21.166667
63
0.51817
false
false
false
false
think-dev/MadridBUS
refs/heads/master
MadridBUS/Source/UI/LineNodeDetailPresenter.swift
mit
1
import Foundation protocol LineNodeDetailPresenter { func nodes(on line: String) func config(using view: View) } class LineNodeDetailPresenterBase: Presenter, LineNodeDetailPresenter { private weak var view: LineNodeDetailView! private var busNodesForLine: BusNodesForBusLinesInteractor! required init(injector: Injector) { busNodesForLine = injector.instanceOf(BusNodesForBusLinesInteractor.self) super.init(injector: injector) } func config(using view: View) { guard let lineNodeDetailView = view as? LineNodeDetailView else { fatalError("\(view) is not an LineNodeDetailView") } self.view = lineNodeDetailView super.config(view: view) } func nodes(on line: String) { busNodesForLine.subscribeHandleErrorDelegate(delegate: self) let dto = BusNodesForBusLinesDTO(using: [line]) busNodesForLine.execute(dto) { (busNodes) in var graphicNodes: [LineSchemeNodeModel] = [] var i = 0 for aNode in busNodes { var nodeModel: LineSchemeNodeModel if aNode.type == .nodeForward || aNode.type == .vertexForward { nodeModel = LineSchemeNodeModel(id: aNode.id, name: aNode.name.capitalized, position: i, direction: .forward, latitude: aNode.latitude, longitude: aNode.longitude) } else if aNode.type == .nodeBackwards || aNode.type == .vertexBackwards { nodeModel = LineSchemeNodeModel(id: aNode.id, name: aNode.name.capitalized, position: i, direction: .backwards, latitude: aNode.latitude, longitude: aNode.longitude) } else { nodeModel = LineSchemeNodeModel(id: aNode.id, name: aNode.name.capitalized, position: i, direction: .undefined, latitude: aNode.latitude, longitude: aNode.longitude) } graphicNodes.append(nodeModel) i = i + 1 } self.view.update(withNodes: graphicNodes) } } }
6161904e0a30d235b783dff05cafead6
38.981132
185
0.622935
false
true
false
false
Lordxen/MagistralSwift
refs/heads/master
Carthage/Checkouts/CocoaMQTT/Example/Example/ChatViewController.swift
apache-2.0
3
// // ChatViewController.swift // Example // // Created by CrazyWisdom on 15/12/24. // Copyright © 2015年 emqtt.io. All rights reserved. // import UIKit import CocoaMQTT class ChatViewController: UIViewController { var animal: String? { didSet { animalAvatarImageView.image = UIImage(named: animal!) if let animal = animal { switch animal { case "Sheep": sloganLabel.text = "Four legs good, two legs bad." case "Pig": sloganLabel.text = "All animals are equal." case "Horse": sloganLabel.text = "I will work harder." default: break } } } } var mqtt: CocoaMQTT? var messages: [ChatMessage] = [] { didSet { tableView.reloadData() scrollToBottom() } } @IBOutlet weak var tableView: UITableView! @IBOutlet weak var messageTextView: UITextView! { didSet { messageTextView.layer.cornerRadius = 5 } } @IBOutlet weak var animalAvatarImageView: UIImageView! @IBOutlet weak var sloganLabel: UILabel! @IBOutlet weak var messageTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var inputViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var sendMessageButton: UIButton! { didSet { sendMessageButton.enabled = false } } @IBAction func sendMessage() { let message = messageTextView.text if let client = animal { mqtt!.publish("chat/room/animals/client/" + client, withString: message, qos: .QOS1) } messageTextView.text = "" sendMessageButton.enabled = false messageTextViewHeightConstraint.constant = messageTextView.contentSize.height messageTextView.layoutIfNeeded() view.endEditing(true) } @IBAction func disconnect() { mqtt!.disconnect() navigationController?.popViewControllerAnimated(true) } override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.hidden = true animal = tabBarController?.selectedViewController?.tabBarItem.title automaticallyAdjustsScrollViewInsets = false messageTextView.delegate = self tableView.delegate = self tableView.dataSource = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 50 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChatViewController.receivedMessage(_:)), name: "MQTTMessageNotification" + animal!, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChatViewController.keyboardChanged(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardChanged(notification: NSNotification) { let userInfo = notification.userInfo as! [String: AnyObject] let keyboardValue = userInfo["UIKeyboardFrameEndUserInfoKey"] let bottomDistance = UIScreen.mainScreen().bounds.size.height - (navigationController?.navigationBar.frame.height)! - keyboardValue!.CGRectValue.origin.y if bottomDistance > 0 { inputViewBottomConstraint.constant = bottomDistance } else { inputViewBottomConstraint.constant = 0 } view.layoutIfNeeded() } func receivedMessage(notification: NSNotification) { let userInfo = notification.userInfo as! [String: AnyObject] let content = userInfo["message"] as! String let topic = userInfo["topic"] as! String let sender = topic.stringByReplacingOccurrencesOfString("chat/room/animals/client/", withString: "") let chatMessage = ChatMessage(sender: sender, content: content) messages.append(chatMessage) } func scrollToBottom() { let count = messages.count if count > 3 { let indexPath = NSIndexPath(forRow: count - 1, inSection: 0) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true) } } } extension ChatViewController: UITextViewDelegate { func textViewDidChange(textView: UITextView) { if textView.contentSize.height != textView.frame.size.height { let textViewHeight = textView.contentSize.height if textViewHeight < 100 { messageTextViewHeightConstraint.constant = textViewHeight textView.layoutIfNeeded() } } if textView.text == "" { sendMessageButton.enabled = false } else { sendMessageButton.enabled = true } } } extension ChatViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let message = messages[indexPath.row] if message.sender == animal { let cell = tableView.dequeueReusableCellWithIdentifier("rightMessageCell", forIndexPath: indexPath) as! ChatRightMessageCell cell.contentLabel.text = messages[indexPath.row].content cell.avatarImageView.image = UIImage(named: animal!) return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("leftMessageCell", forIndexPath: indexPath) as! ChatLeftMessageCell cell.contentLabel.text = messages[indexPath.row].content cell.avatarImageView.image = UIImage(named: message.sender) return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { view.endEditing(true) } }
e9fab9d374be2c26f0eed168aa7bb79a
35.047059
181
0.642787
false
false
false
false
ankurp/Cent
refs/heads/master
Sources/Int.swift
mit
1
// // Int.swift // Cent // // Created by Ankur Patel on 6/30/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation import Dollar public extension Int { /// Invoke a callback n times /// /// - parameter callback: The function to invoke that accepts the index public func times(callback: @escaping (Int) -> ()) { (0..<self).forEach(callback) } /// Invoke a callback n times /// /// - parameter function: The function to invoke public func times(function: @escaping () -> ()) { self.times { (index: Int) -> () in function() } } /// Check if it is even /// /// - returns: Bool whether int is even public var isEven: Bool { get { return self % 2 == 0 } } /// Check if it is odd /// /// - returns: Bool whether int is odd public var isOdd: Bool { get { return self % 2 == 1 } } /// Get ASCII character from integer /// /// - returns: Character represented for the given integer public var char: Character { get { return Character(UnicodeScalar(self)!) } } /// Splits the int into array of digits /// /// - returns: Bool whether int is odd public func digits() -> [Int] { var digits: [Int] = [] var selfCopy = self while selfCopy > 0 { _ = digits << (selfCopy % 10) selfCopy = (selfCopy / 10) } return Array(digits.reversed()) } /// Get the next int /// /// - returns: next int public func next() -> Int { return self + 1 } /// Get the previous int /// /// - returns: previous int public func prev() -> Int { return self - 1 } /// Invoke the callback from int up to and including limit /// /// - parameter limit: the max value to iterate upto /// - parameter callback: to invoke public func upTo(limit: Int, callback: @escaping () -> ()) { (self...limit).forEach { _ in callback() } } /// Invoke the callback from int up to and including limit passing the index /// /// - parameter limit: the max value to iterate upto /// - parameter callback: to invoke public func upTo(limit: Int, callback: @escaping (Int) -> ()) { (self...limit).forEach(callback) } /// Invoke the callback from int down to and including limit /// /// - parameter limit: the min value to iterate upto /// - parameter callback: to invoke public func downTo(limit: Int, callback: () -> ()) { var selfCopy = self while selfCopy >= limit { callback() selfCopy -= 1 } } /// Invoke the callback from int down to and including limit passing the index /// /// - parameter limit: the min value to iterate upto /// - parameter callback: to invoke public func downTo(limit: Int, callback: (Int) -> ()) { var selfCopy = self while selfCopy >= limit { callback(selfCopy) selfCopy -= 1 } } /// GCD metod return greatest common denominator with number passed /// /// - parameter number: /// - returns: Greatest common denominator public func gcd(number: Int) -> Int { return Dollar.gcd(self, number) } /// LCM method return least common multiple with number passed /// /// - parameter number: /// - returns: Least common multiple public func lcm(number: Int) -> Int { return Dollar.lcm(self, number) } /// Returns random number from 0 upto but not including value of integer /// /// - returns: Random number public func random() -> Int { return Dollar.random(self) } /// Returns Factorial of integer /// /// - returns: factorial public func factorial() -> Int { return Dollar.factorial(self) } /// Returns true if i is in closed interval /// /// - parameter interval: to check in /// - returns: true if it is in interval otherwise false public func isIn(interval: ClosedRange<Int>) -> Bool { return Dollar.it(self, isIn: Range(interval)) } /// Returns true if i is in half open interval /// /// - parameter interval: to check in /// - returns: true if it is in interval otherwise false public func isIn(interval: Range<Int>) -> Bool { return Dollar.it(self, isIn: interval) } private func mathForUnit(unit: Calendar.Component) -> CalendarMath { return CalendarMath(unit: unit, value: self) } var seconds: CalendarMath { return mathForUnit(unit: .second) } var second: CalendarMath { return seconds } var minutes: CalendarMath { return mathForUnit(unit: .minute) } var minute: CalendarMath { return minutes } var hours: CalendarMath { return mathForUnit(unit: .hour) } var hour: CalendarMath { return hours } var days: CalendarMath { return mathForUnit(unit: .day) } var day: CalendarMath { return days } var weeks: CalendarMath { return mathForUnit(unit: .weekOfYear) } var week: CalendarMath { return weeks } var months: CalendarMath { return mathForUnit(unit: .month) } var month: CalendarMath { return months } var years: CalendarMath { return mathForUnit(unit: .year) } var year: CalendarMath { return years } struct CalendarMath { private let unit: Calendar.Component private let value: Int private var calendar: Calendar { return NSCalendar.autoupdatingCurrent } public init(unit: Calendar.Component, value: Int) { self.unit = unit self.value = value } private func generateComponents(modifer: (Int) -> (Int) = (+)) -> DateComponents { var components = DateComponents() components.setValue(modifer(value), for: unit) return components } public func from(date: Date) -> Date? { return calendar.date(byAdding: generateComponents(), to: date) } public var fromNow: Date? { return from(date: Date()) } public func before(date: Date) -> Date? { return calendar.date(byAdding: generateComponents(modifer: -), to: date) } public var ago: Date? { return before(date: Date()) } } }
6e54292c245d3762add00f5f0e5a4e05
23.921642
90
0.56221
false
false
false
false
jkolb/midnightbacon
refs/heads/master
MidnightBacon/Reddit/RedditRequest.swift
mit
1
// // RedditRequest.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 Common public class RedditRequest { let clientID: String let redirectURI: NSURL let mapperFactory = RedditFactory() let scope: [OAuthScope] = [ .Account, .Edit, .History, .Identity, .MySubreddits, .PrivateMessages, .Read, .Report, .Save, .Submit, .Subscribe, .Vote ] let duration = TokenDuration.Permanent public var tokenPrototype: NSURLRequest! public var oauthPrototype: NSURLRequest! public init(clientID: String, redirectURI: NSURL) { self.clientID = clientID self.redirectURI = redirectURI } public func authorizeURL(state: String) -> NSURL { let request = AuthorizeRequest(clientID: clientID, state: state, redirectURI: redirectURI, duration: duration, scope: scope) return request.buildURL(tokenPrototype.URL!)! } public func userAccessToken(authorizeResponse: OAuthAuthorizeResponse) -> APIRequestOf<OAuthAccessToken> { return APIRequestOf(OAuthAuthorizationCodeRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, authorizeResponse: authorizeResponse, redirectURI: redirectURI)) } public func refreshAccessToken(accessToken: OAuthAccessToken) -> APIRequestOf<OAuthAccessToken> { return APIRequestOf(OAuthRefreshTokenRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, accessToken: accessToken)) } public func applicationAccessToken(deviceID: NSUUID) -> APIRequestOf<OAuthAccessToken> { return APIRequestOf(OAuthInstalledClientRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, deviceID: deviceID)) } public func userAccount() -> APIRequestOf<Account> { return APIRequestOf(MeRequest(mapperFactory: mapperFactory, prototype: oauthPrototype)) } public func subredditLinks(path: String, after: String? = nil) -> APIRequestOf<Listing> { return APIRequestOf(SubredditRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, path: path, after: after)) } public func linkComments(link: Link) -> APIRequestOf<(Listing, [Thing])> { return APIRequestOf(CommentsRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, article: link)) } public func submit(kind kind: SubmitKind, subreddit: String, title: String, url: NSURL?, text: String?, sendReplies: Bool) -> APIRequestOf<Bool> { return APIRequestOf(SubmitRequest(prototype: oauthPrototype, kind: kind, subreddit: subreddit, title: title, url: url, text: text, sendReplies: sendReplies)) } public func privateMessagesWhere(messageWhere: MessageWhere) -> APIRequestOf<Listing> { return APIRequestOf(MessageRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, messageWhere: messageWhere, mark: nil, mid: nil, after: nil, before: nil, count: nil, limit: nil, show: nil, expandSubreddits: nil)) } }
fab1d3a89f837123ed5c64d8b3c45bff
45.065217
232
0.726286
false
false
false
false
bililioo/CBRoundedCorners
refs/heads/master
CBRoundedCornersDemo/CBRoundedCornersDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // CBRoundedCornersDemo // // Created by Bin on 17/1/30. // Copyright © 2017年 cb. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow() window?.frame = UIScreen.main.bounds let vc = ViewController() let nav = UINavigationController.init(rootViewController:vc) window?.rootViewController = nav 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
240e3ff96a5fa37410d965359e1144ef
43.636364
285
0.731161
false
false
false
false
jaydeboer/SwiftR
refs/heads/master
SwiftR/SwiftR.swift
mit
1
// // SwiftR.swift // SwiftR // // Created by Adam Hartford on 4/13/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import Foundation import WebKit public enum ConnectionType { case Hub case Persistent } public enum State { case Connecting case Connected case Disconnected } public enum Transport { case Auto case WebSockets case ForeverFrame case ServerSentEvents case LongPolling var stringValue: String { switch self { case .WebSockets: return "webSockets" case .ForeverFrame: return "foreverFrame" case .ServerSentEvents: return "serverSentEvents" case .LongPolling: return "longPolling" default: return "auto" } } } public final class SwiftR: NSObject { static var connections = [SignalR]() public static var useWKWebView = false public static var transport: Transport = .Auto public class func connect(url: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) -> SignalR? { let signalR = SignalR(baseUrl: url, connectionType: connectionType, readyHandler: readyHandler) connections.append(signalR) return signalR } public class func startAll() { checkConnections() for connection in connections { connection.stop() } } public class func stopAll() { checkConnections() for connection in connections { connection.stop() } } class func checkConnections() { if connections.count == 0 { print("No active SignalR connections. Use SwiftR.connect(...) first.") } } } public class SignalR: NSObject, SwiftRWebDelegate { var webView: SwiftRWebView! var wkWebView: WKWebView! var baseUrl: String var connectionType: ConnectionType var readyHandler: SignalR -> () var hubs = [String: Hub]() public var state: State = .Disconnected public var connectionID: String? public var received: (AnyObject? -> ())? public var starting: (() -> ())? public var connected: (() -> ())? public var disconnected: (() -> ())? public var connectionSlow: (() -> ())? public var connectionFailed: (() -> ())? public var reconnecting: (() -> ())? public var reconnected: (() -> ())? public var error: (AnyObject? -> ())? public var queryString: AnyObject? { didSet { if let qs: AnyObject = queryString { if let jsonData = try? NSJSONSerialization.dataWithJSONObject(qs, options: NSJSONWritingOptions()) { let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String runJavaScript("swiftR.connection.qs = \(json)") } } else { runJavaScript("swiftR.connection.qs = {}") } } } public var headers: [String: String]? { didSet { if let h = headers { if let jsonData = try? NSJSONSerialization.dataWithJSONObject(h, options: NSJSONWritingOptions()) { let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String runJavaScript("swiftR.headers = \(json)") } } else { runJavaScript("swiftR.headers = {}") } } } init(baseUrl: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) { self.baseUrl = baseUrl self.readyHandler = readyHandler self.connectionType = connectionType super.init() #if COCOAPODS let bundle = NSBundle(identifier: "org.cocoapods.SwiftR")! #elseif SWIFTR_FRAMEWORK let bundle = NSBundle(identifier: "com.adamhartford.SwiftR")! #else let bundle = NSBundle.mainBundle() #endif let jqueryURL = bundle.URLForResource("jquery-2.1.3.min", withExtension: "js")! let signalRURL = bundle.URLForResource("jquery.signalR-2.2.0.min", withExtension: "js")! let jsURL = bundle.URLForResource("SwiftR", withExtension: "js")! if SwiftR.useWKWebView { // Loading file:// URLs from NSTemporaryDirectory() works on iOS, not OS X. // Workaround on OS X is to include the script directly. #if os(iOS) let temp = NSURL(fileURLWithPath: NSTemporaryDirectory()) let jqueryTempURL = temp.URLByAppendingPathComponent("jquery-2.1.3.min.js") let signalRTempURL = temp.URLByAppendingPathComponent("jquery.signalR-2.2.0.min") let jsTempURL = temp.URLByAppendingPathComponent("SwiftR.js") let fileManager = NSFileManager.defaultManager() try! fileManager.removeItemAtURL(jqueryTempURL) try! fileManager.removeItemAtURL(signalRTempURL) try! fileManager.removeItemAtURL(jsTempURL) try! fileManager.copyItemAtURL(jqueryURL, toURL: jqueryTempURL) try! fileManager.copyItemAtURL(signalRURL, toURL: signalRTempURL) try! fileManager.copyItemAtURL(jsURL, toURL: jsTempURL) let jqueryInclude = "<script src='\(jqueryTempURL.absoluteString)'></script>" let signalRInclude = "<script src='\(signalRTempURL.absoluteString)'></script>" let jsInclude = "<script src='\(jsTempURL.absoluteString)'></script>" #else let jqueryString = NSString(contentsOfURL: jqueryURL, encoding: NSUTF8StringEncoding, error: nil)! let signalRString = NSString(contentsOfURL: signalRURL, encoding: NSUTF8StringEncoding, error: nil)! let jsString = NSString(contentsOfURL: jsURL, encoding: NSUTF8StringEncoding, error: nil)! let jqueryInclude = "<script>\(jqueryString)</script>" let signalRInclude = "<script>\(signalRString)</script>" let jsInclude = "<script>\(jsString)</script>" #endif let config = WKWebViewConfiguration() config.userContentController.addScriptMessageHandler(self, name: "interOp") #if !os(iOS) //config.preferences.setValue(true, forKey: "developerExtrasEnabled") #endif wkWebView = WKWebView(frame: CGRectZero, configuration: config) wkWebView.navigationDelegate = self let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude))" + "</body></html>" wkWebView.loadHTMLString(html, baseURL: bundle.bundleURL) return } else { let jqueryInclude = "<script src='\(jqueryURL.absoluteString)'></script>" let signalRInclude = "<script src='\(signalRURL.absoluteString)'></script>" let jsInclude = "<script src='\(jsURL.absoluteString)'></script>" let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude))" + "</body></html>" webView = SwiftRWebView() #if os(iOS) webView.delegate = self webView.loadHTMLString(html, baseURL: bundle.bundleURL) #else webView.policyDelegate = self webView.mainFrame.loadHTMLString(html, baseURL: bundle.bundleURL) #endif } } deinit { if let view = wkWebView { view.removeFromSuperview() } } public func createHubProxy(name: String) -> Hub { let hub = Hub(name: name, connection: self) hubs[name.lowercaseString] = hub return hub } public func send(data: AnyObject?) { var json = "null" if let d: AnyObject = data { if d is String { json = "'\(d)'" } else if d is NSNumber { json = "\(d)" } else if let jsonData = try? NSJSONSerialization.dataWithJSONObject(d, options: NSJSONWritingOptions()) { json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String } } runJavaScript("swiftR.connection.send(\(json))") } public func start() { runJavaScript("start()") } public func stop() { runJavaScript("swiftR.connection.stop()") } func shouldHandleRequest(request: NSURLRequest) -> Bool { if request.URL!.absoluteString.hasPrefix("swiftr://") { let id = (request.URL!.absoluteString as NSString).substringFromIndex(9) let msg = webView.stringByEvaluatingJavaScriptFromString("readMessage(\(id))")! let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: []) processMessage(json) return false } return true } func processMessage(json: AnyObject) { if let message = json["message"] as? String { switch message { case "ready": let isHub = connectionType == .Hub ? "true" : "false" runJavaScript("swiftR.transport = '\(SwiftR.transport.stringValue)'") runJavaScript("initialize('\(baseUrl)', \(isHub))") readyHandler(self) runJavaScript("start()") case "starting": state = .Connecting starting?() case "connected": state = .Connected connectionID = json["connectionId"] as? String connected?() case "disconnected": state = .Disconnected disconnected?() case "connectionSlow": connectionSlow?() case "connectionFailed": connectionFailed?() case "reconnecting": state = .Connecting reconnecting?() case "reconnected": state = .Connected reconnected?() case "error": if let err: AnyObject = json["error"] { error?(err["context"]) } else { error?(nil) } default: break } } else if let data: AnyObject = json["data"] { received?(data) } else if let hubName = json["hub"] as? String { let method = json["method"] as! String let arguments: AnyObject? = json["arguments"] let hub = hubs[hubName] hub?.handlers[method]?(arguments) } } func runJavaScript(script: String, callback: (AnyObject! -> ())? = nil) { if SwiftR.useWKWebView { wkWebView.evaluateJavaScript(script, completionHandler: { (result, _) in callback?(result) }) } else { let result = webView.stringByEvaluatingJavaScriptFromString(script) callback?(result) } } // MARK: - WKNavigationDelegate // http://stackoverflow.com/questions/26514090/wkwebview-does-not-run-javascriptxml-http-request-with-out-adding-a-parent-vie#answer-26575892 public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { #if os(iOS) UIApplication.sharedApplication().keyWindow?.addSubview(wkWebView) #endif } // MARK: - WKScriptMessageHandler public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { let id = message.body as! String wkWebView.evaluateJavaScript("readMessage(\(id))", completionHandler: { [weak self] (msg, _) in let data = msg!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: []) self?.processMessage(json) }) } // MARK: - Web delegate methods #if os(iOS) public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { return shouldHandleRequest(request) } #else public override func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { if shouldHandleRequest(request) { listener.use() } } #endif } // MARK: - Hub public class Hub { let name: String var handlers: [String: AnyObject? -> ()] = [:] public let connection: SignalR! init(name: String, connection: SignalR) { self.name = name self.connection = connection } public func on(method: String, parameters: [String]? = nil, callback: AnyObject? -> ()) { handlers[method] = callback var p = "null" if let params = parameters { p = "['" + params.joinWithSeparator("','") + "']" } connection.runJavaScript("addHandler('\(name)', '\(method)', \(p))") } public func invoke(method: String, arguments: [AnyObject]?) { var jsonArguments = [String]() if let args = arguments { for arg in args { if arg is String { jsonArguments.append("'\(arg)'") } else if arg is NSNumber { jsonArguments.append("\(arg)") } else if let data = try? NSJSONSerialization.dataWithJSONObject(arg, options: NSJSONWritingOptions()) { jsonArguments.append(NSString(data: data, encoding: NSUTF8StringEncoding) as! String) } } } let args = jsonArguments.joinWithSeparator(",") let js = "swiftR.hubs.\(name).invoke('\(method)', \(args))" connection.runJavaScript(js) } } #if os(iOS) typealias SwiftRWebView = UIWebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate {} #else typealias SwiftRWebView = WebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler {} #endif
7e2c2e43d7dfde7254a12f6066568017
35.101695
145
0.571764
false
false
false
false
PodRepo/firefox-ios
refs/heads/master
Client/Application/WebServer.swift
mpl-2.0
7
/* 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 private let WebServerSharedInstance = WebServer() class WebServer { class var sharedInstance: WebServer { return WebServerSharedInstance } let server: GCDWebServer = GCDWebServer() var base: String { return "http://localhost:\(server.port)" } func start() -> Bool { if !server.running { try! server.startWithOptions([GCDWebServerOption_Port: 0, GCDWebServerOption_BindToLocalhost: true, GCDWebServerOption_AutomaticallySuspendInBackground: false]) } return server.running } /// Convenience method to register a dynamic handler. Will be mounted at $base/$module/$resource func registerHandlerForMethod(method: String, module: String, resource: String, handler: (request: GCDWebServerRequest!) -> GCDWebServerResponse!) { server.addHandlerForMethod(method, path: "/\(module)/\(resource)", requestClass: GCDWebServerRequest.self, processBlock: handler) } /// Convenience method to register a resource in the main bundle. Will be mounted at $base/$module/$resource func registerMainBundleResource(resource: String, module: String) { if let path = NSBundle.mainBundle().pathForResource(resource, ofType: nil) { server.addGETHandlerForPath("/\(module)/\(resource)", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } /// Convenience method to register all resources in the main bundle of a specific type. Will be mounted at $base/$module/$resource func registerMainBundleResourcesOfType(type: String, module: String) { for path: NSString in NSBundle.pathsForResourcesOfType(type, inDirectory: NSBundle.mainBundle().bundlePath) { let resource = path.lastPathComponent server.addGETHandlerForPath("/\(module)/\(resource)", filePath: path as String, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } /// Return a full url, as a string, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(resource: String, module: String) -> String { return "\(base)/\(module)/\(resource)" } /// Return a full url, as an NSURL, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(resource: String, module: String) -> NSURL { return NSURL(string: "\(base)/\(module)/\(resource)")! } func updateLocalURL(url: NSURL) -> NSURL? { let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) if components?.host == "localhost" && components?.scheme == "http" { components?.port = WebServer.sharedInstance.server.port } return components?.URL } }
1793688dfad6d039a9a7c435887ae67f
46.171875
172
0.690855
false
false
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuide/Common/CGSSNotification.swift
mit
1
// // CGSSNotification.swift // DereGuide // // Created by zzk on 2017/5/1. // Copyright © 2017年 zzk. All rights reserved. // import UIKit extension Notification.Name { static let updateEnd = Notification.Name.init("CGSS_UPDATE_END") static let gameResoureceProcessedEnd = Notification.Name.init("CGSS_PROCESS_END") static let saveEnd = Notification.Name.init("CGSS_SAVE_END") static let favoriteCardsChanged = Notification.Name.init("CGSS_FAVORITE_CARD_CHANGED") static let favoriteCharasChanged = Notification.Name.init("CGSS_FAVORITE_CHARA_CHANGED") static let favoriteSongsChanged = Notification.Name(rawValue: "CGSS_FAVORITE_SONG_CHANGED") static let dataRemoved = Notification.Name.init("CGSS_DATA_REMOVED") static let unitModified = Notification.Name.init("CGSS_UNIT_MODIFIED") }
020224a676ab4500be760e7ebf4fdb6b
40.25
95
0.751515
false
false
false
false
lokinfey/MyPerfectframework
refs/heads/master
Examples/Tap Tracker/Tap Tracker/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // Tap Tracker // // Created by Kyle Jessup on 2015-10-22. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // 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. 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:. } }
0b590be74f3d2b527bdb99fe94781ce2
41.586207
279
0.729555
false
false
false
false
Cleverlance/Pyramid
refs/heads/master
Sources/Common/Testing/RepositoryTestDoubles.swift
mit
1
// // Copyright © 2016 Cleverlance. All rights reserved. // class RepositoryDummy<Model>: Repository<Model> { override func deleteAll() throws {} override func load() throws -> Model? { return nil } override func save(_ model: Model) throws {} } public class RepositorySpy<Model>: Repository<Model> { public enum Operation { case load, deleteAll, save } public var savedModels = [Model]() public var loadCalled = 0 public var deleteAllCalled = 0 public var operations = [Operation]() override public func deleteAll() throws { deleteAllCalled += 1 operations.append(.deleteAll) } override public func load() throws -> Model? { loadCalled += 1 operations.append(.load) return nil } override public func save(_ model: Model) throws { savedModels.append(model) } } class RepositoryThrowing<Model>: Repository<Model> { fileprivate let error: Error init(_ error: Error = TestError()) { self.error = error } override func deleteAll() throws { throw error } override func load() throws -> Model? { throw error } override func save(_ model: Model) throws { throw error } } class RepositoryReturning<Model>: Repository<Model> { fileprivate let model: Model? init(_ model: Model?) { self.model = model } override func deleteAll() throws {} override func load() throws -> Model? { return model } override func save(_ model: Model) throws {} } public class RepositoryFake<Model>: Repository<Model> { public var model: Model? override public func deleteAll() throws { model = nil } override public func load() throws -> Model? { return model } override public func save(_ model: Model) throws { self.model = model } } extension Repository { public static func dummy() -> Repository<Model> { return RepositoryDummy() } public static func spy() -> RepositorySpy<Model> { return RepositorySpy() } public static func throwing(_ error: Error = TestError()) -> Repository<Model> { return RepositoryThrowing(error) } public static func returning(_ model: Model?) -> Repository<Model> { return RepositoryReturning(model) } public static func fake() -> RepositoryFake<Model> { return RepositoryFake() } }
03caf81d439eeafbbbf09a8ef55d8413
24.052083
84
0.639085
false
false
false
false
exsortis/TenCenturiesKit
refs/heads/master
Sources/TenCenturiesKit/Models/DeleteResponse.swift
mit
1
import Foundation public struct DeleteResponse { public let id : Int public let isVisible : Bool public let isDeleted : Bool } extension DeleteResponse : Serializable { public init?(from json : JSONDictionary) { guard let id = json["id"] as? Int, let isVisible = json["is_visible"] as? Bool, let isDeleted = json["is_deleted"] as? Bool else { return nil } self.id = id self.isVisible = isVisible self.isDeleted = isDeleted } public func toDictionary() -> JSONDictionary { let dict : JSONDictionary = [ "id" : id, "is_visible" : isVisible, "is_deleted" : isDeleted, ] return dict } }
1f47f603bc77720c6549b8d437147a75
20.942857
56
0.549479
false
false
false
false
KrishMunot/swift
refs/heads/master
benchmark/utils/ArgParse.swift
apache-2.0
6
//===--- ArgParse.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation public struct Arguments { public var progName: String public var positionalArgs: [String] public var optionalArgsMap: [String : String] init(_ pName: String, _ posArgs: [String], _ optArgsMap: [String : String]) { progName = pName positionalArgs = posArgs optionalArgsMap = optArgsMap } } /// Using Process.arguments, returns an Arguments struct describing /// the arguments to this program. If we fail to parse arguments, we /// return nil. /// /// We assume that optional switch args are of the form: /// /// --opt-name[=opt-value] /// -opt-name[=opt-value] /// /// with opt-name and opt-value not containing any '=' signs. Any /// other option passed in is assumed to be a positional argument. public func parseArgs(_ validOptions: [String]? = nil) -> Arguments? { let progName = Process.arguments[0] var positionalArgs = [String]() var optionalArgsMap = [String : String]() // For each argument we are passed... var passThroughArgs = false for arg in Process.arguments[1..<Process.arguments.count] { // If the argument doesn't match the optional argument pattern. Add // it to the positional argument list and continue... if passThroughArgs || !arg.characters.starts(with: "-".characters) { positionalArgs.append(arg) continue } if arg == "--" { passThroughArgs = true continue } // Attempt to split it into two components separated by an equals sign. let components = arg.components(separatedBy: "=") let optionName = components[0] if validOptions != nil && !validOptions!.contains(optionName) { print("Invalid option: \(arg)") return nil } var optionVal : String switch components.count { case 1: optionVal = "" case 2: optionVal = components[1] default: // If we do not have two components at this point, we can not have // an option switch. This is an invalid argument. Bail! print("Invalid option: \(arg)") return nil } optionalArgsMap[optionName] = optionVal } return Arguments(progName, positionalArgs, optionalArgsMap) }
b3536fc56067c1576cf16611c5e3bcf1
33
80
0.645173
false
false
false
false
mirai418/leaflet-ios
refs/heads/master
leaflet/PointsOfInterestListViewController.swift
mit
1
// // PointsOfInterestListViewController.swift // leaflet // // Created by Cindy Zeng on 4/8/15. // Copyright (c) 2015 parks-and-rec. All rights reserved. // import UIKit class PointsOfInterestListViewController: UITableViewController, ENSideMenuDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! private var allPois = [FecPoi]() var selectedPoi: FecPoi! override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("pointOfInterest") as? PointsOfInterestListViewCell ?? PointsOfInterestListViewCell() var pointOfInterest = self.allPois[indexPath.row] cell.poiName.text = pointOfInterest.title cell.locationAway.text = pointOfInterest.getHumanDistance() cell.poiImage.image = pointOfInterest.image return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.allPois.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedPoi = allPois[indexPath.row] self.performSegueWithIdentifier("toContentFromList", sender: self) } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationController?.navigationBar.barTintColor = UIColor(hex: GlobalConstants.defaultNavColor) self.tableView.rowHeight = 60.0 allPois = LibraryAPI.sharedInstance.getPois() self.navigationController?.navigationBar.barTintColor = UIColor(hex: GlobalConstants.defaultNavColor) self.navigationController?.navigationBar.translucent = false self.navigationController?.navigationBar.clipsToBounds = false self.sideMenuController()?.sideMenu?.delegate = self hideSideMenuView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func revealCompassView(sender: AnyObject) { let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil) var destViewController : UIViewController destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("compassView") as! UIViewController sideMenuController()?.setContentViewController(destViewController) } @IBAction func toggleSideMenu(sender: AnyObject) { toggleSideMenuView() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segue.identifier! { case "toContentFromList": if var poiVC = segue.destinationViewController as? DetailedViewController { poiVC.selectedPoi = self.selectedPoi } default: break } } }
0d52b3892f22385b90133ad0eb9b1c60
35.755814
148
0.686808
false
false
false
false
maghov/IS-213
refs/heads/master
LoginV1/LoginV1/SecondViewController.swift
mit
1
// // SecondViewController.swift // RoomBooking3 // // Created by Gruppe10 on 18.04.2017. // Copyright © 2017 Gruppe10. All rights reserved. // import UIKit import Firebase var roomList = [RoomModel]() var refRooms: FIRDatabaseReference! var myIndex = Int() class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var viewDropDownMenu: UIView! @IBOutlet weak var textFieldSpace: UITextField! @IBOutlet weak var textFieldName: UITextField! @IBOutlet weak var textFieldDetails: UITextField! @IBOutlet weak var tblRooms: UITableView! //Code for dropdown menu @IBAction func showDropDownMenu(_ sender: UIBarButtonItem) { if (viewDropDownMenu.isHidden == true){ viewDropDownMenu.isHidden = false } else if (viewDropDownMenu.isHidden == false){ viewDropDownMenu.isHidden = true } } //Logs out the user @IBAction func logoutButtonPressed(_ sender: UIButton) { try! FIRAuth.auth()?.signOut() performSegue(withIdentifier: "SegueChooseRoomToLogin", sender: self) } //This button runs the function addRoom() @IBAction func buttonAddRoom(_ sender: UIButton) { addRoom() } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { myIndex = indexPath.row print("IndexPath ", indexPath.row) performSegue(withIdentifier: "segue", sender: self) } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return roomList.count } //Creates rows for every room in the database. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as!ViewControllerTableViewCell let room: RoomModel room = roomList[indexPath.row] cell.lblName.text = room.name cell.lblSpace.text = "Antall plasser " + room.space! cell.lblDetails.text = room.details return cell } //Function to add a room func addRoom() { let key = textFieldName.text! as String let room = ["id": key, "name": textFieldName.text! as String, "space": textFieldSpace.text! as String, "details": textFieldDetails.text! as String ] refRooms.child(key).setValue(room) } override func viewDidLoad() { super.viewDidLoad() viewDropDownMenu.isHidden = true refRooms = FIRDatabase.database().reference().child("list") refRooms.observe(FIRDataEventType.value, with:{(snapshot) in if snapshot.childrenCount > 0 { roomList.removeAll() for rooms in snapshot.children.allObjects as! [FIRDataSnapshot] { let roomObject = rooms.value as? [String: AnyObject] let name = roomObject?["name"] let space = roomObject?["space"] let id = roomObject?["id"] let details = roomObject? ["details"] let tiElleve = roomObject? ["tiElleve"] let elleveTolv = roomObject? ["elleveTolv"] let tolvEtt = roomObject? ["tolvEtt"] let ettTo = roomObject? ["ettTo"] let toTre = roomObject? ["toTre"] let treFire = roomObject? ["treFire"] let booketAvTiElleve = roomObject? ["booketAvTiElleve"] let booketAvElleveTolv = roomObject? ["booketAvElleveTolv"] let booketAvTolvEtt = roomObject? ["booketAvTolvEtt"] let booketAvEttTo = roomObject? ["booketAvEttTo"] let booketAvToTre = roomObject? ["booketAvToTre"] let booketAvTreFire = roomObject? ["booketAvTreFire"] let room = RoomModel(id: id as! String?, name: name as! String?, space: space as! String?, details: details as! String?, tiElleve: tiElleve as! String?, elleveTolv: elleveTolv as! String?, tolvEtt: tolvEtt as! String?, ettTo: ettTo as! String?, toTre: toTre as! String?, treFire: treFire as! String?, booketAvTiElleve: booketAvTiElleve as! String?, booketAvElleveTolv: booketAvElleveTolv as! String?, booketAvTolvEtt: booketAvTolvEtt as! String?, booketAvEttTo: booketAvEttTo as! String?, booketAvToTre: booketAvToTre as! String?, booketAvTreFire: booketAvTreFire as! String?) roomList.append(room) } } self.tblRooms.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Hides keyboard when user touches outside textfield override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
7f25bbe30e9ccbc1025e3bd026618fd6
35.323171
119
0.533994
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Issues/Review/IssueReviewDetailsCell.swift
mit
1
// // IssueReviewDetailsCell.swift // Freetime // // Created by Ryan Nystrom on 7/5/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit import IGListKit protocol IssueReviewDetailsCellDelegate: class { func didTapActor(cell: IssueReviewDetailsCell) } final class IssueReviewDetailsCell: UICollectionViewCell, ListBindable { weak var delegate: IssueReviewDetailsCellDelegate? let icon = UIImageView() let actorButton = UIButton() let dateLabel = ShowMoreDetailsLabel() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white let iconSize = Styles.Sizes.icon icon.clipsToBounds = true icon.layer.cornerRadius = iconSize.width/2 icon.contentMode = .center contentView.addSubview(icon) icon.snp.makeConstraints { make in make.size.equalTo(iconSize) make.centerY.equalTo(contentView) make.left.equalTo(Styles.Sizes.gutter) } actorButton.addTarget(self, action: #selector(IssueReviewDetailsCell.onActorTapped), for: .touchUpInside) contentView.addSubview(actorButton) actorButton.snp.makeConstraints { make in make.centerY.equalTo(icon) make.left.equalTo(icon.snp.right).offset(Styles.Sizes.columnSpacing) } contentView.addSubview(dateLabel) dateLabel.font = Styles.Fonts.secondary dateLabel.textColor = Styles.Colors.Gray.medium.color dateLabel.snp.makeConstraints { make in make.centerY.equalTo(actorButton) make.left.equalTo(actorButton.snp.right).offset(Styles.Sizes.columnSpacing/2) } contentView.addBorder(.top) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentViewForSafeAreaInsets() } // MARK: Private API @objc func onActorTapped() { delegate?.didTapActor(cell: self) } // MARK: ListBindable func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? IssueReviewDetailsModel else { return } dateLabel.setText(date: viewModel.date) let action: String let iconBackgroundColor: UIColor let iconTintColor: UIColor let iconName: String switch viewModel.state { case .commented: action = NSLocalizedString("commented", comment: "") iconBackgroundColor = Styles.Colors.Gray.lighter.color iconTintColor = Styles.Colors.Gray.medium.color iconName = "eye-small" case .changesRequested: action = NSLocalizedString("requested changes", comment: "") iconBackgroundColor = Styles.Colors.Red.medium.color iconTintColor = .white iconName = "x-small" case .approved: action = NSLocalizedString("approved", comment: "") iconBackgroundColor = Styles.Colors.Green.medium.color iconTintColor = .white iconName = "check-small" case .pending: action = NSLocalizedString("pending review", comment: "") iconBackgroundColor = Styles.Colors.Yellow.light.color iconTintColor = Styles.Colors.Gray.medium.color iconName = "eye-small" case .dismissed: action = NSLocalizedString("dismissed a review", comment: "") iconBackgroundColor = Styles.Colors.Gray.light.color iconTintColor = Styles.Colors.Gray.medium.color iconName = "x-small" } icon.backgroundColor = iconBackgroundColor icon.tintColor = iconTintColor icon.image = UIImage(named: iconName)?.withRenderingMode(.alwaysTemplate) var attributes = [ NSAttributedStringKey.font: Styles.Fonts.title, NSAttributedStringKey.foregroundColor: Styles.Colors.Gray.medium.color ] let mActorString = NSMutableAttributedString(string: viewModel.actor, attributes: attributes) attributes[NSAttributedStringKey.font] = Styles.Fonts.secondary mActorString.append(NSAttributedString(string: " \(action)", attributes: attributes)) actorButton.setAttributedTitle(mActorString, for: .normal) } }
5ac23eb99697d669e81acb7b7d704e3b
33.414063
113
0.657662
false
false
false
false
TIEmerald/UNDanielBasicTool_Swift
refs/heads/master
UNDanielBasicTool_Swift/Classes/Useful Views/Drop Down List/UNDDropDownListTableViewController.swift
mit
1
// // UNDDropDownListTableViewController.swift // Pods // // Created by 尓健 倪 on 17/6/17. // // import UIKit public protocol UNDDropDownListDelegate : NSObjectProtocol { func dropdownList(_ dropdownList: UNDDropDownListTableViewController, didSelectCellAtIndexPath indexPath: IndexPath) -> Void func dropdownList(_ dropdownList: UNDDropDownListTableViewController, dataAtIndexPath indexPath: IndexPath) -> Any func numberOfCellsInDropdownList(_ dropdownList: UNDDropDownListTableViewController) -> Int } open class UNDDropDownListTableViewController: UITableViewController { /// Mark : - Interfaces public weak var delegate : UNDDropDownListDelegate? public var identifierTag : Int? public var isMultipleSelectable : Bool { get{ return self.tableView.allowsMultipleSelection } set(newValue){ self.tableView.allowsMultipleSelection = newValue } } /// Set this property tell us how many cells you what to show up in the Drop Down List each time public var numberOfDisplayingCells : Int{ get{ return _numberOfDisplayingCells } set(newValue){ _ = self.resignFirstResponder() _numberOfDisplayingCells = newValue } } /// Normally, you should let us know that is the Width of the Dropdown List public var width : CGFloat{ get{ return _width } set(newValue){ _ = self.resignFirstResponder() _width = newValue } } /// And you'd better tell us what is the origin Point of the Dropdown List public var originPoint : CGPoint{ get{ return _originPoint } set(newValue){ _ = self.resignFirstResponder() _originPoint = newValue } } /// You need o set this property to let us know should we hide the default seperator for the table view cells or not.... Ifyou want use your custom Seperator, you'd better set this property to YES public var shouldHideSeperator : Bool { get{ return hideSeperator } set(newValue){ hideSeperator = newValue self.setTableViewSeperator() } } /// You need to update this property if you want your Drop down list be transparent public var dropdownListAlpha : CGFloat = 1 /// You need to update this property if you want your Drop down list show up or hide quicker public var dropdownListShowUpAndHideDuration : TimeInterval = 0.5 /// MARK : Read Only Property open var dropdownListHeight : CGFloat{ return self.usingCellHeight * CGFloat.init(min(self.numberOfDisplayingCells, getSupportTotalCellRows())) } open var dropdownListOriginPoint : CGPoint { return _originPoint } open var dropdownListWidth : CGFloat{ return _width } private var usingFrame : CGRect{ return CGRect(origin: dropdownListOriginPoint, size: CGSize(width: dropdownListWidth, height: dropdownListHeight)) } /// MARK : Private Properties private var hideSeperator : Bool = false private var usingCellHeight : CGFloat = 44.0 private var usingCellIdentifier : String? private var _numberOfDisplayingCells : Int = 5 private var _width : CGFloat = 0 private var _originPoint : CGPoint = CGPoint(x: 0, y: 0) /// MARK : - Public Methods public func setupWithTarget(_ target : UNDDropDownListDelegate, showUpView view: UIView, andCell cell : UNDBaseTableViewCell){ self.registerCell(cell) view.addSubview(self.view) self.view.alpha = 0 self.delegate = target } public func registerCell(_ cell: UNDBaseTableViewCell){ type(of: cell).registerSelf(intoTableView:self.tableView) self.usingCellHeight = type(of: cell).cellHeight self.usingCellIdentifier = type(of: cell).cellIdentifierName } public func showUp(){ self.view.frame = usingFrame self.view.superview?.bringSubview(toFront: self.view) UNDanielUtilsTool.log("_____ Trying to show Dropdown List:\(self) in superView :\(String(describing: self.view.superview)) in Frame :\(usingFrame)") UIView.animate(withDuration: self.dropdownListShowUpAndHideDuration) { self.view.alpha = self.dropdownListAlpha } } public func reloadData(){ self.tableView.reloadData() } public func hideDropdownList(){ if self.view.alpha > 0.0 { UIView.animate(withDuration: self.dropdownListShowUpAndHideDuration, animations: { self.view.alpha = 0.0 }) } } public func setUpDispalyingPositionWithView(_ view: UIView, andExtendWidth extendWidth: CGFloat ){ if let convertedRect = view.superview?.convert(view.frame, to: self.view.superview){ _originPoint = CGPoint(x: convertedRect.origin.x, y: convertedRect.origin.y + convertedRect.size.height) _width = convertedRect.size.width + extendWidth } else { _originPoint = CGPoint(x: 0, y: 0) _width = 0.0 + extendWidth } } open override func resignFirstResponder() -> Bool { self.hideDropdownList() return super.resignFirstResponder() } /// MARK : - Privete Methods /// MARK : - UI View Controller override open func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.view.backgroundColor = UIColor.clear self.tableView.backgroundView = UIView() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) self.tableView.bounces = false self.tableView.alwaysBounceVertical = false self.tableView.alwaysBounceHorizontal = false self.setTableViewSeperator() } // MARK: - Table view data source override open func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return getSupportTotalCellRows() } override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.usingCellHeight } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UNDBaseTableViewCell = UNDDDLSampleTableViewCell() if let unwrapedCellIdentifier = self.usingCellIdentifier { cell = tableView.dequeueReusableCell(withIdentifier: unwrapedCellIdentifier, for: indexPath) as! UNDBaseTableViewCell } if let unwrapDelegate = self.delegate { var model : Any? if unwrapDelegate.responds(to: Selector(("dropdownList:dataAtIndexPath:"))) { model = unwrapDelegate.dropdownList(self, dataAtIndexPath: indexPath) } if let unwrapedModel = model { cell.setupCell(basedOnModelDictionary: [UNDBaseTableViewCell.UITableViewCell_BaseModle_Key : unwrapedModel]) } } return cell } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let unwrapDelegate = self.delegate { if unwrapDelegate.responds(to: Selector(("dropdownList:didSelectCellAtIndexPath:"))) { unwrapDelegate.dropdownList(self, didSelectCellAtIndexPath: indexPath) } } } /// MARK: - Support Methods func setTableViewSeperator() -> Void { if !hideSeperator { self.tableView.separatorStyle = .singleLine } else { self.tableView.separatorStyle = .none } } func getSupportTotalCellRows() -> Int { var returnInt : Int = 0 if let unwrapDelegate = self.delegate { if unwrapDelegate.responds(to: Selector(("numberOfCellsInDropdownList:"))) { returnInt = unwrapDelegate.numberOfCellsInDropdownList(self) } } return returnInt } }
cfb64eb6477897be72ed71c1117f4e87
34.992278
200
0.618108
false
false
false
false
Antondomashnev/ADChromePullToRefresh
refs/heads/master
Source/ADChromePullToRefreshRIghtActionView.swift
mit
1
// // ADChromePullToRefreshRightActionView.swift // ADChromePullToRefresh // // Created by Anton Domashnev on 4/26/15. // Copyright (c) 2015 Anton Domashnev. All rights reserved. // import UIKit public class ADChromePullToRefreshRightActionView: ADChromePullToRefreshActionView { fileprivate let zeroAlphaScrollProgress: CGFloat = 0.6 fileprivate let oneAlphaScrollProgress: CGFloat = 0.9 fileprivate let initialTranslateX: CGFloat = -40.0 //MARK: - Interface override func updateWithScrollProgress(_ scrollProgress: CGFloat) { let newAlpha = min(1, (scrollProgress - zeroAlphaScrollProgress) / (oneAlphaScrollProgress - zeroAlphaScrollProgress)) self.alpha = newAlpha let newTranslateX = initialTranslateX - (initialTranslateX * scrollProgress) self.iconView.transform = CGAffineTransform.identity.translatedBy(x: newTranslateX, y: 0) } class func rightActionView() -> ADChromePullToRefreshRightActionView { let view = ADChromePullToRefreshRightActionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) view.iconMaskView.image = UIImage(named: "ic_close_black") view.iconView.transform = CGAffineTransform.identity.translatedBy(x: view.initialTranslateX, y: 0) return view } }
cd779b4409003c337f5d75efc4579eb2
38.69697
126
0.723664
false
false
false
false
AlexRamey/mbird-iOS
refs/heads/develop
CHFoundation/Pods/PromiseKit/Sources/join.swift
apache-2.0
43
import Dispatch /** Waits on all provided promises. `when` rejects as soon as one of the provided promises rejects. `join` waits on all provided promises, then rejects if any of those promises rejected, otherwise it fulfills with values from the provided promises. join(promise1, promise2, promise3).then { results in //… }.catch { error in switch error { case Error.Join(let promises): //… } } - Returns: A new promise that resolves once all the provided promises resolve. - SeeAlso: `PromiseKit.Error.join` */ @available(*, deprecated: 4.0, message: "Use when(resolved:)") public func join<T>(_ promises: Promise<T>...) -> Promise<[T]> { return join(promises) } /// Waits on all provided promises. @available(*, deprecated: 4.0, message: "Use when(resolved:)") public func join(_ promises: [Promise<Void>]) -> Promise<Void> { return join(promises).then(on: zalgo) { (_: [Void]) in return Promise(value: ()) } } /// Waits on all provided promises. @available(*, deprecated: 4.0, message: "Use when(resolved:)") public func join<T>(_ promises: [Promise<T>]) -> Promise<[T]> { guard !promises.isEmpty else { return Promise(value: []) } var countdown = promises.count let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) var rejected = false return Promise { fulfill, reject in for promise in promises { promise.state.pipe { resolution in barrier.sync(flags: .barrier) { if case .rejected(_, let token) = resolution { token.consumed = true // the parent Error.Join consumes all rejected = true } countdown -= 1 if countdown == 0 { if rejected { reject(PMKError.join(promises)) } else { fulfill(promises.map{ $0.value! }) } } } } } } }
8cd8f905e6eeca8384d0d7ce68e1e0fb
34.5
213
0.559624
false
false
false
false
Ramotion/elongation-preview
refs/heads/master
ElongationPreview/Source/ElongationTransition.swift
mit
2
// // ElongationTransition.swift // ElongationPreview // // Created by Abdurahim Jauzee on 11/02/2017. // Copyright © 2017 Ramotion. All rights reserved. // import UIKit /// Provides transition animations between `ElongationViewController` & `ElongationDetailViewController`. public class ElongationTransition: NSObject { // MARK: Constructor internal convenience init(presenting: Bool) { self.init() self.presenting = presenting } // MARK: Properties fileprivate var presenting = true fileprivate var appearance: ElongationConfig { return ElongationConfig.shared } fileprivate let additionalOffsetY: CGFloat = 30 fileprivate var rootKey: UITransitionContextViewControllerKey { return presenting ? .from : .to } fileprivate var detailKey: UITransitionContextViewControllerKey { return presenting ? .to : .from } fileprivate var rootViewKey: UITransitionContextViewKey { return presenting ? .from : .to } fileprivate var detailViewKey: UITransitionContextViewKey { return presenting ? .to : .from } fileprivate func root(from context: UIViewControllerContextTransitioning) -> ElongationViewController { let viewController = context.viewController(forKey: rootKey) if let navi = viewController as? UINavigationController { for case let elongationViewController as ElongationViewController in navi.viewControllers { return elongationViewController } } else if let tab = viewController as? UITabBarController, let elongationViewController = tab.selectedViewController as? ElongationViewController { return elongationViewController } else if let elongationViewController = viewController as? ElongationViewController { return elongationViewController } fatalError("Can't get `ElongationViewController` from UINavigationController nor from context's viewController itself.") } fileprivate func detail(from context: UIViewControllerContextTransitioning) -> ElongationDetailViewController { return context.viewController(forKey: detailKey) as? ElongationDetailViewController ?? ElongationDetailViewController(nibName: nil, bundle: nil) } } // MARK: - Transition Protocol Implementation extension ElongationTransition: UIViewControllerAnimatedTransitioning { /// :nodoc: open func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval { return presenting ? appearance.detailPresentingDuration : appearance.detailDismissingDuration } /// :nodoc: open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { presenting ? present(using: transitionContext) : dismiss(using: transitionContext) } } // MARK: - Presenting Animation extension ElongationTransition { fileprivate func present(using context: UIViewControllerContextTransitioning) { let duration = transitionDuration(using: context) let containerView = context.containerView let root = self.root(from: context) // ElongationViewController let detail = self.detail(from: context) // ElongationDetailViewController let rootView = context.view(forKey: rootViewKey) let detailView = context.view(forKey: detailViewKey) let detailViewFinalFrame = context.finalFrame(for: detail) // Final frame for presenting view controller let statusBarHeight: CGFloat if #available(iOS 11, *) { statusBarHeight = UIApplication.shared.statusBarFrame.height } else { statusBarHeight = 0 } guard let rootTableView = root.tableView, // get `tableView` from root let path = root.expandedIndexPath ?? rootTableView.indexPathForSelectedRow, // get expanded or selected indexPath let cell = rootTableView.cellForRow(at: path) as? ElongationCell, // get expanded cell from root `tableView` let view = detailView // unwrap optional `detailView` else { return } // Determine are `root` view is in expanded state. // We need to know that because animation depends on the state. let isExpanded = root.state == .expanded // Create `ElongationHeader` from `ElongationCell` and set it as `headerView` to `detail` view controller let header = cell.elongationHeader detail.headerView = header // Get frame of expanded cell and convert it to `containerView` coordinates let rect = rootTableView.rectForRow(at: path) let cellFrame = rootTableView.convert(rect, to: containerView) // Whole view snapshot UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) let fullImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() // Header snapshot UIGraphicsBeginImageContextWithOptions(header.frame.size, true, 0) fullImage.draw(at: CGPoint(x: 0, y: 0)) let headerSnapsot = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() // TableView snapshot let cellsSize = CGSize(width: view.frame.width, height: view.frame.height - header.frame.height) UIGraphicsBeginImageContextWithOptions(cellsSize, true, 0) fullImage.draw(at: CGPoint(x: 0, y: -header.frame.height - statusBarHeight)) let tableSnapshot = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() let headerSnapshotView = UIImageView(image: headerSnapsot) let tableViewSnapshotView = UIImageView(image: tableSnapshot) let tempView = UIView() tempView.backgroundColor = header.bottomView.backgroundColor // Add coming `view` to temporary `containerView` containerView.addSubview(view) containerView.addSubview(tempView) containerView.addSubview(tableViewSnapshotView) // Update `bottomView`s top constraint and invalidate layout header.bottomViewTopConstraint.constant = appearance.topViewHeight header.bottomView.setNeedsLayout() let height = isExpanded ? cellFrame.height : appearance.topViewHeight + appearance.bottomViewHeight view.frame = CGRect(x: 0, y: cellFrame.minY - statusBarHeight, width: detailViewFinalFrame.width, height: cellFrame.height) headerSnapshotView.frame = CGRect(x: 0, y: cellFrame.minY - statusBarHeight, width: cellFrame.width, height: height) tableViewSnapshotView.frame = CGRect(x: 0, y: detailViewFinalFrame.maxY, width: cellsSize.width, height: cellsSize.height) tempView.frame = CGRect(x: 0, y: cellFrame.maxY - statusBarHeight, width: detailViewFinalFrame.width, height: 0) // Animate to new state UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: { root.view?.alpha = 0 header.scalableView.transform = .identity // reset scale to 1.0 header.contentView.frame = CGRect(x: 0, y: 0, width: cellFrame.width, height: cellFrame.height + self.appearance.bottomViewOffset) header.contentView.setNeedsLayout() header.contentView.layoutIfNeeded() view.frame = detailViewFinalFrame headerSnapshotView.frame = CGRect(x: 0, y: 0, width: cellFrame.width, height: height) tableViewSnapshotView.frame = CGRect(x: 0, y: header.frame.height + statusBarHeight, width: detailViewFinalFrame.width, height: cellsSize.height) tempView.frame = CGRect(x: 0, y: headerSnapshotView.frame.maxY, width: detailViewFinalFrame.width, height: detailViewFinalFrame.height) }) { completed in rootView?.removeFromSuperview() tempView.removeFromSuperview() headerSnapshotView.removeFromSuperview() tableViewSnapshotView.removeFromSuperview() context.completeTransition(completed) } } } // MARK: - Dismiss Animation extension ElongationTransition { fileprivate func dismiss(using context: UIViewControllerContextTransitioning) { let root = self.root(from: context) let detail = self.detail(from: context) let containerView = context.containerView let duration = transitionDuration(using: context) guard let header = detail.headerView, let view = context.view(forKey: detailViewKey), // actual view of `detail` view controller let rootTableView = root.tableView, // `tableView` of root view controller let detailTableView = detail.tableView, // `tableView` of detail view controller let path = root.expandedIndexPath ?? rootTableView.indexPathForSelectedRow, // `indexPath` of expanded or selected cell let expandedCell = rootTableView.cellForRow(at: path) as? ElongationCell else { return } // Collapse root view controller without animation root.collapseCells(animated: false) expandedCell.topViewTopConstraint.constant = 0 expandedCell.topViewHeightConstraint.constant = appearance.topViewHeight expandedCell.hideSeparator(false, animated: true) expandedCell.topView.setNeedsLayout() UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() let yOffset = detailTableView.contentOffset.y let topViewSize = CGSize(width: view.bounds.width, height: appearance.topViewHeight) UIGraphicsBeginImageContextWithOptions(topViewSize, true, 0) header.topView.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: topViewSize), afterScreenUpdates: true) let topViewImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let bottomViewSize = CGSize(width: view.bounds.width, height: appearance.bottomViewHeight) UIGraphicsBeginImageContextWithOptions(bottomViewSize, true, 0) header.bottomView.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: bottomViewSize), afterScreenUpdates: true) let bottomViewImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let size = CGSize(width: view.bounds.width, height: view.bounds.height - header.frame.height) UIGraphicsBeginImageContextWithOptions(size, true, 0) image.draw(at: CGPoint(x: 0, y: -header.frame.height)) let tableViewImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let bottomViewImageView = UIImageView(image: bottomViewImage) let topViewImageView = UIImageView(image: topViewImage) let tableViewSnapshotView = UIImageView(image: tableViewImage) // Add `header` and `tableView` snapshot to temporary container containerView.addSubview(bottomViewImageView) containerView.addSubview(tableViewSnapshotView) containerView.addSubview(topViewImageView) // Prepare view to dismissing let rect = rootTableView.rectForRow(at: path) let cellFrame = rootTableView.convert(rect, to: containerView) detailTableView.alpha = 0 // Place views at their start points. topViewImageView.frame = CGRect(x: 0, y: -yOffset, width: topViewSize.width, height: topViewSize.height) bottomViewImageView.frame = CGRect(x: 0, y: -yOffset + topViewSize.height, width: view.bounds.width, height: bottomViewSize.height) tableViewSnapshotView.frame = CGRect(x: 0, y: header.frame.maxY - yOffset, width: view.bounds.width, height: tableViewSnapshotView.frame.height) UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: { root.view?.alpha = 1 tableViewSnapshotView.alpha = 0 // Animate views to collapsed cell size let collapsedFrame = CGRect(x: 0, y: cellFrame.origin.y, width: header.frame.width, height: cellFrame.height) topViewImageView.frame = collapsedFrame bottomViewImageView.frame = collapsedFrame tableViewSnapshotView.frame = collapsedFrame expandedCell.contentView.layoutIfNeeded() }, completion: { completed in root.state = .normal root.expandedIndexPath = nil view.removeFromSuperview() context.completeTransition(completed) }) } }
a1154cee4d21b9d6cf2277331e82ee0e
46.737828
157
0.707908
false
false
false
false
coshx/caravel
refs/heads/master
caravel/internal/DataSerializer.swift
mit
1
import Foundation /** **DataSerializer** Serializes data to JS format and parses data coming from JS */ internal class DataSerializer { internal static func serialize<T>(_ input: T) throws -> String { var output: String? if let b = input as? Bool { output = b ? "true" : "false" } else if let i = input as? Int { output = "\(i)" } else if let f = input as? Float { output = "\(f)" } else if let d = input as? Double { output = "\(d)" } else if var s = input as? String { // As this string is going to be unwrapped from quotes, when passed to JS, all quotes need to be escaped s = s.replacingOccurrences(of: "\"", with: "\\\"", options: NSString.CompareOptions(), range: nil) s = s.replacingOccurrences(of: "'", with: "\'", options: NSString.CompareOptions(), range: nil) output = "\"\(s)\"" } else if let a = input as? NSArray { // Array and Dictionary are serialized to JSON. // They should wrap only "basic" data (same types than supported ones) let json = try! JSONSerialization.data(withJSONObject: a, options: JSONSerialization.WritingOptions()) output = NSString(data: json, encoding: String.Encoding.utf8.rawValue)! as String } else if let d = input as? NSDictionary { let json = try! JSONSerialization.data(withJSONObject: d, options: JSONSerialization.WritingOptions()) output = NSString(data: json, encoding: String.Encoding.utf8.rawValue)! as String } else { throw CaravelError.serializationUnsupportedData } return output! } internal static func deserialize(_ input: String) -> AnyObject { if input.characters.count > 0 { if (input.first == "[" && input.last == "]") || (input.first == "{" && input.last == "}") { // Array or Dictionary, matching JSON format let json = input.data(using: String.Encoding.utf8, allowLossyConversion: false)! return try! JSONSerialization.jsonObject(with: json, options: JSONSerialization.ReadingOptions()) as AnyObject } if input == "true" { return true as AnyObject } else if input == "false" { return false as AnyObject } var isNumber = true for i in 0..<input.characters.count { if Int(input[i]) != nil || input[i] == "." || input[i] == "," { // Do nothing } else { isNumber = false break } } if isNumber { if let i = Int(input) { return i as AnyObject } else { return (input as NSString).doubleValue as AnyObject } } } return input as AnyObject } }
de3d66185b27a1104ce413da9c0cfe9d
39.552632
126
0.522388
false
false
false
false
mibaldi/IOS_MIMO_APP
refs/heads/master
iosAPP/ingredients/IngredientsViewController.swift
apache-2.0
1
// // IngredientsViewController.swift // iosAPP // // Created by MIMO on 14/2/16. // Copyright © 2016 mikel balduciel diaz. All rights reserved. // import UIKit class IngredientsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{ @IBOutlet weak var categorias: UICollectionView! let reuseIdentifier = "cell" var items = [Dictionary<String,AnyObject>]() var category = "" var screenWidth = UIScreen.mainScreen().bounds.width var screenHeight = UIScreen.mainScreen().bounds.height var myLayout = UICollectionViewFlowLayout() @IBOutlet weak var ingredientsLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() setText() categoryInit() myLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) myLayout.minimumInteritemSpacing = 0 myLayout.minimumLineSpacing = 0 if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation){ screenWidth = UIScreen.mainScreen().bounds.width screenHeight = UIScreen.mainScreen().bounds.height print("POO") myLayout.itemSize = CGSize(width:screenWidth/4 , height: screenHeight/3) }else{ myLayout.itemSize = CGSize(width: screenWidth/3, height: screenHeight/5.5) } self.categorias.setCollectionViewLayout(myLayout, animated: false) } func setText(){ ingredientsLabel.text = NSLocalizedString("INGREDIENTS",comment:"Ingredientes") } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { screenWidth = UIScreen.mainScreen().bounds.width screenHeight = UIScreen.mainScreen().bounds.height if (toInterfaceOrientation.isLandscape){ myLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) myLayout.minimumInteritemSpacing = 0 myLayout.minimumLineSpacing = 0 myLayout.itemSize = CGSize(width:screenHeight/4 , height: screenWidth/3) }else{ myLayout.itemSize = CGSize(width: screenHeight/3, height: screenWidth/5.5) } self.categorias.setCollectionViewLayout(myLayout, animated: false) } func categoryInit(){ let filePath = NSBundle.mainBundle().pathForResource("Category", ofType: "json") let jsonData = NSData.init(contentsOfFile: filePath!) do { let objOrigen = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: [.MutableContainers, .MutableLeaves]) as! [String:AnyObject] for category in objOrigen["Categories"] as! [[String:AnyObject]] { items.append(category) } } catch let error as NSError { print("json error: \(error.localizedDescription)") } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCollectionViewCell cell.categoryLabel.text = self.items[indexPath.item]["category"] as? String var image = self.items[indexPath.item]["image"] as! String if(image == ""){ image = "Carne" } cell.image.image = UIImage(named: image) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { category = items[indexPath.row]["category"] as! String performSegueWithIdentifier("ingredientsCategory", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let segueID = segue.identifier{ if segueID == "ingredientsCategory"{ if let destinoVC = segue.destinationViewController as? IngredientListViewController{ destinoVC.category = self.category } } } } }
58a4ae04fc64cf3816041df0c760deb0
36.322034
145
0.64941
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
refs/heads/master
Former/RowFormers/SelectorDatePickerRowFormer.swift
mit
2
// // SelectorDatePickerRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 8/24/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol SelectorDatePickerFormableRow: FormableRow { var selectorDatePicker: UIDatePicker? { get set } // Needs NOT to set instance. var selectorAccessoryView: UIView? { get set } // Needs NOT to set instance. func formTitleLabel() -> UILabel? func formDisplayLabel() -> UILabel? func formDefaultDisplayDate() -> NSDate? func formDefaultDisplayLabelText() -> String? //If formDefaultDisplayDate() returns a real date, the return value from this is ignored } open class SelectorDatePickerRowFormer<T: UITableViewCell> : BaseRowFormer<T>, Formable, UpdatableSelectorForm where T: SelectorDatePickerFormableRow { // MARK: Public override open var canBecomeEditing: Bool { return enabled } open var date: Date? = nil open var inputAccessoryView: UIView? open var titleDisabledColor: UIColor? = .lightGray open var displayDisabledColor: UIColor? = .lightGray open var titleEditingColor: UIColor? open var displayEditingColor: UIColor? public private(set) final lazy var selectorView: UIDatePicker = { [unowned self] in let datePicker = UIDatePicker() datePicker.addTarget(self, action: #selector(SelectorDatePickerRowFormer.dateChanged(datePicker:)), for: .valueChanged) return datePicker }() public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } @discardableResult public final func onDateChanged(_ handler: @escaping ((Date) -> Void)) -> Self { onDateChanged = handler return self } @discardableResult public final func displayTextFromDate(_ handler: @escaping ((Date) -> String)) -> Self { displayTextFromDate = handler return self } open override func update() { super.update() cell.selectorDatePicker = selectorView cell.selectorAccessoryView = inputAccessoryView let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if let date = date { displayLabel?.text = displayTextFromDate?(date) ?? "\(date)" } else if let defaultDate = cell.formDefaultDisplayDate() { self.date = defaultDate as Date displayLabel?.text = displayTextFromDate?(defaultDate as Date) ?? "\(defaultDate)" } else if let defaultDisplayText = cell.formDefaultDisplayLabelText() { displayLabel?.text = defaultDisplayText } if self.enabled { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayTextColor.map { displayLabel?.textColor = $0 } titleColor = nil displayTextColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .black } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .black } titleLabel?.textColor = titleDisabledColor displayLabel?.textColor = displayDisabledColor } } open override func cellSelected(indexPath: IndexPath) { former?.deselect(animated: true) } public func editingDidBegin() { if enabled { let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if titleColor == nil { titleColor = titleLabel?.textColor ?? .black } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .black } _ = titleEditingColor.map { titleLabel?.textColor = $0 } _ = displayEditingColor.map { displayEditingColor = $0 } isEditing = true } } public func editingDidEnd() { isEditing = false let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if enabled { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayTextColor.map { displayLabel?.textColor = $0 } titleColor = nil displayTextColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .black } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .black } titleLabel?.textColor = titleDisabledColor displayLabel?.textColor = displayDisabledColor } } // MARK: Private private final var onDateChanged: ((Date) -> Void)? private final var displayTextFromDate: ((Date) -> String)? private final var titleColor: UIColor? private final var displayTextColor: UIColor? @objc private dynamic func dateChanged(datePicker: UIDatePicker) { let date = datePicker.date self.date = date cell.formDisplayLabel()?.text = displayTextFromDate?(date) ?? "\(date)" onDateChanged?(date) } }
39357da12e9fb3a8deae67109130cb21
35.957447
138
0.633468
false
false
false
false
knutigro/AppReviews
refs/heads/develop
AppReviews/NSImageView+Networking.swift
gpl-3.0
1
// // NSImageView+Networking.swift // App Reviews // // Created by Knut Inge Grosland on 2015-04-13. // Copyright (c) 2015 Cocmoc. All rights reserved. // import AppKit protocol AFImageCacheProtocol:class{ func cachedImageForRequest(request:NSURLRequest) -> NSImage? func cacheImage(image:NSImage, forRequest request:NSURLRequest); } extension NSImageView { private struct AssociatedKeys { static var SharedImageCache = "SharedImageCache" static var RequestImageOperation = "RequestImageOperation" static var URLRequestImage = "UrlRequestImage" } class func setSharedImageCache(cache:AFImageCacheProtocol?) { objc_setAssociatedObject(self, &AssociatedKeys.SharedImageCache, cache, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } class func sharedImageCache() -> AFImageCacheProtocol { struct Static { static var token: dispatch_once_t = 0 static var defaultImageCache:AFImageCache? } dispatch_once(&Static.token, { () -> Void in Static.defaultImageCache = AFImageCache() }) return objc_getAssociatedObject(self, &AssociatedKeys.SharedImageCache) as? AFImageCache ?? Static.defaultImageCache! } class func af_sharedImageRequestOperationQueue() -> NSOperationQueue { struct Static { static var token:dispatch_once_t = 0 static var queue:NSOperationQueue? } dispatch_once(&Static.token, { () -> Void in Static.queue = NSOperationQueue() Static.queue!.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount }) return Static.queue! } private var af_requestImageOperation:(operation:NSOperation?, request: NSURLRequest?) { get { let operation:NSOperation? = objc_getAssociatedObject(self, &AssociatedKeys.RequestImageOperation) as? NSOperation let request:NSURLRequest? = objc_getAssociatedObject(self, &AssociatedKeys.URLRequestImage) as? NSURLRequest return (operation, request) } set { objc_setAssociatedObject(self, &AssociatedKeys.RequestImageOperation, newValue.operation, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.URLRequestImage, newValue.request, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func setImageWithUrl(url:NSURL, placeHolderImage:NSImage? = nil) { let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.addValue("image/*", forHTTPHeaderField: "Accept") setImageWithUrlRequest(request, placeHolderImage: placeHolderImage, success: nil, failure: nil) } func setImageWithUrlRequest(request:NSURLRequest, placeHolderImage:NSImage? = nil, success:((request:NSURLRequest?, response:NSURLResponse?, image:NSImage) -> Void)?, failure:((request:NSURLRequest?, response:NSURLResponse?, error:NSError) -> Void)?) { cancelImageRequestOperation() if let cachedImage = NSImageView.sharedImageCache().cachedImageForRequest(request) { if success != nil { success!(request: nil, response:nil, image: cachedImage) } else { image = cachedImage } return } if placeHolderImage != nil { image = placeHolderImage } af_requestImageOperation = (NSBlockOperation(block: { () -> Void in var response:NSURLResponse? var error:NSError? let data: NSData? do { data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) } catch let error1 as NSError { error = error1 data = nil } catch { fatalError() } dispatch_async(dispatch_get_main_queue(), { () -> Void in if request.URL!.isEqual(self.af_requestImageOperation.request?.URL) { let image:NSImage? = (data != nil ? NSImage(data: data!): nil) if image != nil { if success != nil { success!(request: request, response: response, image: image!) } else { self.image = image! } } else { if failure != nil { failure!(request: request, response:response, error: error!) } } self.af_requestImageOperation = (nil, nil) } }) }), request) NSImageView.af_sharedImageRequestOperationQueue().addOperation(af_requestImageOperation.operation!) } private func cancelImageRequestOperation() { af_requestImageOperation.operation?.cancel() af_requestImageOperation = (nil, nil) } } func AFImageCacheKeyFromURLRequest(request:NSURLRequest) -> String { return request.URL!.absoluteString } class AFImageCache: NSCache, AFImageCacheProtocol { func cachedImageForRequest(request: NSURLRequest) -> NSImage? { switch request.cachePolicy { case NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData: return nil default: break } return objectForKey(AFImageCacheKeyFromURLRequest(request)) as? NSImage } func cacheImage(image: NSImage, forRequest request: NSURLRequest) { setObject(image, forKey: AFImageCacheKeyFromURLRequest(request)) } }
c8a1976e37f63cf6850e911f00e4a6ad
37.816993
159
0.611991
false
false
false
false
marty-suzuki/QiitaApiClient
refs/heads/master
QiitaApiClient/QiitaApplicationInfo.swift
mit
1
// // QiitaApplicationInfo.swift // QiitaApiClient // // Created by Taiki Suzuki on 2016/08/19. // // import Foundation class QiitaApplicationInfo { private struct Const { static let QiitaCodeKey = "qiita_code" static let QiitaAccessTokenKey = "qiita_access_token" } static let sharedInfo: QiitaApplicationInfo = .init() let clientId: String let clientSecret: String let redirectURL: String let scope: String var code: String? { get { return NSUserDefaults.standardUserDefaults().stringForKey(Const.QiitaCodeKey) } set { let ud = NSUserDefaults.standardUserDefaults() ud.setObject(newValue, forKey: Const.QiitaCodeKey) ud.synchronize() } } var accessToken: String? { get { return NSUserDefaults.standardUserDefaults().stringForKey(Const.QiitaAccessTokenKey) } set { let ud = NSUserDefaults.standardUserDefaults() ud.setObject(newValue, forKey: Const.QiitaAccessTokenKey) ud.synchronize() } } private init() { guard let infoDict = NSBundle.mainBundle().infoDictionary?["QiitaApplicaiontInfo"] as? [String : NSObject] else { fatalError("can not find Qiita Applicaiont Info") } guard let clientId = infoDict["client_id"] as? String where !clientId.isEmpty else { fatalError("can not find Qiita Applicationt Client Id") } guard let clientSecret = infoDict["client_secret"] as? String where !clientSecret.isEmpty else { fatalError("can not find Qiita Applicationt Client Secret") } guard let redirectURL = infoDict["redirect_url"] as? String where !redirectURL.isEmpty else { fatalError("can not find Qiita Applicationt redirect URL") } guard let rawScope = infoDict["scope"] as? [String] else { fatalError("can not find Qiita Application scope") } self.clientId = clientId self.clientSecret = clientSecret self.redirectURL = redirectURL let scopes: [QiitaAuthorizeScope] = rawScope.map { guard let scope = QiitaAuthorizeScope(rawValue: $0) else { fatalError("invalid scope string \"\($0)\"") } return scope } let scopeStrings: [String] = scopes.map { $0.rawValue } let scopeString: String = scopeStrings.reduce("") { $0 == "" ? $1 : $0 + "+" + $1 } self.scope = scopeString } }
dba4cf55c8e3fdb281c4293f82817257
34.315068
121
0.611952
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Common/UI/TabBarViewController/TabBarViewController.swift
agpl-3.0
2
// // TabBarViewController.swift // SmartReceipts // // Created by Bogdan Evsenev on 14.11.2019. // Copyright © 2019 Will Baumann. All rights reserved. // import Foundation class TabBarViewController: UITabBarController, UITabBarControllerDelegate, Storyboardable { private var tabBarView: TabBar? override func viewDidLoad() { tabBarView = tabBar as? TabBar tabBar.unselectedItemTintColor = UIColor.black.withAlphaComponent(0.3) tabBar.tintColor = #colorLiteral(red: 0.2705882353, green: 0.1568627451, blue: 0.6235294118, alpha: 1) tabBarView?.updateIndicatorPosition(item: selectedViewController?.tabBarItem) tabBarView?.actionButton.addTarget(self, action: #selector(didTapActionButton), for: .touchUpInside) delegate = self } @objc func didTapActionButton() { let tabWithAction = viewControllers?[selectedIndex] as? TabHasMainAction tabWithAction?.mainAction() } override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { UIView.animate(withDuration: DEFAULT_ANIMATION_DURATION) { [weak self] in self?.tabBarView?.updateIndicatorPosition(item: item) } guard let index = tabBar.items?.firstIndex(of: item) else { return } let tabWithAction = viewControllers?[index] as? TabHasMainAction guard let icon = tabWithAction?.actionIcon else { return } tabBarView?.actionButton.setImage(icon.withRenderingMode(.alwaysOriginal), for: .normal) } func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { return viewController.tabBarItem.tag > Constants.unselectableTag } } extension TabBarViewController { enum Constants { static let unselectableTag = -1 } } protocol TabHasMainAction { func mainAction() var actionIcon: UIImage { get } } extension TabHasMainAction { var actionIcon: UIImage { return #imageLiteral(resourceName: "white_plus") } }
8304225c99a7e498127273648a6b0a8f
33.881356
122
0.704568
false
false
false
false