repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
MAARK/Charts
ChartsDemo-iOS/Swift/Demos/LineChart1ViewController.swift
2
6628
// // LineChart1ViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class LineChart1ViewController: DemoBaseViewController { @IBOutlet var chartView: LineChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Line Chart 1" self.options = [.toggleValues, .toggleFilled, .toggleCircles, .toggleCubic, .toggleHorizontalCubic, .toggleIcons, .toggleStepped, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.pinchZoomEnabled = true // x-axis limit line let llXAxis = ChartLimitLine(limit: 10, label: "Index 10") llXAxis.lineWidth = 4 llXAxis.lineDashLengths = [10, 10, 0] llXAxis.labelPosition = .bottomRight llXAxis.valueFont = .systemFont(ofSize: 10) chartView.xAxis.gridLineDashLengths = [10, 10] chartView.xAxis.gridLineDashPhase = 0 let ll1 = ChartLimitLine(limit: 150, label: "Upper Limit") ll1.lineWidth = 4 ll1.lineDashLengths = [5, 5] ll1.labelPosition = .topRight ll1.valueFont = .systemFont(ofSize: 10) let ll2 = ChartLimitLine(limit: -30, label: "Lower Limit") ll2.lineWidth = 4 ll2.lineDashLengths = [5,5] ll2.labelPosition = .bottomRight ll2.valueFont = .systemFont(ofSize: 10) let leftAxis = chartView.leftAxis leftAxis.removeAllLimitLines() leftAxis.addLimitLine(ll1) leftAxis.addLimitLine(ll2) leftAxis.axisMaximum = 200 leftAxis.axisMinimum = -50 leftAxis.gridLineDashLengths = [5, 5] leftAxis.drawLimitLinesBehindDataEnabled = true chartView.rightAxis.enabled = false //[_chartView.viewPortHandler setMaximumScaleY: 2.f]; //[_chartView.viewPortHandler setMaximumScaleX: 2.f]; let marker = BalloonMarker(color: UIColor(white: 180/255, alpha: 1), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8)) marker.chartView = chartView marker.minimumSize = CGSize(width: 80, height: 40) chartView.marker = marker chartView.legend.form = .line sliderX.value = 45 sliderY.value = 100 slidersValueChanged(nil) chartView.animate(xAxisDuration: 2.5) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let values = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i), y: val, icon: #imageLiteral(resourceName: "icon")) } let set1 = LineChartDataSet(entries: values, label: "DataSet 1") set1.drawIconsEnabled = false set1.lineDashLengths = [5, 2.5] set1.highlightLineDashLengths = [5, 2.5] set1.setColor(.black) set1.setCircleColor(.black) set1.lineWidth = 1 set1.circleRadius = 3 set1.drawCircleHoleEnabled = false set1.valueFont = .systemFont(ofSize: 9) set1.formLineDashLengths = [5, 2.5] set1.formLineWidth = 1 set1.formSize = 15 let gradientColors = [ChartColorTemplates.colorFromString("#00ff0000").cgColor, ChartColorTemplates.colorFromString("#ffff0000").cgColor] let gradient = CGGradient(colorsSpace: nil, colors: gradientColors as CFArray, locations: nil)! set1.fillAlpha = 1 set1.fill = Fill(linearGradient: gradient, angle: 90) //.linearGradient(gradient, angle: 90) set1.drawFilledEnabled = true let data = LineChartData(dataSet: set1) chartView.data = data } override func optionTapped(_ option: Option) { switch option { case .toggleFilled: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawFilledEnabled = !set.drawFilledEnabled } chartView.setNeedsDisplay() case .toggleCircles: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawCirclesEnabled = !set.drawCirclesEnabled } chartView.setNeedsDisplay() case .toggleCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier } chartView.setNeedsDisplay() case .toggleStepped: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .stepped) ? .linear : .stepped } chartView.setNeedsDisplay() case .toggleHorizontalCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .horizontalBezier : .cubicBezier } chartView.setNeedsDisplay() default: super.handleOption(option, forChartView: chartView) } } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
6d56d72a9eac7225a6ebd7a95bb1227f
34.438503
103
0.56466
5.024261
false
false
false
false
iDevelopper/PBRevealViewController
Example3Swift/Example3Swift/MainViewController.swift
1
3120
// // MainViewController.swift // Example3Swift // // Created by Patrick BODET on 06/08/2016. // Copyright © 2016 iDevelopper. All rights reserved. // import UIKit class MainViewController: UIViewController { var image: UIImage? @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var leftButton: UIBarButtonItem! @IBOutlet weak var rightButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() leftButton.target = self.revealViewController() leftButton.action = #selector(PBRevealViewController.revealLeftView) rightButton.target = self.revealViewController() rightButton.action = #selector(PBRevealViewController.revealRightView) if (image != nil) { imageView.image = image } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func replaceLeftView(_ sender: UIBarButtonItem) { var controller: UIViewController? let storyboard = UIStoryboard(name: "Main", bundle: nil) let nc = revealViewController().leftViewController as! UINavigationController if nc.topViewController! is MenuTableViewController { self.revealViewController().leftViewBlurEffectStyle = .none controller = storyboard.instantiateViewController(withIdentifier: "RightViewController") controller!.title = "Menu" } else { self.revealViewController().leftViewBlurEffectStyle = .light controller = storyboard.instantiateViewController(withIdentifier: "MenuTableViewController") } let newNc = UINavigationController(rootViewController: controller!) revealViewController().setLeft(newNc, animated: true) } @IBAction func resizeLeftView(_ sender: UIBarButtonItem) { if revealViewController().leftViewRevealWidth < 200 { revealViewController().setLeftViewRevealWidth(200, animated: true) } else { revealViewController().setLeftViewRevealWidth(180, animated: true) } } @IBAction func replaceRightView(_ sender: UIBarButtonItem) { var controller: UIViewController? let storyboard = UIStoryboard(name: "Main", bundle: nil) if revealViewController().rightViewController is RightViewController2 { controller = storyboard.instantiateViewController(withIdentifier: "RightViewController") } else { controller = storyboard.instantiateViewController(withIdentifier: "RightViewController2") } revealViewController().setRight(controller, animated: true) } @IBAction func resizeRightView(_ sender: UIBarButtonItem) { if revealViewController().rightViewRevealWidth < 180 { revealViewController().rightViewRevealWidth = 180 } else { revealViewController().rightViewRevealWidth = 160 } } }
mit
af0337cf5b205b0bfccba82460f80722
34.044944
104
0.663033
5.929658
false
false
false
false
rb-de0/tech.reb-dev.com
Sources/App/Controllers/ArticleRegisterController.swift
2
1527
final class ArticleRegisterController: ResourceRepresentable { private let view: ViewRenderer private let twitterClient: TwitterClient init(view: ViewRenderer, twitterClient: TwitterClient) { self.view = view self.twitterClient = twitterClient } func makeResource() -> Resource<String>{ return Resource( index: index, store: store ) } func index(request: Request) throws -> ResponseRepresentable { return try view.makeWithBase(request: request, path: "article-register") } func store(request: Request) throws -> ResponseRepresentable { do { let article = try Article(request: request) try article.save() guard let id = article.id?.int else { throw Abort.serverError } twitterClient.tweetNewRegister(title: article.title, articleId: id) return Response(redirect: "/edit/\(id)?message=\(SuccessMessage.articleRegister)") } catch { let context: NodeRepresentable = [ "title": request.data["title"]?.string ?? "", "content": request.data["content"]?.string ?? "", "error_message": error.localizedDescription ] return try view.makeWithBase(request: request, path: "article-register", context: context) } } }
mit
6f22cb8782026b6ba09129a5e975dfb0
29.54
103
0.553373
5.552727
false
false
false
false
MingLoan/SimpleTransition
Pod/Classes/SimplePresentationController.swift
2
7767
// SimplePresentationController.swift // // Copyright (c) 2016, Mingloan, Keith Chan. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit final class SimplePresentationController: UIPresentationController { // default value var keepPresentingViewOrientation = false var keepPresentingViewAfterPresentation = false var presentedViewAlignment: TransitionPresentedViewAlignment = .centerCenter var dismissViaChromeView = false { willSet { if newValue { addTapOnChromeView(); } else { removeTapOnChromeView(); } } } var presentedViewSize = SimpleTransition.FlexibleSize var chromeViewBackgroundColor: UIColor = UIColor(white: 0.0, alpha: 0.3) { didSet { chromeView.backgroundColor = chromeViewBackgroundColor } } let chromeView = UIView() fileprivate lazy var boundsOfPresentedViewInContainerView: CGRect = { return CGRect(origin: CGPoint.zero, size: self.presentedViewSize) }() lazy var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap(_:))) override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) chromeView.backgroundColor = UIColor(white: 0.0, alpha: 0.3) chromeView.alpha = 0.0 delegate = self } // MARK: override func override var frameOfPresentedViewInContainerView : CGRect { var frame = boundsOfPresentedViewInContainerView guard let containerView = containerView else { return frame } guard let presentedView = presentedView else { return frame } switch presentedViewAlignment { case .topLeft: break case .topCenter: frame.origin = CGPoint(x: presentedView.frame.midX - frame.width/2, y: frame.minY) break case .topRight: frame.origin = CGPoint(x: presentedView.frame.width - frame.width, y: frame.minY) break case .centerLeft: frame.origin = CGPoint(x: frame.minX, y: presentedView.frame.midY - frame.height/2) break case .centerCenter: frame.origin = CGPoint(x: presentedView.frame.midX - frame.width/2, y: presentedView.frame.midY - frame.height/2) break case .centerRight: frame.origin = CGPoint(x: presentedView.frame.width - frame.width, y: presentedView.frame.midY - frame.height/2) break case .bottomLeft: frame.origin = CGPoint(x: frame.minX, y: containerView.frame.height - frame.height) break case .bottomCenter: frame.origin = CGPoint(x: containerView.bounds.midX - frame.width/2, y: containerView.frame.height - frame.height) break case .bottomRight: frame.origin = CGPoint(x: containerView.bounds.width - frame.width, y: containerView.frame.height - frame.height) break } return frame } override func containerViewWillLayoutSubviews() { guard let containerView = containerView else { return } chromeView.frame = containerView.bounds } override func presentationTransitionWillBegin() { guard let containerView = containerView else { return } guard let coordinator = presentedViewController.transitionCoordinator else { return } chromeView.frame = containerView.bounds chromeView.alpha = 0.0 containerView.insertSubview(chromeView, at:0) coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in self.chromeView.alpha = 1.0 }, completion: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in }) } override func presentationTransitionDidEnd(_ completed: Bool) { if !completed { chromeView.removeFromSuperview() } } override func dismissalTransitionWillBegin() { guard let coordinator = presentedViewController.transitionCoordinator else { return } coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in self.chromeView.alpha = 0.0 }, completion: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in }) } override func dismissalTransitionDidEnd(_ completed: Bool) { if !completed { UIView.animate( withDuration: 0.2, animations: { self.chromeView.alpha = 1.0; }) } else { chromeView.removeFromSuperview() } } override var shouldPresentInFullscreen : Bool { if (SimpleTransition.FlexibleSize.equalTo(presentedViewSize) && !keepPresentingViewAfterPresentation) { return true } return false } override var shouldRemovePresentersView : Bool { if keepPresentingViewOrientation || shouldPresentInFullscreen { return true } return false } override var adaptivePresentationStyle : UIModalPresentationStyle { return .fullScreen } override func adaptivePresentationStyle(for traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .fullScreen } // MARK: Chrome View func addTapOnChromeView() { chromeView.addGestureRecognizer(tapGesture) } func removeTapOnChromeView() { chromeView.removeGestureRecognizer(tapGesture) } // MARK: Tap Chrome View func tap(_ sender: UITapGestureRecognizer) { if sender.state == .ended { presentedViewController.dismiss(animated: true, completion: nil) } } } // MARK: - UIAdaptivePresentationControllerDelegate extension SimplePresentationController: UIAdaptivePresentationControllerDelegate { func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { // further development... return nil } }
mit
882eb1d4d970c52bf438ffb67787be19
36.521739
170
0.645037
5.575736
false
false
false
false
kaushaldeo/Olympics
Olympics/Pager/ViewPagerController+ScrollHeaderSupport.swift
1
5518
// // ViewPagerController+ScrollHeaderSupport.swift // ViewPagerController // // Created by xxxAIRINxxx on 2016/01/05. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit extension ViewPagerController { // MARK: - Override (KVO) override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (keyPath == "contentOffset") { let old = change?[NSKeyValueChangeOldKey]?.CGPointValue let new = change?[NSKeyValueChangeNewKey]?.CGPointValue guard let _old = old, _new = new else { return } switch self.scrollViewObservingType { case .Header: self.updateHeaderViewHeight(_old, currentOffset: _new) case .NavigationBar: self.updateNavigationBarHeight(_old, currentOffset: _new) case .None: break } } } // MARK: - Public Functions public func resetHeaderViewHeight(animated: Bool) { self.headerViewHeightConstraint.constant = self.headerViewHeight UIView.animateWithDuration(animated ? 0.25 : 0, animations: { self.view.layoutIfNeeded() }) } public func resetNavigationBarHeight(animated: Bool) { if let _navigationBar = self.targetNavigationBar { self.viewTopConstraint.constant = 0 UIView.animateWithDuration(animated ? 0.25 : 0, animations: { _navigationBar.frame.origin.y = self.navigationBarBaselineOriginY() self.view.layoutIfNeeded() }) } } // MARK: - Private Functions private func updateHeaderViewHeight(prevOffset: CGPoint, currentOffset: CGPoint) { let maxHeaderHeight = self.headerViewHeight let minHeaderHeight = self.scrollViewMinPositionY if prevOffset.y == currentOffset.y { return } if prevOffset.y <= currentOffset.y { // down scrolling if currentOffset.y <= 0 { return } let diff = currentOffset.y - prevOffset.y if (self.headerViewHeightConstraint.constant - diff) < minHeaderHeight { if self.headerViewHeightConstraint.constant == minHeaderHeight { return } self.headerViewHeightConstraint.constant = minHeaderHeight } else { self.headerViewHeightConstraint.constant -= diff * self.scrollViewObservingDelay } } else { // up scrolling if currentOffset.y > self.headerViewHeight { return } let diff = prevOffset.y - currentOffset.y if (self.headerViewHeightConstraint.constant + diff) > maxHeaderHeight { if self.headerViewHeightConstraint.constant == maxHeaderHeight { return } self.headerViewHeightConstraint.constant = maxHeaderHeight } else { self.headerViewHeightConstraint.constant += diff * self.scrollViewObservingDelay } } self.view.layoutIfNeeded() self.didChangeHeaderViewHeightHandler?(self.headerViewHeightConstraint.constant) } private func updateNavigationBarHeight(prevOffset: CGPoint, currentOffset: CGPoint) { if let _navigationBar = self.targetNavigationBar { let minHeaderHeight = self.scrollViewMinPositionY let baselineOriginY = self.navigationBarBaselineOriginY() let visibleBarHeight = _navigationBar.frame.size.height + _navigationBar.frame.origin.y let minNavigatonBarOriginY = -(_navigationBar.frame.size.height - minHeaderHeight) if prevOffset.y == currentOffset.y { return } if prevOffset.y <= currentOffset.y { // down scrolling if currentOffset.y <= 0 { return } let diff = currentOffset.y - prevOffset.y if (visibleBarHeight - diff) < minHeaderHeight { _navigationBar.frame.origin.y = minNavigatonBarOriginY self.viewTopConstraint.constant = minNavigatonBarOriginY - baselineOriginY } else { _navigationBar.frame.origin.y -= diff * self.scrollViewObservingDelay self.viewTopConstraint.constant -= diff * self.scrollViewObservingDelay } } else { // up scrolling if currentOffset.y > (baselineOriginY + _navigationBar.frame.size.height) { return } let diff = prevOffset.y - currentOffset.y if (_navigationBar.frame.origin.y + diff) > baselineOriginY { _navigationBar.frame.origin.y = baselineOriginY self.viewTopConstraint.constant = 0 } else { _navigationBar.frame.origin.y += diff * self.scrollViewObservingDelay self.viewTopConstraint.constant += diff * self.scrollViewObservingDelay } } self.view.layoutIfNeeded() self.didChangeHeaderViewHeightHandler?(visibleBarHeight) } } private func navigationBarBaselineOriginY() -> CGFloat { return UIApplication.sharedApplication().statusBarFrame.size.height } }
apache-2.0
bb1f10e4e67b179a78db43e460e41ac1
41.114504
164
0.603589
5.578362
false
false
false
false
magnetsystems/message-samples-ios
Soapbox/Pods/MagnetMaxCore/MagnetMax/Core/Operations/URLSessionTaskOperation.swift
7
2338
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Shows how to lift operation-like objects in to the NSOperation world. */ import Foundation private var URLSessionTaksOperationKVOContext = 0 /** `URLSessionTaskOperation` is an `Operation` that lifts an `NSURLSessionTask` into an operation. Note that this operation does not participate in any of the delegate callbacks \ of an `NSURLSession`, but instead uses Key-Value-Observing to know when the task has been completed. It also does not get notified about any errors that occurred during execution of the task. An example usage of `URLSessionTaskOperation` can be seen in the `DownloadEarthquakesOperation`. */ // Includes a fix from here: https://github.com/pluralsight/PSOperations/pull/24/files#diff-086cc60d8fd6d7e2b0102a0c2036e30e public class URLSessionTaskOperation: Operation { let task: NSURLSessionTask private var observerRemoved = false private let stateLock = NSLock() public init(task: NSURLSessionTask) { assert(task.state == .Suspended, "Tasks must be suspended.") self.task = task super.init() } override func execute() { assert(task.state == .Suspended, "Task was resumed by something other than \(self).") task.addObserver(self, forKeyPath: "state", options: [], context: &URLSessionTaksOperationKVOContext) task.resume() } override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard context == &URLSessionTaksOperationKVOContext else { return } stateLock.withCriticalScope { if object === task && keyPath == "state" && !observerRemoved { switch task.state { case .Completed: finish() fallthrough case .Canceling: observerRemoved = true task.removeObserver(self, forKeyPath: "state") default: return } } } } override public func cancel() { task.cancel() super.cancel() } }
apache-2.0
290ddb20341c14d748f465afa279a33d
33.352941
164
0.642979
4.949153
false
false
false
false
mohojojo/iOS-swiftbond-viper
Pods/Bond/Sources/Bond/Collections/ObservableArray.swift
2
20800
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Diff import ReactiveKit public enum ObservableArrayChange { case reset case inserts([Int]) case deletes([Int]) case updates([Int]) case move(Int, Int) case beginBatchEditing case endBatchEditing } public protocol ObservableArrayEventProtocol { associatedtype Item var change: ObservableArrayChange { get } var source: ObservableArray<Item> { get } } public struct ObservableArrayEvent<Item>: ObservableArrayEventProtocol { public let change: ObservableArrayChange public let source: ObservableArray<Item> public init(change: ObservableArrayChange, source: ObservableArray<Item>) { self.change = change self.source = source } public init(change: ObservableArrayChange, source: [Item]) { self.change = change self.source = ObservableArray(source) } } public class ObservableArray<Item>: Collection, SignalProtocol { public fileprivate(set) var array: [Item] fileprivate let subject = PublishSubject<ObservableArrayEvent<Item>, NoError>() fileprivate let lock = NSRecursiveLock(name: "com.reactivekit.bond.observablearray") public init(_ array: [Item] = []) { self.array = array } public func makeIterator() -> Array<Item>.Iterator { return array.makeIterator() } public var underestimatedCount: Int { return array.underestimatedCount } public var startIndex: Int { return array.startIndex } public var endIndex: Int { return array.endIndex } public func index(after i: Int) -> Int { return array.index(after: i) } public var isEmpty: Bool { return array.isEmpty } public var count: Int { return array.count } public subscript(index: Int) -> Item { get { return array[index] } } public func observe(with observer: @escaping (Event<ObservableArrayEvent<Item>, NoError>) -> Void) -> Disposable { observer(.next(ObservableArrayEvent(change: .reset, source: self))) return subject.observe(with: observer) } } extension ObservableArray: Deallocatable { public var deallocated: Signal<Void, NoError> { return subject.disposeBag.deallocated } } extension ObservableArray where Item: Equatable { public static func ==(lhs: ObservableArray<Item>, rhs: ObservableArray<Item>) -> Bool { return lhs.array == rhs.array } } public class MutableObservableArray<Item>: ObservableArray<Item> { /// Append `newElement` to the array. public func append(_ newElement: Item) { lock.lock(); defer { lock.unlock() } array.append(newElement) subject.next(ObservableArrayEvent(change: .inserts([array.count-1]), source: self)) } /// Insert `newElement` at index `i`. public func insert(_ newElement: Item, at index: Int) { lock.lock(); defer { lock.unlock() } array.insert(newElement, at: index) subject.next(ObservableArrayEvent(change: .inserts([index]), source: self)) } /// Insert elements `newElements` at index `i`. public func insert(contentsOf newElements: [Item], at index: Int) { lock.lock(); defer { lock.unlock() } array.insert(contentsOf: newElements, at: index) subject.next(ObservableArrayEvent(change: .inserts(Array(index..<index+newElements.count)), source: self)) } /// Move the element at index `i` to index `toIndex`. public func moveItem(from fromIndex: Int, to toIndex: Int) { lock.lock(); defer { lock.unlock() } let item = array.remove(at: fromIndex) array.insert(item, at: toIndex) subject.next(ObservableArrayEvent(change: .move(fromIndex, toIndex), source: self)) } /// Remove and return the element at index i. @discardableResult public func remove(at index: Int) -> Item { lock.lock(); defer { lock.unlock() } let element = array.remove(at: index) subject.next(ObservableArrayEvent(change: .deletes([index]), source: self)) return element } /// Remove an element from the end of the array in O(1). @discardableResult public func removeLast() -> Item { lock.lock(); defer { lock.unlock() } let element = array.removeLast() subject.next(ObservableArrayEvent(change: .deletes([array.count]), source: self)) return element } /// Remove all elements from the array. public func removeAll() { lock.lock(); defer { lock.unlock() } let deletes = Array(0..<array.count) array.removeAll() subject.next(ObservableArrayEvent(change: .deletes(deletes), source: self)) } public override subscript(index: Int) -> Item { get { return array[index] } set { lock.lock(); defer { lock.unlock() } array[index] = newValue subject.next(ObservableArrayEvent(change: .updates([index]), source: self)) } } /// Perform batched updates on the array. public func batchUpdate(_ update: (MutableObservableArray<Item>) -> Void) { lock.lock(); defer { lock.unlock() } // use proxy to collect changes let proxy = MutableObservableArray(array) var patch: [ObservableArrayChange] = [] let disposable = proxy.skip(first: 1).observeNext { event in patch.append(event.change) } update(proxy) disposable.dispose() // generate diff from changes let diff = generateDiff(from: patch) // if only reset, do not batch: if diff == [.reset] { subject.next(ObservableArrayEvent(change: .reset, source: self)) } else if diff.count > 0 { // ...otherwise batch: subject.next(ObservableArrayEvent(change: .beginBatchEditing, source: self)) array = proxy.array diff.forEach { change in subject.next(ObservableArrayEvent(change: change, source: self)) } subject.next(ObservableArrayEvent(change: .endBatchEditing, source: self)) } } /// Change the underlying value withouth notifying the observers. public func silentUpdate(_ update: (inout [Item]) -> Void) { lock.lock(); defer { lock.unlock() } update(&array) } } extension MutableObservableArray: BindableProtocol { public func bind(signal: Signal<ObservableArrayEvent<Item>, NoError>) -> Disposable { return signal .take(until: deallocated) .observeNext { [weak self] event in guard let s = self else { return } s.array = event.source.array s.subject.next(ObservableArrayEvent(change: event.change, source: s)) } } } // MARK: DataSourceProtocol conformation extension ObservableArrayEvent: DataSourceEventProtocol { public var kind: DataSourceEventKind { switch change { case .reset: return .reload case .inserts(let indices): return .insertItems(indices.map { IndexPath(item: $0, section: 0) }) case .deletes(let indices): return .deleteItems(indices.map { IndexPath(item: $0, section: 0) }) case .updates(let indices): return .reloadItems(indices.map { IndexPath(item: $0, section: 0) }) case .move(let from, let to): return .moveItem(IndexPath(item: from, section: 0), IndexPath(item: to, section: 0)) case .beginBatchEditing: return .beginUpdates case .endBatchEditing: return .endUpdates } } public var dataSource: ObservableArray<Item> { return source } } extension ObservableArray: DataSourceProtocol { public var numberOfSections: Int { return 1 } public func numberOfItems(inSection section: Int) -> Int { return count } } extension ObservableArray: QueryableDataSourceProtocol { public func item(at index: Int) -> Item { return self[index] } } extension MutableObservableArray { public func replace(with array: [Item]) { lock.lock(); defer { lock.unlock() } self.array = array subject.next(ObservableArrayEvent(change: .reset, source: self)) } } extension MutableObservableArray where Item: Equatable { public func replace(with array: [Item], performDiff: Bool) { if performDiff { lock.lock() let diff = self.array.extendedDiff(array) subject.next(ObservableArrayEvent(change: .beginBatchEditing, source: self)) self.array = array for step in diff { switch step { case .insert(let index): subject.next(ObservableArrayEvent(change: .inserts([index]), source: self)) case .delete(let index): subject.next(ObservableArrayEvent(change: .deletes([index]), source: self)) case .move(let from, let to): subject.next(ObservableArrayEvent(change: .move(from, to), source: self)) } } subject.next(ObservableArrayEvent(change: .endBatchEditing, source: self)) lock.unlock() } else { replace(with: array) } } } public extension SignalProtocol where Element: ObservableArrayEventProtocol { public typealias Item = Element.Item /// Map underlying ObservableArray. /// Complexity of mapping on each event is O(n). public func map<U>(_ transform: @escaping (Item) -> U) -> Signal<ObservableArrayEvent<U>, Error> { return map { (event: Element) -> ObservableArrayEvent<U> in let mappedArray = ObservableArray(event.source.array.map(transform)) return ObservableArrayEvent<U>(change: event.change, source: mappedArray) } } /// Laziliy map underlying ObservableArray. /// Complexity of mapping on each event (change) is O(1). public func lazyMap<U>(_ transform: @escaping (Item) -> U) -> Signal<ObservableArrayEvent<U>, Error> { return map { (event: Element) -> ObservableArrayEvent<U> in let mappedArray = ObservableArray(event.source.array.lazy.map(transform)) return ObservableArrayEvent<U>(change: event.change, source: mappedArray) } } /// Filter underlying ObservableArrays. /// Complexity of filtering on each event is O(n). public func filter(_ isIncluded: @escaping (Item) -> Bool) -> Signal<ObservableArrayEvent<Item>, Error> { var isBatching = false var previousIndexMap: [Int: Int] = [:] return map { (event: Element) -> [ObservableArrayEvent<Item>] in let array = event.source.array var filtered: [Item] = [] var indexMap: [Int: Int] = [:] filtered.reserveCapacity(array.count) var iterator = 0 for (index, element) in array.enumerated() { if isIncluded(element) { filtered.append(element) indexMap[index] = iterator iterator += 1 } } var changes: [ObservableArrayChange] = [] switch event.change { case .inserts(let indices): let newIndices = indices.flatMap { indexMap[$0] } if newIndices.count > 0 { changes = [.inserts(newIndices)] } case .deletes(let indices): let newIndices = indices.flatMap { previousIndexMap[$0] } if newIndices.count > 0 { changes = [.deletes(newIndices)] } case .updates(let indices): var (updates, inserts, deletes) = ([Int](), [Int](), [Int]()) for index in indices { if let mappedIndex = indexMap[index] { if let _ = previousIndexMap[index] { updates.append(mappedIndex) } else { inserts.append(mappedIndex) } } else if let mappedIndex = previousIndexMap[index] { deletes.append(mappedIndex) } } if deletes.count > 0 { changes.append(.deletes(deletes)) } if updates.count > 0 { changes.append(.updates(updates)) } if inserts.count > 0 { changes.append(.inserts(inserts)) } case .move(let previousIndex, let newIndex): if let previous = indexMap[previousIndex], let new = indexMap[newIndex] { changes = [.move(previous, new)] } case .reset: isBatching = false changes = [.reset] case .beginBatchEditing: isBatching = true changes = [.beginBatchEditing] case .endBatchEditing: isBatching = false changes = [.endBatchEditing] } if !isBatching { previousIndexMap = indexMap } if changes.count > 1 && !isBatching { changes.insert(.beginBatchEditing, at: 0) changes.append(.endBatchEditing) } let source = ObservableArray(filtered) return changes.map { ObservableArrayEvent(change: $0, source: source) } }._unwrap() } } extension SignalProtocol where Element: Collection, Element.Iterator.Element: Equatable { // Diff each emitted collection with the previously emitted one. // Returns a signal of ObservableArrayEvents that can be bound to a table or collection view. public func diff() -> Signal<ObservableArrayEvent<Element.Iterator.Element>, Error> { return Signal { observer in var previous: MutableObservableArray<Element.Iterator.Element>? = nil return self.observe { event in switch event { case .next(let element): let array = Array(element) if let previous = previous { let disposable = previous.skip(first: 1).observeNext { event in observer.next(event) } previous.replace(with: array, performDiff: true) disposable.dispose() } else { observer.next(ObservableArrayEvent(change: .reset, source: array)) } previous = MutableObservableArray(array) case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } } fileprivate extension SignalProtocol where Element: Sequence { /// Unwrap sequence elements into signal elements. fileprivate func _unwrap() -> Signal<Element.Iterator.Element, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let array): array.forEach { observer.next($0) } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } } func generateDiff(from sequenceOfChanges: [ObservableArrayChange]) -> [ObservableArrayChange] { var diff = sequenceOfChanges.flatMap { $0.unwrap } for i in 0..<diff.count { for j in 0..<i { switch (diff[i], diff[j]) { // (deletes, *) case let (.deletes(l), .deletes(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot >= index { diff[i] = .deletes([pivot+1]) } case let (.deletes(l), .inserts(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot < index { diff[j] = .inserts([index-1]) } else if pivot == index { diff[j] = .inserts([]) diff[i] = .deletes([]) } else if pivot > index { diff[i] = .deletes([pivot-1]) } case let (.deletes(l), .updates(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot == index { diff[j] = .updates([]) } case (let .deletes(l), let .move(from, to)): guard let pivot = l.first else { break } guard from != -1 else { break } var newTo = to if pivot == to { diff[j] = .inserts([]) diff[i] = .deletes([from]) break } else if pivot < to { newTo = to-1 diff[j] = .move(from, newTo) } if pivot >= from && pivot < to { diff[i] = .deletes([pivot+1]) } // (inserts, *) case (.inserts, .deletes): break case let (.inserts(l), .inserts(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot <= index { diff[j] = .inserts([index+1]) } case (.inserts, .updates): break case (let .inserts(l), let .move(from, to)): guard let pivot = l.first else { break } guard from != -1 else { break } if pivot <= to { diff[j] = .move(from, to+1) } // (updates, *) case let (.updates(l), .deletes(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot >= index { diff[i] = .updates([pivot+1]) } case let (.updates(l), .inserts(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot == index { diff[i] = .updates([]) } case let (.updates(l), .updates(r)): guard let pivot = l.first else { break } guard let index = r.first else { break } if pivot == index { diff[i] = .updates([]) } case (let .updates(l), let .move(from, to)): guard var pivot = l.first else { break } guard from != -1 else { break } if pivot == from { // Updating item at moved indices not supported. Fallback to reset. return [.reset] } if pivot >= from { pivot += 1 } if pivot >= to { pivot -= 1 } if pivot == to { // Updating item at moved indices not supported. Fallback to reset. return [.reset] } diff[i] = .updates([pivot]) case (.move, _): // Move operations in batchUpdate must be performed first. Fallback to reset. return [.reset] default: break } } } return diff.filter { change -> Bool in switch change { case .deletes(let indices): return !indices.isEmpty case .inserts(let indices): return !indices.isEmpty case .updates(let indices): return !indices.isEmpty case .move(let from, let to): return from != -1 && to != -1 default: return true } } } fileprivate extension ObservableArrayChange { fileprivate var unwrap: [ObservableArrayChange] { func deletionsPatch(_ indices: [Int]) -> [Int] { var indices = indices for i in 0..<indices.count { let pivot = indices[i] for j in (i+1)..<indices.count { let index = indices[j] if index > pivot { indices[j] = index - 1 } } } return indices } func insertionsPatch(_ indices: [Int]) -> [Int] { var indices = indices for i in 0..<indices.count { let pivot = indices[i] for j in 0..<i { let index = indices[j] if index > pivot { indices[j] = index - 1 } } } return indices } switch self { case .inserts(let indices): return insertionsPatch(indices).map { .inserts([$0]) } case .deletes(let indices): return deletionsPatch(indices).map { .deletes([$0]) } case .updates(let indices): return indices.map { .updates([$0]) } default: return [self] } } } extension ObservableArrayChange: Equatable { public static func ==(lhs: ObservableArrayChange, rhs: ObservableArrayChange) -> Bool { switch (lhs, rhs) { case (.reset, .reset): return true case (.inserts(let lhs), .inserts(let rhs)): return lhs == rhs case (.deletes(let lhs), .deletes(let rhs)): return lhs == rhs case (.updates(let lhs), .updates(let rhs)): return lhs == rhs case (.move(let lhsFrom, let lhsTo), .move(let rhsFrom, let rhsTo)): return lhsFrom == rhsFrom && lhsTo == rhsTo case (.beginBatchEditing, .beginBatchEditing): return true case (.endBatchEditing, .endBatchEditing): return true default: return false } } }
mit
ddcfe683fe95e8c04cbc23e6dddf7cd3
29.860534
116
0.622837
4.240571
false
false
false
false
LbfAiYxx/douyuTV
DouYu/DouYu/Classes/Home/view/AmuseMenuView.swift
1
2496
// // AmuseView.swift // DouYu // // Created by 刘冰峰 on 2017/1/15. // Copyright © 2017年 LBF. All rights reserved. // import UIKit class AmuseMenuView: UIView { var amuseGroups:[CategoryGroup]?{ didSet{ collectionView.reloadData() } } @IBOutlet weak var pagecontrol: UIPageControl! @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.dataSource = self collectionView.delegate = self collectionView.register(UINib.init(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: "cellID") } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal } } extension AmuseMenuView{ class func amuseView()->AmuseMenuView{ return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as!AmuseMenuView } } extension AmuseMenuView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if amuseGroups == nil { return 0 } pagecontrol.numberOfPages = (amuseGroups!.count - 1) / 8 + 1 return (amuseGroups!.count - 1) / 8 + 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell (withReuseIdentifier: "cellID", for: indexPath) as! AmuseMenuViewCell comfirmAmuseGroups(cell: cell, indexPath:indexPath) return cell } private func comfirmAmuseGroups(cell:AmuseMenuViewCell,indexPath:IndexPath){ let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 if endIndex > amuseGroups!.count - 1{ endIndex = amuseGroups!.count - 1 } cell.amuseGroups = Array(amuseGroups![startIndex...endIndex]) } } extension AmuseMenuView:UICollectionViewDelegate{ func scrollViewDidScroll(_ scrollView: UIScrollView) { pagecontrol.currentPage = Int(scrollView.contentOffset.x / CscreenW) } }
mit
76cf25213e017c5a3f1a2c0c830b539f
26.633333
124
0.66546
5.065173
false
false
false
false
kstaring/swift
test/DebugInfo/typealias.swift
11
1139
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} class DWARF { // CHECK-DAG: ![[BASE:.*]] = !DICompositeType({{.*}}identifier: "_TtVs6UInt32" // CHECK-DAG: ![[DIEOFFSET:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_TtaC9typealias5DWARF9DIEOffset",{{.*}} line: [[@LINE+1]], baseType: ![[BASE]]) typealias DIEOffset = UInt32 // CHECK-DAG: ![[VOID:.*]] = !DICompositeType({{.*}}identifier: "_TtT_" // CHECK-DAG: ![[PRIVATETYPE:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_TtaC9typealias5DWARFP{{.+}}11PrivateType",{{.*}} line: [[@LINE+1]], baseType: ![[VOID]]) fileprivate typealias PrivateType = () fileprivate static func usePrivateType() -> PrivateType { return () } } func main () { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} type: ![[DIEOFFSET]] let a : DWARF.DIEOffset = 123 markUsed(a) // CHECK-DAG: !DILocalVariable(name: "b",{{.*}} type: ![[DIEOFFSET]] let b = DWARF.DIEOffset(456) as DWARF.DIEOffset markUsed(b) // CHECK-DAG: !DILocalVariable(name: "c",{{.*}} type: ![[PRIVATETYPE]] let c = DWARF.usePrivateType() markUsed(c); } main();
apache-2.0
ed4eb29f162d90440fb77fec4fd19253
39.678571
170
0.62511
3.35
false
false
false
false
doronkatz/firefox-ios
Sync/Synchronizers/ClientsSynchronizer.swift
2
17475
/* 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 Storage import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger let ClientsStorageVersion = 1 // TODO public protocol Command { static func fromName(_ command: String, args: [JSON]) -> Command? func run(_ synchronizer: ClientsSynchronizer) -> Success static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? } // Shit. // We need a way to wipe or reset engines. // We need a way to log out the account. // So when we sync commands, we're gonna need a delegate of some kind. open class WipeCommand: Command { public init?(command: String, args: [JSON]) { return nil } open class func fromName(_ command: String, args: [JSON]) -> Command? { return WipeCommand(command: command, args: args) } open func run(_ synchronizer: ClientsSynchronizer) -> Success { return succeed() } open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? { let json = JSON(parseJSON: syncCommand.value) if let name = json["command"].string, let args = json["args"].array { return WipeCommand.fromName(name, args: args) } return nil } } open class DisplayURICommand: Command { let uri: URL let title: String let sender: String public init?(command: String, args: [JSON]) { if let uri = args[0].string?.asURL, let sender = args[1].string, let title = args[2].string { self.uri = uri self.sender = sender self.title = title } else { // Oh, Swift. self.uri = "http://localhost/".asURL! self.title = "" return nil } } open class func fromName(_ command: String, args: [JSON]) -> Command? { return DisplayURICommand(command: command, args: args) } open func run(_ synchronizer: ClientsSynchronizer) -> Success { func display(_ deviceName: String? = nil) -> Success { synchronizer.delegate.displaySentTab(for: uri, title: title, from: deviceName) return succeed() } guard let getClientWithId = synchronizer.localClients?.getClientWithId(sender) else { return display() } return getClientWithId >>== { client in return display(client?.name) } } open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? { let json = JSON(parseJSON: syncCommand.value) if let name = json["command"].string, let args = json["args"].array { return DisplayURICommand.fromName(name, args: args) } return nil } } open class RepairResponseCommand: Command { let repairResponse: RepairResponse public init(command: String, args: [JSON]) { self.repairResponse = RepairResponse.fromJSON(args: args[0]) } open class func fromName(_ command: String, args: [JSON]) -> Command? { return RepairResponseCommand(command: command, args: args) } open func run(_ synchronizer: ClientsSynchronizer) -> Success { let repairer = BookmarksRepairRequestor(scratchpad: synchronizer.scratchpad, basePrefs: synchronizer.basePrefs, remoteClients: synchronizer.localClients!) return repairer.continueRepairs(response: self.repairResponse) >>> succeed } open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? { let json = JSON(parseJSON: syncCommand.value) if let name = json["command"].string, let args = json["args"].array { return RepairResponseCommand.fromName(name, args: args) } return nil } } let Commands: [String: (String, [JSON]) -> Command?] = [ "wipeAll": WipeCommand.fromName, "wipeEngine": WipeCommand.fromName, // resetEngine // resetAll // logout "displayURI": DisplayURICommand.fromName, "repairResponse": RepairResponseCommand.fromName ] open class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "clients") } var localClients: RemoteClientsAndTabs? override var storageVersion: Int { return ClientsStorageVersion } var clientRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastClientUpload") } get { return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0 } } // Sync Object Format (Version 1) for Form Factors: http://docs.services.mozilla.com/sync/objectformats.html#id2 fileprivate enum SyncFormFactorFormat: String { case phone = "phone" case tablet = "tablet" } open func getOurClientRecord() -> Record<ClientPayload> { let guid = self.scratchpad.clientGUID let formfactor = formFactorString() let json = JSON(object: [ "id": guid, "fxaDeviceId": self.scratchpad.fxaDeviceId, "version": AppInfo.appVersion, "protocols": ["1.5"], "name": self.scratchpad.clientName, "os": "iOS", "commands": [JSON](), "type": "mobile", "appPackage": Bundle.main.bundleIdentifier ?? "org.mozilla.ios.FennecUnknown", "application": DeviceInfo.appName(), "device": DeviceInfo.deviceModel(), "formfactor": formfactor]) let payload = ClientPayload(json) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } fileprivate func formFactorString() -> String { let userInterfaceIdiom = UIDevice.current.userInterfaceIdiom var formfactor: String switch userInterfaceIdiom { case .phone: formfactor = SyncFormFactorFormat.phone.rawValue case .pad: formfactor = SyncFormFactorFormat.tablet.rawValue default: formfactor = SyncFormFactorFormat.phone.rawValue } return formfactor } fileprivate func clientRecordToLocalClientEntry(_ record: Record<ClientPayload>) -> RemoteClient { let modified = record.modified let payload = record.payload return RemoteClient(json: payload.json, modified: modified) } // If this is a fresh start, do a wipe. // N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!) // N.B., but perhaps we should discard outgoing wipe/reset commands! fileprivate func wipeIfNecessary(_ localClients: RemoteClientsAndTabs) -> Success { if self.lastFetched == 0 { return localClients.wipeClients() } return succeed() } /** * Returns whether any commands were found (and thus a replacement record * needs to be uploaded). Also returns the commands: we run them after we * upload a replacement record. */ fileprivate func processCommandsFromRecord(_ record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> { log.debug("Processing commands from downloaded record.") // TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead. if let record = record { let commands = record.payload.commands if !commands.isEmpty { func parse(_ json: JSON) -> Command? { if let name = json["command"].string, let args = json["args"].array, let constructor = Commands[name] { return constructor(name, args) } return nil } // TODO: can we do anything better if a command fails? return deferMaybe((true, optFilter(commands.map(parse)))) } } return deferMaybe((false, [])) } fileprivate func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { return localClients.getCommands() >>== { clientCommands in return clientCommands.map { (clientGUID, commands) -> Success in self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient) }.allSucceed() } } fileprivate func syncClientCommands(_ clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let deleteCommands: () -> Success = { return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() }) } log.debug("Fetching current client record for client \(clientGUID).") let fetch = storageClient.get(clientGUID) return fetch.bind() { result in if let response = result.successValue, response.value.payload.isValid() { let record = response.value if var clientRecord = record.payload.json.dictionary { clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON(parseJSON: $0.value) }) let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds) return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified) >>== { resp in log.debug("Client \(clientGUID) commands upload succeeded.") // Always succeed, even if we couldn't delete the commands. return deleteCommands() } } } else { if let failure = result.failureValue { log.warning("Failed to fetch record with GUID \(clientGUID).") if failure is NotFound<HTTPURLResponse> { log.debug("Not waiting to see if the client comes back.") // TODO: keep these around and retry, expiring after a while. // For now we just throw them away so we don't fail every time. return deleteCommands() } if failure is BadRequestError<HTTPURLResponse> { log.debug("We made a bad request. Throwing away queued commands.") return deleteCommands() } } } log.error("Client \(clientGUID) commands upload failed: No remote client for GUID") return deferMaybe(UnknownError()) } } /** * Upload our record if either (a) we know we should upload, or (b) * our own notes tell us we're due to reupload. */ fileprivate func maybeUploadOurRecord(_ should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let lastUpload = self.clientRecordLastUpload let expired = lastUpload < (Date.now() - (2 * OneDayInMilliseconds)) log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).") if !should && !expired { return succeed() } let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload) var uploadStats = SyncUploadStats() return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Client record upload succeeded. New timestamp: \(ts).") self.clientRecordLastUpload = ts uploadStats.sent += 1 } else { uploadStats.sentFailed += 1 } self.statsSession.recordUpload(stats: uploadStats) return succeed() } } fileprivate func applyStorageResponse(_ response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { log.debug("Applying clients response.") var downloadStats = SyncDownloadStats() let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) client records.") let ourGUID = self.scratchpad.clientGUID var toInsert = [RemoteClient]() var ours: Record<ClientPayload>? = nil for (rec) in records { guard rec.payload.isValid() else { log.warning("Client record \(rec.id) is invalid. Skipping.") continue } if rec.id == ourGUID { if rec.modified == self.clientRecordLastUpload { log.debug("Skipping our own unmodified record.") } else { log.debug("Saw our own record in response.") ours = rec } } else { toInsert.append(self.clientRecordToLocalClientEntry(rec)) } } downloadStats.applied += toInsert.count // Apply remote changes. // Collect commands from our own record and reupload if necessary. // Then run the commands and return. return localClients.insertOrUpdateClients(toInsert) >>== { succeeded in downloadStats.succeeded += succeeded downloadStats.failed += (toInsert.count - succeeded) self.statsSession.recordDownload(stats: downloadStats) return succeed() } >>== { self.processCommandsFromRecord(ours, withServer: storageClient) } >>== { (shouldUpload, commands) in return self.maybeUploadOurRecord(shouldUpload, ifUnmodifiedSince: ours?.modified, toServer: storageClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) } >>> { log.debug("Running \(commands.count) commands.") for command in commands { _ = command.run(self) } self.lastFetched = responseTimestamp! return succeed() } } } open func synchronizeLocalClients(_ localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { log.debug("Synchronizing clients.") self.localClients = localClients // Store for later when we process a repairResponse command if let reason = self.reasonToNotSync(storageClient) { switch reason { case .engineRemotelyNotEnabled: // This is a hard error for us. return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?")) default: return deferMaybe(SyncStatus.notStarted(reason)) } } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0.json }) let encrypter = keys?.encrypter(self.collection, encoder: encoder) if encrypter == nil { log.error("Couldn't make clients encrypter.") return deferMaybe(FatalError(message: "Couldn't make clients encrypter.")) } let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!) if !self.remoteHasChanges(info) { log.debug("No remote changes for clients. (Last fetched \(self.lastFetched).)") statsSession.start() return self.maybeUploadOurRecord(false, ifUnmodifiedSince: nil, toServer: clientsClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: clientsClient) } >>> { deferMaybe(self.completedWithStats) } } // TODO: some of the commands we process might involve wiping collections or the // entire profile. We should model this as an explicit status, and return it here // instead of .completed. statsSession.start() return clientsClient.getSince(self.lastFetched) >>== { response in return self.wipeIfNecessary(localClients) >>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) } } >>> { deferMaybe(self.completedWithStats) } } }
mpl-2.0
b64d47d690234c00d5230bec5fc677c9
39.545244
224
0.608469
5.319635
false
false
false
false
Hejki/SwiftExtLib
src/SegueHandler.swift
1
4023
// // HejkiSwiftCore // // Copyright (c) 2015-2016 Hejki // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if os(iOS) import UIKit #else import Cocoa #endif /** Type safe segue handling. Start with define `SegueIdentifier`s in your `UIViewController` or `NSViewController`. ```swift class MyViewController: UIViewController, SegueHandler { enum SegueIdentifier: String { case ShowImportUnicorn = "ShowImportUnicorn" case ShowEditUnicorn = "ShowEditUnicorn" } } ``` - Use function `performSegue(withIdentifier:sender:)` for performs the specific segue. - Use function `segueIdentifier(for:)` for obtain `SegueIdentifier` for prepareForSegue method or other view controller methods. */ public protocol SegueHandler { associatedtype SegueIdentifier: RawRepresentable } #if os(iOS) public extension SegueHandler where Self: UIViewController, SegueIdentifier.RawValue == String { /** Performs the specified segue. - parameter identifier: defined segue identifier - parameter sender: The object that you want to use to initiate the segue. This parameter makes the object available to your implementation during the segue. Default value is nil */ public func performSegue(withIdentifier identifier: SegueIdentifier, sender: Any? = nil) { performSegue(withIdentifier: identifier.rawValue, sender: sender) } /** Create segue identifier from storyboard segue instance. - parameter segue: storyboard segue */ public func segueIdentifier(for segue: UIStoryboardSegue) throws -> SegueIdentifier { guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { throw HSCAppError.invalidSegueIdentifier(identifier: segue.identifier) } return segueIdentifier } } //#else //public extension SegueHandler where Self: NSSeguePerforming, SegueIdentifier.RawValue == String { // // /** // Performs the specified segue. // // - parameter identifier: defined segue identifier // - parameter sender: The object that you want to use to initiate the segue. This parameter makes the object available to your implementation during the segue. Default value is nil // */ // @available(OSX 10.10, *) // public func performSegue(withIdentifier identifier: SegueIdentifier, sender: Any? = nil) { // performSegue?(withIdentifier: NSStoryboardSegue.Identifier(rawValue: identifier.rawValue), sender: sender) // } // // @available(OSX 10.10, *) // public func segueIdentifier(for segue: NSStoryboardSegue) throws -> SegueIdentifier { // guard let identifier = segue.identifier, // let segueIdentifier = SegueIdentifier(rawValue: identifier) else { // throw HSCAppError.invalidSegueIdentifier(identifier: segue.identifier.map { $0.rawValue }) // } // // return segueIdentifier // } //} #endif
mit
a190fc2e8407af4ad03d37411adfa193
38.441176
185
0.718618
4.817964
false
false
false
false
yoonapps/QPXExpressWrapper
QPXExpressWrapper/Classes/TripOptionSlice.swift
1
779
// // TripOptionSlice.swift // Flights // // Created by Kyle Yoon on 2/14/16. // Copyright © 2016 Kyle Yoon. All rights reserved. // import Foundation import Gloss public struct TripOptionSlice: Decodable { public let kind: String public let duration: Int? public let segment: [TripOptionSliceSegment]? public init?(json: JSON) { guard let kind: String = "kind" <~~ json else { return nil } self.kind = kind self.duration = "duration" <~~ json if let jsonSegment = json["segment"] as? [JSON], let segment = [TripOptionSliceSegment].from(jsonArray: jsonSegment) { self.segment = segment } else { self.segment = nil } } }
mit
d92a2be06d27589bf7ab36d8502fea08
21.882353
81
0.57455
4.094737
false
false
false
false
raysarebest/Hello
Hello/MHPhraseViewController.swift
1
1444
// // MHPhraseViewController.swift // Hello // // Created by Michael Hulet on 11/25/15. // Copyright © 2015 Michael Hulet. All rights reserved. // import UIKit //MARK: - Phrase View Controller ///View controller to display phrases onscreen class MHPhraseViewController: UIViewController{ //MARK: View Controller Lifecycle override func viewDidLoad() -> Void{ super.viewDidLoad() let presentationMethod: Selector = "presentSelectionViewController" let pull = UIScreenEdgePanGestureRecognizer(target: self, action: presentationMethod) pull.edges = .Bottom view.addGestureRecognizer(pull) let swipe = UISwipeGestureRecognizer(target: self, action: presentationMethod) swipe.direction = .Up view.addGestureRecognizer(swipe) view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: presentationMethod)) } //MARK: Transition Handling ///Presents the selection view func presentSelectionViewController() -> Void{ presentViewController(UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("Selection"), animated: true, completion: nil) } //MARK: System UI Delegation override func prefersStatusBarHidden() -> Bool{ return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask{ return .Landscape } }
mit
01f8142551a8c4a9488b5bc78d05b5d9
30.391304
174
0.717949
5.344444
false
false
false
false
forgo/BabySync
bbsync/mobile/iOS/Baby Sync/Baby Sync/AuthUser.swift
1
2303
// // AuthUser.swift // SignInBase // // Created by Elliott Richerson on 10/25/15. // Copyright © 2015 Elliott Richerson. All rights reserved. // import Locksmith import UIKit struct AuthUser: CreateableSecureStorable, ReadableSecureStorable, DeleteableSecureStorable, GenericPasswordSecureStorable, CustomStringConvertible { var userId: String var accessToken: String var name: String var email: String var pic: UIImage var jwt: String // Required by GenericPasswordSecureStorable var service: String var account: String { return email } // Required by CreateableSecureStorable var data: [String: Any] { return [ "userId": userId as AnyObject, "accessToken": accessToken as AnyObject, "name": name as AnyObject, "email": email as AnyObject, "pic": pic, "jwt": jwt as AnyObject ] } init() { self.service = AuthConstant.Default.AuthMethod.rawValue self.userId = "" self.accessToken = "" self.name = "" self.email = "" self.pic = AuthConstant.Default.ProfilePic self.jwt = "" } init(service: AuthMethodType, userId: String, accessToken: String, name: String, email: String, pic: UIImage, jwt: String) { self.service = service.rawValue self.userId = userId self.accessToken = accessToken self.name = name self.email = email self.pic = pic self.jwt = jwt } var description: String { let tokenAbbreviation: String = self.accessToken.substring(with: (self.accessToken.startIndex ..< self.accessToken.characters.index(self.accessToken.startIndex, offsetBy: min(self.accessToken.characters.count, 10)))) + "..." let jwtAbbreviation: String = self.jwt.substring(with: (self.jwt.startIndex ..< self.jwt.characters.index(self.jwt.startIndex, offsetBy: min(self.jwt.characters.count, 10)))) + "..." return "AuthUser(\n\tservice: \(self.service)\n\tuserId: \(self.userId)\n\taccessToken: \(tokenAbbreviation)\n\tname: \(self.name)\n\temail: \(self.email)\n\tpic: \(self.pic)\n\tjwt: \(jwtAbbreviation)\n)" } }
mit
50fc913b14c1cd2ba67bbb283c1e9a3d
33.358209
232
0.621199
4.302804
false
false
false
false
pj4533/wat
wat/Models/FrameControl.swift
1
1972
// // FrameControl.swift // wat // // Created by PJ Gray on 8/15/14. // Copyright (c) 2014 Say Goodnight Software. All rights reserved. // import Cocoa class FrameControl: RawData { let frameControlBytes: Int16 enum FrameControlType { case Management, Control, Data, Reserved, Unknown func simpleDescription() -> String { switch self { case .Management: return "MGMT" case .Control: return "CTRL" case .Data: return "DATA" case .Reserved: return "Reserved" case .Unknown: return "Unknown" } } } let frameControlType: FrameControlType enum FrameControlSubType { case Authentication, Unknown func simpleDescription() -> String { switch self { case .Authentication: return "AUTH" case .Unknown: return "Unknown" } } } let frameControlSubType: FrameControlSubType override init(rawData: NSData) { self.frameControlBytes = 0 self.frameControlType = .Unknown self.frameControlSubType = .Unknown super.init(rawData: rawData) self.frameControlBytes = self.read(0) as Int16 switch (((self.frameControlBytes) >> 2) & 0x3) { case 0x0: self.frameControlType = .Management case 0x1: self.frameControlType = .Control case 0x2: self.frameControlType = .Data case 0x3: self.frameControlType = .Reserved default: self.frameControlType = .Unknown } switch (((self.frameControlBytes) >> 4) & 0xF) { case 0xB: self.frameControlSubType = .Authentication default: self.frameControlSubType = .Unknown } } }
mit
c40817d7b0d95a1d9cf34062f4558f02
24.282051
67
0.534483
4.821516
false
false
false
false
miktap/pepe-p06
PePeP06/PePeP06Tests/Mocks/MockTasoClient.swift
1
3408
// // MockTasoClient.swift // PePeP06Tests // // Created by Mikko Tapaninen on 28/12/2017. // import Foundation import PromiseKit @testable import PePeP06 class MockTasoClient: TasoClientProtocol { var delegate: TasoClientDelegate? var team_id: String? var competition_id: String? var category_id: String? var current: String? var season_id: String? var organiser: String? var region: String? var all_current: String? var club_id: String? var player_id: String? var group_id: String? var matches: String? var rejectPromise = false var webResponse: WebResponse? func initialize() {} func getTeam(team_id: String, competition_id: String?, category_id: String?) -> Promise<WebResponse>? { self.team_id = team_id self.competition_id = competition_id self.category_id = category_id return Promise {fulfill, reject in if rejectPromise { reject(NSError(domain: "dummy", code: 0, userInfo: nil)) } else { fulfill(webResponse!) } } } func getCompetitions(current: String?, season_id: String?, organiser: String?, region: String?) -> Promise<WebResponse>? { self.current = current self.season_id = season_id self.organiser = organiser self.region = region return Promise {fulfill, reject in if rejectPromise { reject(NSError(domain: "dummy", code: 0, userInfo: nil)) } else { fulfill(webResponse!) } } } func getCategories(competition_id: String?, category_id: String?, organiser: String?, all_current: String?) -> Promise<WebResponse>? { self.competition_id = competition_id self.category_id = category_id self.organiser = organiser self.all_current = all_current return Promise {fulfill, reject in if rejectPromise { reject(NSError(domain: "dummy", code: 0, userInfo: nil)) } else { fulfill(webResponse!) } } } func getClub(club_id: String?) -> Promise<WebResponse>? { self.club_id = club_id return Promise {fulfill, reject in if rejectPromise { reject(NSError(domain: "dummy", code: 0, userInfo: nil)) } else { fulfill(webResponse!) } } } func getPlayer(player_id: String) -> Promise<WebResponse>? { self.player_id = player_id return Promise {fulfill, reject in if rejectPromise { reject(NSError(domain: "dummy", code: 0, userInfo: nil)) } else { fulfill(webResponse!) } } } func getGroup(competition_id: String, category_id: String, group_id: String, matches: String?) -> Promise<WebResponse>? { self.competition_id = competition_id self.category_id = category_id self.group_id = group_id self.matches = matches return Promise {fulfill, reject in if rejectPromise { reject(NSError(domain: "dummy", code: 0, userInfo: nil)) } else { fulfill(webResponse!) } } } }
mit
738d8224bd57ff4e608d8fc846e95862
28.634783
138
0.556045
4.380463
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/KYC/Client/VeriffCredentials.swift
1
1210
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation /// Model describing credentials for interacting with the Veriff API public struct VeriffCredentials: Codable { public let applicantId: String public let key: String public let url: String private enum CodingKeys: String, CodingKey { case applicantId case key = "token" case data case url } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let nested = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .data) applicantId = try values.decode(String.self, forKey: .applicantId) key = try values.decode(String.self, forKey: .key) url = try nested.decode(String.self, forKey: .url) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data) try container.encode(applicantId, forKey: .applicantId) try container.encode(key, forKey: .key) try nested.encode(url, forKey: .url) } }
lgpl-3.0
08fce9f07d2ebe069a9066fdf2fd331a
34.558824
88
0.681555
4.257042
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/ReaderTopicService+FollowedInterests.swift
1
4964
import Foundation // MARK: - ReaderFollowedInterestsService /// Protocol representing a service that retrieves the users followed interests/tags protocol ReaderFollowedInterestsService: AnyObject { /// Fetches the users locally followed interests /// - Parameter completion: Called after a fetch, will return nil if the user has no interests or an error occurred func fetchFollowedInterestsLocally(completion: @escaping ([ReaderTagTopic]?) -> Void) /// Fetches the users followed interests from the network, then returns the sync'd interests /// - Parameter completion: Called after a fetch, will return nil if the user has no interests or an error occurred func fetchFollowedInterestsRemotely(completion: @escaping ([ReaderTagTopic]?) -> Void) /// Follow the provided interests /// If the user is not logged into a WP.com account, the interests will only be saved locally. func followInterests(_ interests: [RemoteReaderInterest], success: @escaping ([ReaderTagTopic]?) -> Void, failure: @escaping (Error) -> Void, isLoggedIn: Bool) /// Returns the API path of a given slug func path(slug: String) -> String } // MARK: - CoreData Fetching extension ReaderTopicService: ReaderFollowedInterestsService { public func fetchFollowedInterestsLocally(completion: @escaping ([ReaderTagTopic]?) -> Void) { completion(followedInterests()) } public func fetchFollowedInterestsRemotely(completion: @escaping ([ReaderTagTopic]?) -> Void) { fetchReaderMenu(success: { [weak self] in self?.fetchFollowedInterestsLocally(completion: completion) }) { [weak self] error in DDLogError("Could not fetch remotely followed interests: \(String(describing: error))") self?.fetchFollowedInterestsLocally(completion: completion) } } func followInterests(_ interests: [RemoteReaderInterest], success: @escaping ([ReaderTagTopic]?) -> Void, failure: @escaping (Error) -> Void, isLoggedIn: Bool) { // If the user is logged in, attempt to save the interests on the server // If the user is not logged in, save the interests locally if isLoggedIn { let slugs = interests.map { $0.slug } let topicService = ReaderTopicServiceRemote(wordPressComRestApi: apiRequest()) topicService.followInterests(withSlugs: slugs, success: { [weak self] in self?.fetchFollowedInterestsRemotely(completion: success) }) { error in failure(error) } } else { followInterestsLocally(interests, success: success, failure: failure) } } func path(slug: String) -> String { // We create a "remote" service to get an accurate path for the tag // https://public-api.../tags/_tag_/posts let service = ReaderTopicServiceRemote(wordPressComRestApi: apiRequest()) return service.pathForTopic(slug: slug) } private func followInterestsLocally(_ interests: [RemoteReaderInterest], success: @escaping ([ReaderTagTopic]?) -> Void, failure: @escaping (Error) -> Void) { interests.forEach { interest in let topic = ReaderTagTopic(remoteInterest: interest, context: managedObjectContext, isFollowing: true) topic.path = path(slug: interest.slug) } ContextManager.sharedInstance().save(managedObjectContext, withCompletionBlock: { [weak self] in self?.fetchFollowedInterestsLocally(completion: success) }) } private func apiRequest() -> WordPressComRestApi { let accountService = AccountService(managedObjectContext: managedObjectContext) let defaultAccount = accountService.defaultWordPressComAccount() let token: String? = defaultAccount?.authToken return WordPressComRestApi.defaultApi(oAuthToken: token, userAgent: WPUserAgent.wordPress()) } // MARK: - Private: Fetching Helpers private func followedInterestsFetchRequest() -> NSFetchRequest<ReaderTagTopic> { let entityName = "ReaderTagTopic" let predicate = NSPredicate(format: "following = YES AND showInMenu = YES") let fetchRequest = NSFetchRequest<ReaderTagTopic>(entityName: entityName) fetchRequest.predicate = predicate return fetchRequest } private func followedInterests() -> [ReaderTagTopic]? { let fetchRequest = followedInterestsFetchRequest() do { return try managedObjectContext.fetch(fetchRequest) } catch { DDLogError("Could not fetch followed interests: \(String(describing: error))") return nil } } }
gpl-2.0
bbe44344b360fd9e7e75d1bb1e3f9efb
42.929204
119
0.650081
5.571268
false
false
false
false
danielsaidi/iExtra
iExtra/UI/Extensions/UIImage/UIImage+Shadow.swift
1
1295
// // UIImage+Shadow.swift // iExtra // // Created by Daniel Saidi on 2016-03-15. // Copyright © 2016 Daniel Saidi. All rights reserved. // /* The UIView version of `addDropShadow` is slow if it is used on several views. This one is much faster, since it will create a copy of the image with a shadow added to it. However, note that you can not rotate such images much, since the shadow will be fixed. Use it for performance only. */ import UIKit public extension UIImage { func addDropShadow(withSize shadowSize: CGFloat, opacity: Float) -> UIImage? { let width = size.width + 2 * shadowSize let height = size.height + 2 * shadowSize let newSize = CGSize(width: width, height: height) let offset = CGSize(width: shadowSize, height: shadowSize) let color = UIColor(red: 0, green: 0, blue: 0, alpha: CGFloat(opacity)) UIGraphicsBeginImageContextWithOptions(newSize, false, scale) let context = UIGraphicsGetCurrentContext() context?.setShadow(offset: offset, blur: shadowSize, color: color.cgColor) draw(at: CGPoint(x: shadowSize, y: shadowSize)) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } }
mit
cb7196a00277924eb225c5d61107bb13
31.35
82
0.677743
4.371622
false
false
false
false
mikemilla/wordnerd-ios
wordnerd/Resources.swift
1
651
// // Resources.swift // smtfresh // // Created by Michael Miller on 11/26/15. // Copyright © 2015 Michael Miller. All rights reserved. // import UIKit struct Colors { static var redColor = UIColor(hex: 0xF44336) static var deepPurpleColor = UIColor(hex: 0x673AB7) static var blueColor = UIColor(hex: 0x118DF0) static var greenColor = UIColor(hex: 0x00C05F) static var greenDarkColor = UIColor(hex: 0x099C52) static var amberColor = UIColor(hex: 0xFFB007) static var greyLightColor = UIColor(hex: 0x616161) static var greyDarkColor = UIColor(hex: 0x424242) static var greyIconColor = UIColor(hex: 0x666666) }
gpl-3.0
4f1fcbb5dacd715201b840b0a482f8a8
30
57
0.718462
3.403141
false
false
false
false
noppoMan/Hexaville
Sources/HexavilleCore/SwiftBuilder/SwiftBuildEnvironmentProvider/DockerBuildEnvironmentProvider.swift
1
5771
// // DockerBuildEnvironmentProvider.swift // Hexaville // // Created by Yuki Takei on 2017/05/22. // // import Foundation enum DockerBuildEnvironmentProviderError: Error { case dockerIsNotFound case dockerBuildFailed case couldNotMakeSharedDir } extension DockerBuildEnvironmentProviderError: CustomStringConvertible { var description: String { switch self { case .dockerIsNotFound: return """ [DockerBuildEnvironmentProviderError] Could not find 'docker' in your machine. Please install docker. See Official installation guides with 'open https://docs.docker.com/engine/installation' """ case .dockerBuildFailed: return "[DockerBuildEnvironmentProviderError] docker build is failed with the above reason." case .couldNotMakeSharedDir: return "[DockerBuildEnvironmentProviderError] Could not make shared directory between Host machine and Docker. Please make sure permission of your working directory." } } } struct DockerBuildEnvironmentProvider: SwiftBuildEnvironmentProvider { var dockerExecutablePath: String { return ProcessInfo.processInfo.environment["DOCKER_PATH"] ?? "docker" } func build(config: HexavilleFile, hexavilleApplicationPath: String, executable: String) throws -> BuildResult { let tag = executable.lowercased() let sharedDir = "\(hexavilleApplicationPath)/__docker_shared" if let _ = ProcessInfo.processInfo.environment["DEBUG_SKIP_SWIFT_BUILD"] { return BuildResult(destination: sharedDir+"/\(config.swift.buildMode)", dockerTag: tag) } print("\nDocker version") let dockerVersionResult = Process.exec("docker", ["version"]) if dockerVersionResult.terminationStatus != 0 { throw DockerBuildEnvironmentProviderError.dockerIsNotFound } let templatePath = try Finder.findTemplatePath() let buildSwiftShellPath = try Finder.findScriptPath(for: "build-swift.sh") try String(contentsOfFile: buildSwiftShellPath, encoding: .utf8) .write(toFile: "\(hexavilleApplicationPath)/build-swift.sh", atomically: true, encoding: .utf8) let swiftVersion = config.swift.version let dest: String if swiftVersion.asCompareableVersion() > Version(major: 3, minor: 1) { dest = "/hexaville-app/.build/x86_64-unknown-linux" } else { dest = "/hexaville-app/.build" } try String(contentsOfFile: templatePath+"/Dockerfile", encoding: .utf8) .replacingOccurrences(of: "{{SWIFT_DOWNLOAD_URL}}", with: swiftVersion.downloadURLString) .replacingOccurrences(of: "{{SWIFTFILE}}", with: swiftVersion.fileName) .replacingOccurrences(of: "{{EXECUTABLE_NAME}}", with: executable) .replacingOccurrences(of: "{{DEST}}", with: dest) .write( toFile: hexavilleApplicationPath+"/Dockerfile", atomically: true, encoding: .utf8 ) try String(contentsOfFile: templatePath+"/.dockerignore", encoding: .utf8) .write( toFile: hexavilleApplicationPath+"/.dockerignore", atomically: true, encoding: .utf8 ) var opts = ["build", "-t", tag, "-f", "\(hexavilleApplicationPath)/Dockerfile", hexavilleApplicationPath] if let docker = config.docker, let nocache = docker.buildOptions.nocache, nocache { opts.insert("--no-cache", at: 1) } let buildResult = Process.exec(dockerExecutablePath, opts) if buildResult.terminationStatus != 0 { throw DockerBuildEnvironmentProviderError.dockerBuildFailed } let mkdirResult = Process.exec("mkdir", ["-p", sharedDir]) if mkdirResult.terminationStatus != 0 { throw DockerBuildEnvironmentProviderError.couldNotMakeSharedDir } #if os(OSX) let dockerRunOpts = [ "-e", "BUILD_CONFIGURATION=\(config.swift.buildMode)", "-v", "\(sharedDir):\(dest)", "-it", tag ] #else guard let user = ProcessInfo.processInfo.environment["USER"] else { fatalError("$USER was not found in env") } let dockerRunOpts = [ "-e", "BUILD_CONFIGURATION=\(config.swift.buildMode)", "-e", "VOLUME_USER=\(user)", "-e", "VOLUME_GROUP=\(user)", "-v", "\(sharedDir):\(dest)", "-it", tag ] #endif do { try self.spawnDocker(dockerRunOpts) } catch SpawnError.terminatedWithStatus(let errorCode) { switch errorCode { case 256: // retry swift build when get the rename error from CNIOBoringSSL try self.spawnDocker(dockerRunOpts) default: throw SpawnError.terminatedWithStatus(errorCode) } } catch { throw error } return BuildResult(destination: sharedDir+"/\(config.swift.buildMode)", dockerTag: tag) } private func spawnDocker(_ dockerRunOpts: [String]) throws { _ = try Spawn(args: ["/usr/bin/env", "docker", "run"] + dockerRunOpts) { print($0, separator: "", terminator: "") } } }
mit
01033d84eb5d97f8bd37d5f1400f2366
36.232258
178
0.579796
4.957904
false
true
false
false
cheyongzi/MGTV-Swift
MGTV-Swift/Share/Extension/UIViewController+Extension.swift
1
2796
// // UIViewController+Extension.swift // MGTV-Swift // // Created by Che Yongzi on 16/10/17. // Copyright © 2016年 Che Yongzi. All rights reserved. // import UIKit extension UIViewController { func barItem(_ imageName: String, frame: CGRect) -> UIBarButtonItem { let imageView = UIImageView.init(frame: frame) imageView.image = UIImage(named: imageName) let barItem = UIBarButtonItem(customView: imageView) return barItem } func barItem(imageName: String, frame: CGRect, selector: Selector?) -> UIBarButtonItem { let button = UIButton(type: .custom) button.frame = frame button.setImage(UIImage(named: imageName), for: .normal) if let sel = selector { button.addTarget(self, action: sel, for: .touchUpInside) } let item = UIBarButtonItem(customView: button) return item } func barItem(title: String, frame: CGRect, selector: Selector?) -> UIBarButtonItem { let button = UIButton(type: .custom) button.frame = frame button.setAttributedTitle(NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 15)]), for: .normal) if let sel = selector { button.addTarget(self, action: sel, for: .touchUpInside) } let item = UIBarButtonItem(customView: button) return item } func barItem(_ width: CGFloat) -> UIBarButtonItem { let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) space.width = width return space } } extension UIViewController { static func visibleController(_ viewController: UIViewController) -> UIViewController { if let controller = viewController.presentedViewController { return UIViewController.visibleController(controller) } else if let navController = viewController as? UINavigationController { guard navController.viewControllers.count > 0 else { return viewController } return UIViewController.visibleController(navController.topViewController!) } else if let tabBarController = viewController as? UITabBarController { guard (tabBarController.viewControllers?.count)! > 0 else { return viewController } return UIViewController.visibleController(tabBarController.selectedViewController!) }else { return viewController } } static func currentController() -> UIViewController { let viewController = BaseTabBarController.mainController return UIViewController.visibleController(viewController) } }
mit
e9e100c99721ef172286704391ff3c6d
37.791667
197
0.66416
5.465753
false
false
false
false
SergeMaslyakov/audio-player
app/src/controllers/music/ArtistsViewController.swift
1
3213
// // ArtistsViewController.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import MediaPlayer import Reusable import DipUI import TableKit class ArtistsViewController: UIViewController, StoryboardSceneBased, MusicPickerCoordinatable { static let sceneStoryboard = UIStoryboard(name: StoryboardScenes.musicLib.rawValue, bundle: nil) var dataService: AppleMusicArtistsDataService? var data: [(Int, MPMediaItemCollection)] = [] var tableDirector: TableDirector! var refreshControl: UIRefreshControl! @IBOutlet weak var stubDataView: StubDataView! { didSet { stubDataView.retryDelegate = self } } @IBOutlet weak var tableView: UITableView! { didSet { tableDirector = TableDirector(tableView: tableView) refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged) if #available(iOS 10.0, *) { tableView.refreshControl = refreshControl } else { tableView.addSubview(refreshControl) } tableView.alpha = 0 } } override func viewDidLoad() { super.viewDidLoad() let titleView = self.navigationItem.titleView as? MusicPickerTitleView titleView?.delegate = musicCoordinator installTable() refresh(manual: false) } func installTable() { let section = TableSection() section.headerTitle = "COLLECTION".localized(withFile: .music) section.footerHeight = ThemeHeightHelper.Artists.sectionFooterHeight section.headerHeight = ThemeHeightHelper.Artists.sectionHeaderHeight tableDirector += section } func refresh(manual: Bool) { if manual { stubDataView?.dataLoading() } dataService?.loadAsync(with: { [weak self] (artists: [(albums: Int, songs: MPMediaItemCollection)]) in guard let strongSelf = self else { return } strongSelf.data = artists strongSelf.refreshTable() strongSelf.refreshControl.endRefreshing() if artists.count > 0 { strongSelf.stubDataView?.dataWasLoaded() } else { let error = "NO_ARTISTS_IN_THE_LIBRARY".localized(withFile: .music) strongSelf.stubDataView?.dataNotLoaded(errorMessage: error) } }) } func refreshTable() { let section = tableDirector.sections[0] section.clear() for artist in data { let row = TableRow<MusicArtistTableViewCell>(item: artist) .on(.click) { options in self.tableDirector.tableView?.deselectRow(at: options.indexPath, animated: true) } section += row } tableDirector.reload() } } // // MARK: Retry delegate // extension ArtistsViewController: StubDataRetryProtocol { func userRequestRetry(from stubView: StubDataView) { refresh(manual: true) } }
apache-2.0
1ec31b3e324f2215d21d5cf16d9117ad
25.766667
110
0.620174
5.106518
false
false
false
false
realDogbert/myScore
myScore/Match.swift
1
947
// // Match.swift // myScore // // Created by von Eitzen Frank on 24.07.14. // Copyright (c) 2014 Frank von Eitzen. All rights reserved. // class Match { var course:Course! var average:Int init(course:Course) { self.course = course self.average = 0 for hole in course.holes { self.average += hole.average } } func getTotalScore() -> Int { var total = 0 for hole in course.holes { total = total + hole.score.strokes } return total } func getCalculatedAverage() -> Int { var calcAverage = 0 for hole in course.holes { calcAverage += hole.getAverageDiff() } if calcAverage > 0 { return 1 } else if calcAverage < 0 { return -1 } else { return 0 } } }
mit
16b93b7ca30ceebdb74ca4d9a3416852
17.94
61
0.476241
4.344037
false
false
false
false
alexhillc/AXPhotoViewer
Source/Extensions/AXPhotoProtocol+Internal.swift
1
1993
// // AXPhoto+Internal.swift // AXPhotoViewer // // Created by Alex Hill on 5/27/17. // Copyright © 2017 Alex Hill. All rights reserved. // #if os(iOS) import FLAnimatedImage.FLAnimatedImage #elseif os(tvOS) import FLAnimatedImage_tvOS.FLAnimatedImage #endif enum AXPhotoLoadingState { case notLoaded, loading, loaded, loadingCancelled, loadingFailed } fileprivate struct AssociationKeys { static var error: UInt8 = 0 static var progress: UInt8 = 0 static var loadingState: UInt8 = 0 static var animatedImage: UInt8 = 0 } // MARK: - Internal AXPhotoProtocol extension to be used by the framework. extension AXPhotoProtocol { var ax_progress: CGFloat { get { return objc_getAssociatedObject(self, &AssociationKeys.progress) as? CGFloat ?? 0 } set(value) { objc_setAssociatedObject(self, &AssociationKeys.progress, value, .OBJC_ASSOCIATION_RETAIN) } } var ax_error: Error? { get { return objc_getAssociatedObject(self, &AssociationKeys.error) as? Error } set(value) { objc_setAssociatedObject(self, &AssociationKeys.error, value, .OBJC_ASSOCIATION_RETAIN) } } var ax_loadingState: AXPhotoLoadingState { get { return objc_getAssociatedObject(self, &AssociationKeys.loadingState) as? AXPhotoLoadingState ?? .notLoaded } set(value) { objc_setAssociatedObject(self, &AssociationKeys.loadingState, value, .OBJC_ASSOCIATION_RETAIN) } } var ax_animatedImage: FLAnimatedImage? { get { return objc_getAssociatedObject(self, &AssociationKeys.animatedImage) as? FLAnimatedImage } set(value) { objc_setAssociatedObject(self, &AssociationKeys.animatedImage, value, .OBJC_ASSOCIATION_RETAIN) } } var ax_isReducible: Bool { get { return self.url != nil } } }
mit
b2b8f39fbcc846ed95bcce8f86d8d1fa
27.056338
118
0.640562
4.368421
false
false
false
false
zhxnlai/AsyncTask
Source/Base/Collection.swift
1
5049
// // Wait.swift // Pods // // Created by Zhixuan Lai on 5/27/16. // // import Foundation extension SequenceType where Generator.Element : ThrowableTaskType { public func awaitFirstResult(queue: DispatchQueue = DefaultQueue) -> Result<Generator.Element.ReturnType> { let tasks = map{$0} return Task {(callback: Result<Generator.Element.ReturnType> -> ()) in tasks.concurrentForEach(queue, transform: {task in task.awaitResult()}) { index, result in callback(result) } }.await(queue) } public func awaitAllResults(queue: DispatchQueue = DefaultQueue, concurrency: Int = DefaultConcurrency) -> [Result<Generator.Element.ReturnType>] { let tasks = map{$0} return tasks.concurrentMap(queue, concurrency: concurrency) {task in task.awaitResult()} } public func awaitFirst(queue: DispatchQueue = DefaultQueue) throws -> Generator.Element.ReturnType { return try awaitFirstResult(queue).extract() } public func awaitAll(queue: DispatchQueue = DefaultQueue, concurrency: Int = DefaultConcurrency) throws -> [Generator.Element.ReturnType] { return try awaitAllResults(queue, concurrency: concurrency).map {try $0.extract()} } } extension Dictionary where Value : ThrowableTaskType { public func awaitFirst(queue: DispatchQueue = DefaultQueue) throws -> Value.ReturnType { return try values.awaitFirst(queue) } public func awaitAll(queue: DispatchQueue = DefaultQueue, concurrency: Int = DefaultConcurrency) throws -> [Key: Value.ReturnType] { let elements = Array(zip(Array(keys), try values.awaitAll(queue, concurrency: concurrency))) return Dictionary<Key, Value.ReturnType>(elements: elements) } } extension SequenceType where Generator.Element : TaskType { var throwableTasks: [ThrowableTask<Generator.Element.ReturnType>] { return map {$0.throwableTask} } public func awaitFirst(queue: DispatchQueue = DefaultQueue) -> Generator.Element.ReturnType { return try! throwableTasks.awaitFirstResult(queue).extract() } public func awaitAll(queue: DispatchQueue = DefaultQueue, concurrency: Int = DefaultConcurrency) -> [Generator.Element.ReturnType] { return throwableTasks.awaitAllResults(queue, concurrency: concurrency).map {result in try! result.extract() } } } extension Dictionary where Value : TaskType { var throwableTasks: [ThrowableTask<Value.ReturnType>] { return values.throwableTasks } public func awaitFirst(queue: DispatchQueue = DefaultQueue) -> Value.ReturnType { return try! throwableTasks.awaitFirstResult(queue).extract() } public func await(queue: DispatchQueue = DefaultQueue, concurrency: Int = DefaultConcurrency) -> [Key: Value.ReturnType] { let elements = Array(zip(Array(keys), try! throwableTasks.awaitAll(queue, concurrency: concurrency))) return Dictionary<Key, Value.ReturnType>(elements: elements) } } extension Dictionary { init(elements: [(Key, Value)]) { self.init() for (key, value) in elements { updateValue(value, forKey: key) } } } extension Array { func concurrentForEach<U>(queue: DispatchQueue, transform: Element -> U, completion: (Int, U) -> ()) { let fd_sema = dispatch_semaphore_create(0) var numberOfCompletedTasks = 0 let numberOfTasks = count for (index, item) in enumerate() { dispatch_async(queue.get()) { let result = transform(item) dispatch_sync(DispatchQueue.getCollectionQueue().get()) { completion(index, result) numberOfCompletedTasks += 1 if numberOfCompletedTasks == numberOfTasks { dispatch_semaphore_signal(fd_sema) } } } } dispatch_semaphore_wait(fd_sema, dispatch_time_t(timeInterval: -1)) } func concurrentMap<U>(queue: DispatchQueue, concurrency: Int, transform: Element -> U) -> [U] { let fd_sema = dispatch_semaphore_create(0) let fd_sema2 = dispatch_semaphore_create(concurrency) var results = [U?](count: count, repeatedValue: nil) var numberOfCompletedTasks = 0 let numberOfTasks = count dispatch_apply(count, queue.get()) {index in dispatch_semaphore_wait(fd_sema2, dispatch_time_t(timeInterval: -1)) let result = transform(self[index]) dispatch_sync(DispatchQueue.getCollectionQueue().get()) { results[index] = result numberOfCompletedTasks += 1 if numberOfCompletedTasks == numberOfTasks { dispatch_semaphore_signal(fd_sema) } dispatch_semaphore_signal(fd_sema2) } } dispatch_semaphore_wait(fd_sema, dispatch_time_t(timeInterval: -1)) return results.flatMap {$0} } }
mit
36de8fb38c14c9962589b962383811fc
34.0625
151
0.646663
4.504014
false
false
false
false
rock-n-code/Kashmir
Kashmir/Shared/Features/Core Data/Protocols/CoreDataDecodable.swift
1
2288
// // CoreDataDecodable.swift // Kashmir // // Created by Javier Cicchelli on 06/01/2018. // Copyright © 2018 Rock & Code. All rights reserved. // import Foundation import CoreData public protocol CoreDataDecodable: Decodable { // MARK: Associated types associatedtype DTO: Decodable // MARK: Static static func makePredicate(from dto: DTO) -> NSPredicate? // MARK: Initializers init(dto: DTO, context: NSManagedObjectContext) throws // MARK: Functions func shouldUpdate(from dto: DTO) throws -> Bool func update(from dto: DTO) throws } // MARK: - public extension CoreDataDecodable { // MARK: Static static func makePredicate(from dto: DTO) -> NSPredicate? { return nil } // MARK: Initializers public init(from decoder: Decoder) throws { try self.init(dto: DTO(from: decoder), context: .decodingContext(at: decoder.codingPath)) } } // MARK: - public extension CoreDataDecodable where Self: NSManagedObject { // MARK: Static static func createNew(from dto: DTO, in context: NSManagedObjectContext) throws -> Self { return try self.init(dto: dto, context: context) } static func findFirst(from dto: DTO, in context: NSManagedObjectContext) throws -> Self? { guard let request = self.fetchRequest() as? NSFetchRequest<Self>, let predicate = self.makePredicate(from: dto) else { return nil } request.predicate = predicate request.fetchLimit = 1 request.resultType = .managedObjectResultType return try context.fetch(request).first } static func findOrCreate(from dto: DTO, in context: NSManagedObjectContext) throws -> Self { if let object = try findFirst(from: dto, in: context) { return object } else { return try createNew(from: dto, in: context) } } static func createOrUpdate(from dto: DTO, in context: NSManagedObjectContext) throws -> Self { if let object = try findFirst(from: dto, in: context) { try object.update(from: dto) return object } else { return try createNew(from: dto, in: context) } } // MARK: Initializers init(dto: DTO, context: NSManagedObjectContext) throws { self.init(context: context) try update(from: dto) } }
mit
a1be58619af336824d439d0bcec4afe2
18.547009
64
0.670748
3.712662
false
false
false
false
laxmankhanal/JCKRC
JCKRC/Controller/DemoTableViewController.swift
1
2290
// // DemoTableViewController.swift // JCKRC // // Created by Pro on 4/22/17. // Copyright © 2017 leapfrog-laxman. All rights reserved. // import UIKit class DemoTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.contentInset.top = 50 // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return Heading.all.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CellTableViewCell cell.label.text = Heading(rawValue: indexPath.row)?.title() return cell } enum Heading: Int { case selectSalon, newSalon, analysis, training, availaibility, book, logout static var all: [Heading] = [.selectSalon, .newSalon, .analysis, .training, .availaibility, .book, .logout] func title() -> String { switch self { case .selectSalon: return "SALON SELECT" case .newSalon: return "NEW SALON" case .analysis: return "ANALYSIS" case .training: return "BOOK A TRAINING" case .availaibility: return "VIEW AVAILAIBILITY" case .book: return "BOOK AN ORDER" case .logout: return "LOGOUT" } } } }
mit
d7114d5e9304e84da6e84eca31b43bf9
31.239437
121
0.68021
4.76875
false
false
false
false
One-self/ZhihuDaily
ZhihuDaily/ZhihuDaily/Classes/View/ZDNavigationController.swift
1
1761
// // ZDNavigationController.swift // ZhihuDaily // // Created by Oneselfly on 2017/5/13. // Copyright © 2017年 Oneself. All rights reserved. // class ZDNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() navigationBar.isHidden = true view.backgroundColor = UIColor.white addFullScreenReturnGes() NotificationCenter.default.addObserver(self, selector: #selector(popToHome), name: NSNotification.Name(rawValue: ZHShouldPopToHomeNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(pushTheme), name: NSNotification.Name(rawValue: ZHShouldPushThemeNotification), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func popToHome() { popToRootViewController(animated: true) } @objc private func pushTheme() { pushViewController(ZDThemeViewController(), animated: true) } } // MARK: - 全屏手势 extension ZDNavigationController: UIGestureRecognizerDelegate { fileprivate func addFullScreenReturnGes() { let target = interactivePopGestureRecognizer?.delegate let handler = NSSelectorFromString("handleNavigationTransition:") let fullScreenGes = UIPanGestureRecognizer(target: target, action: handler) fullScreenGes.delegate = self view.addGestureRecognizer(fullScreenGes) interactivePopGestureRecognizer?.isEnabled = false } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return childViewControllers.count == 1 ? false : true } }
mit
31d6589249c2d8209678592c9faa0820
30.818182
165
0.689714
5.451713
false
false
false
false
darrenclark/objc2swift
objc2swift/Clang/Cursor.swift
1
1747
struct Cursor { let raw: CXCursor let translationUnit: TranslationUnit init?(raw: CXCursor, translationUnit: TranslationUnit) { self.raw = raw self.translationUnit = translationUnit if clang_Cursor_isNull(raw) != 0 { return nil } } } //MARK: - Attributes extension Cursor { var kind: CursorKind { return CursorKind(rawValue: clang_getCursorKind(raw))! } var spelling: String { return clang_getCursorSpelling(raw).convertAndDispose() } //MARK: - var extent: CXSourceRange { return clang_getCursorExtent(raw) } //MARK: - var type: Type { return clang_getCursorType(raw) } var resultType: Type { return clang_getCursorResultType(raw) } } //MARK: - Traversal extension Cursor { func visitChildren(block: (cursor: Cursor, parent: Cursor) -> ChildVisitResult) { clang_visitChildrenWithBlock(raw) { rawCursor, rawParent in let cursor = Cursor(raw: rawCursor, translationUnit: self.translationUnit)! let parent = Cursor(raw: rawParent, translationUnit: self.translationUnit)! return block(cursor: cursor, parent: parent).rawValue } } var children: [Cursor] { var result = [Cursor]() visitChildren { child, _ in result.append(child) return .Continue } return result } func firstChild(kind kind: CursorKind) -> Cursor? { let children = self.children let index = children.indexOf { cursor in cursor.kind == kind } return index.map { index in children[index] } } } //MARK: Debugging extension Cursor: CustomDebugStringConvertible { var debugDescription: String { var retVal = "\(kind) - \(spelling)\n" for child in children { child.debugDescription.enumerateLines { line, _ in retVal += "\t\(line)\n" } } return retVal } }
mit
c5b44f196e8e5995518df4adb635d9e9
19.313953
82
0.692044
3.405458
false
false
false
false
SwiftKit/Reactant
Source/StaticMap/Collection+CLLocationCoordinate2D.swift
2
2541
// // Collection+CLLocationCoordinate2D.swift // Reactant // // Created by Filip Dolnik on 26.02.17. // Copyright © 2017 Brightify. All rights reserved. // import MapKit extension Collection where Iterator.Element == CLLocationCoordinate2D { public func centerCoordinate() -> CLLocationCoordinate2D { guard count > 1 else { return first ?? CLLocationCoordinate2D() } let vector = reduce(DoubleVector3()) { accumulator, coordinate in let latitude = degreesToRadians(coordinate.latitude) let longitude = degreesToRadians(coordinate.longitude) let vector = DoubleVector3( x: cos(latitude) * cos(longitude), y: cos(latitude) * sin(longitude), z: sin(latitude)) return accumulator + vector } / Double(count) let resultLongitude = atan2(vector.y, vector.x) let resultSquareRoot = sqrt(vector.x * vector.x + vector.y * vector.y) let resultLatitude = atan2(vector.z, resultSquareRoot) return CLLocationCoordinate2D( latitude: radiansToDegrees(resultLatitude), longitude: radiansToDegrees(resultLongitude)) } public func coordinateSpan() -> MKCoordinateSpan { var minLatitude: Double = 90 var maxLatitude: Double = -90 var minLongitude: Double = 180 var maxLongitude: Double = -180 for coordinates in self { minLatitude = Swift.min(minLatitude, coordinates.latitude) maxLatitude = Swift.max(maxLatitude, coordinates.latitude) minLongitude = Swift.min(minLongitude, coordinates.longitude) maxLongitude = Swift.max(maxLongitude, coordinates.longitude) } return MKCoordinateSpan(latitudeDelta: maxLatitude - minLatitude, longitudeDelta: maxLongitude - minLongitude) } func boundingCoordinateRegion() -> MKCoordinateRegion { return MKCoordinateRegion(center: centerCoordinate(), span: coordinateSpan()) } } fileprivate struct DoubleVector3 { var x: Double = 0 var y: Double = 0 var z: Double = 0 } fileprivate func + (lhs: DoubleVector3, rhs: DoubleVector3) -> DoubleVector3 { return DoubleVector3( x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z) } fileprivate func / (lhs: DoubleVector3, rhs: Double) -> DoubleVector3 { return DoubleVector3( x: lhs.x / rhs, y: lhs.y / rhs, z: lhs.z / rhs) }
mit
2b8c79104c12e4c5140ce6ead9636e55
32.866667
118
0.631102
4.519573
false
false
false
false
dhf/SwiftForms
SwiftForms/cells/FormStepperCell.swift
1
2710
// // FormStepperCell.swift // SwiftFormsApplication // // Created by Miguel Angel Ortuno Ortuno on 23/5/15. // Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. // public class FormStepperCell: FormTitleCell { /// MARK: Cell views public let stepperView = UIStepper() public let countLabel = UILabel() public required init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .None titleLabel.translatesAutoresizingMaskIntoConstraints = false stepperView.translatesAutoresizingMaskIntoConstraints = false countLabel.translatesAutoresizingMaskIntoConstraints = false countLabel.textAlignment = .Right contentView.addSubview(titleLabel) contentView.addSubview(countLabel) contentView.addSubview(stepperView) titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal) contentView.addConstraint(NSLayoutConstraint(item: stepperView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) stepperView.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged) } public override func update() { super.update() let config = rowDescriptor.configuration if let mx = config.maximumValue { stepperView.maximumValue = mx } if let mn = config.minimumValue { stepperView.minimumValue = mn } if let s = config.steps { stepperView.stepValue = s } titleLabel.text = rowDescriptor.title if let value = rowDescriptor.value as? Double { stepperView.value = value } else { stepperView.value = stepperView.minimumValue rowDescriptor.value = stepperView.minimumValue } countLabel.text = rowDescriptor.value?.description } public override func constraintsViews() -> [String : UIView] { return ["titleLabel" : titleLabel, "countLabel" : countLabel, "stepperView" : stepperView] } public override func defaultVisualConstraints() -> [String] { return [ "V:|[titleLabel]|", "V:|[countLabel]|", "H:|-16-[titleLabel][countLabel]-[stepperView]-16-|" ] } internal func valueChanged(_: UISwitch) { rowDescriptor.value = stepperView.value countLabel.text = rowDescriptor.value?.description } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
d5527b046ea5e9e6691aadf009c9051e
33.74359
186
0.645387
5.313725
false
true
false
false
DrippApp/Dripp-iOS
Dripp/ProfileViewController.swift
1
5356
// // ProfileViewController.swift // Dripp // // Created by Henry Saniuk on 1/29/16. // Copyright © 2016 Henry Saniuk. All rights reserved. // import UIKit import MBCircularProgressBar import Haneke class ProfileViewController: UIViewController, UICollectionViewDelegate { @IBOutlet weak var profilePicture: UIImageView! @IBOutlet weak var currentLevel: UIImageView! @IBOutlet weak var nextLevel: UIImageView! @IBOutlet weak var nextLevelText: UILabel! @IBOutlet weak var progressBar: MBCircularProgressBarView! @IBOutlet weak var currentLevelText: UILabel! var achievements = [Achievement]() var id = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. profilePicture.image = UIImage(named: "default") profilePicture.layer.borderWidth = 1 profilePicture.layer.borderColor = UIColor.lightGrayColor().CGColor profilePicture.layer.cornerRadius = profilePicture.frame.height/2 profilePicture.layer.masksToBounds = false profilePicture.clipsToBounds = true self.navigationItem.title = "" // Level Status currentLevelText.text = "1" nextLevelText.text = "2" let params = ["fields": "name, id"] let graphPath: String if id == "" { //get the profile of the current user graphPath = "me" } else { //get the profile of another user graphPath = id } let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: graphPath, parameters: params) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { // Process error print("Error: \(error)") } else { let id = result.valueForKey("id") as! NSString as String self.profilePicture.hnk_setImageFromURL(NSURL(string: "https://graph.facebook.com/\(id)/picture?width=800&height=800&return_ssl_resources=1")!) self.navigationItem.title = result.valueForKey("name") as! NSString as String } }) let progressBlue = UIColor(hexString: "#4E8DCB") self.progressBar.progressColor = progressBlue self.progressBar.progressStrokeColor = progressBlue self.achievements.append(Achievement(id: 1, title: "Power Shower", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower2", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower3", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower4", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower5", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower6", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower7", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower8", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower9", description: "You showered in under 10 minutes", image: "lock")) self.achievements.append(Achievement(id: 1, title: "Power Shower10", description: "You showered in under 10 minutes", image: "lock")) } override func viewDidAppear(animated: Bool) { self.progressBar.setValue(85, animateWithDuration: 1.5) } func numberOfSectionsInCollectionView(collectionView: UICollectionView?) -> Int { return 1 } func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int { return achievements.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("achievement", forIndexPath: indexPath) as! AchievementCell cell.image?.image = UIImage(named: achievements[indexPath.item].image) cell.contentView.layer.cornerRadius = 5 cell.contentView.layer.masksToBounds = true return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let achievement = achievements[indexPath.item] let alert = UIAlertController(title: achievement.title, message: achievement.description, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okey Dokey", style: UIAlertActionStyle.Default, handler: { alertAction in alert.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } }
mit
6fe5f2096ef0fb560279f24ee418c017
49.056075
159
0.675817
4.772727
false
false
false
false
alexdrone/S
src/Condition.swift
1
10238
import Foundation extension Condition: Generatable { /// Generates the code for this right hand side value. func generate() -> String { var expressions = [String]() for expression in self.expressions { let size = Configuration.targetOsx ? "(NSApplication.shared().mainWindow?.frame.size ?? CGSize.zero)" : "UIScreen.main.fixedCoordinateSpace.bounds.size" if Configuration.targetOsx { switch expression.expression.0 { case .height: break case .width: break case .horizontal: continue case .vertical: continue case .idiom: continue case .unspecified: continue default: continue } } var string = "" switch expression.expression.0 { case .height: string += "\(size).height " case .width: string += "\(size).width " case .horizontal: string += "(traitCollection?.horizontalSizeClass ?? UIUserInterfaceSizeClass.unspecified) " case .vertical: string += "(traitCollection?.verticalSizeClass ?? UIUserInterfaceSizeClass.unspecified) " case .idiom: string += "UIDevice.current.userInterfaceIdiom " case .contentSize: string += Configuration.appExtensionApiOnly ? "Application.preferredContentSizeCategory() " : "UIApplication.shared.preferredContentSizeCategory " case .unspecified: string += "true " } switch expression.expression.1 { case .equal: string += "== " case .notEqual: string += "!= " case .greaterThan: string += "> " case .greaterThanOrequal: string += ">= " case .lessThan: string += "< " case .lessThanOrequal: string += "<= " case .unspecified: string += "" } switch expression.expression.2 { case .constant: string += "\(expression.expression.3)" case .compact: string += "UIUserInterfaceSizeClass.compact" case .regular: string += "UIUserInterfaceSizeClass.regular" case .pad: string += "UIUserInterfaceIdiom.pad" case .phone: string += "UIUserInterfaceIdiom.phone" case .contentSizeExtraSmall: string += ".extraSmall" case .contentSizeSmall: string += ".small" case .contentSizeMedium: string += ".medium" case .contentSizeLarge: string += ".large" case .contentSizeExtraLarge: string += ".extraLarge" case .contentSizeExtraExtraLarge: string += ".extraExtraLarge" case .contentSizeExtraExtraExtraLarge: string += ".extraExtraExtraLarge" case .contentSizeAccessibilityMedium: string += ".accessibilityMedium" case .contentSizeAccessibilityLarge: string += ".accessibilityLarge" case .contentSizeAccessibilityExtraLarge: string += ".accessibilityExtraLarge" case .contentSizeAccessibilityExtraExtraLarge: string += ".accessibilityExtraExtraLarge" case .contentSizeAccessibilityExtraExtraExtraLarge: string += ".accessibilityExtraExtraExtraLarge" case .unspecified: string += "" } expressions.append(string) } return expressions.joined(separator: " && ") } } enum ConditionError: Error { case malformedCondition(error: String) case malformedRhsValue(error: String) } func ==<T:Parsable>(lhs: T, rhs: T) -> Bool { return lhs.rawString == rhs.rawString } func hash<T:Parsable>(_ item: T) -> Int { return item.rawString.hashValue; } protocol Parsable: Equatable { var rawString: String { get } init(rawString: String) throws } struct Condition: Hashable, Parsable { struct ExpressionToken { enum Default: String { case `default` = "default" case external = "?" } enum Lhs: String { case horizontal = "horizontal" case vertical = "vertical" case width = "width" case height = "height" case idiom = "idiom" case contentSize = "category" case unspecified = "unspecified" } enum Operator: String { case equal = "=" case notEqual = "≠" case lessThan = "<" case lessThanOrequal = "≤" case greaterThan = ">" case greaterThanOrequal = "≥" case unspecified = "unspecified" static func all() -> [Operator] { return [equal, notEqual, lessThan, lessThanOrequal, greaterThan, greaterThanOrequal] } static func allRaw() -> [String] { return [equal.rawValue, notEqual.rawValue, lessThan.rawValue, lessThanOrequal.rawValue, greaterThan.rawValue, greaterThanOrequal.rawValue] } static func characterSet() -> CharacterSet { return CharacterSet(charactersIn: self.allRaw().joined(separator: "")) } static func operatorContainedInString(_ string: String) -> Operator { for opr in self.all() { if string.range(of: opr.rawValue) != nil { return opr } } return unspecified } func isEqual<T:Equatable>(_ lhs: T, rhs: T) -> Bool { switch self { case .equal: return lhs == rhs case .notEqual: return lhs != rhs default: return false } } func compare<T:Comparable>(_ lhs: T, rhs: T) -> Bool { switch self { case .equal: return lhs == rhs case .notEqual: return lhs != rhs case .lessThan: return lhs < rhs case .lessThanOrequal: return lhs <= rhs case .greaterThan: return lhs > rhs case .greaterThanOrequal: return lhs >= rhs default: return false } } } enum Rhs: String { case regular = "regular" case compact = "compact" case pad = "pad" case phone = "phone" case constant = "_" case contentSizeExtraSmall = "xs" case contentSizeSmall = "s" case contentSizeMedium = "m" case contentSizeLarge = "l" case contentSizeExtraLarge = "xl" case contentSizeExtraExtraLarge = "xxl" case contentSizeExtraExtraExtraLarge = "xxxl" case contentSizeAccessibilityMedium = "am" case contentSizeAccessibilityLarge = "al" case contentSizeAccessibilityExtraLarge = "axl" case contentSizeAccessibilityExtraExtraLarge = "axxl" case contentSizeAccessibilityExtraExtraExtraLarge = "axxxl" case unspecified = "unspecified" } } struct Expression: Hashable, Parsable { /// @see Parsable. let rawString: String /// Wether this expression is always true or not. fileprivate let tautology: Bool /// The actual parsed expression. fileprivate let expression: (Condition.ExpressionToken.Lhs, Condition.ExpressionToken.Operator, Condition.ExpressionToken.Rhs, Float) /// Hashable compliancy. var hashValue: Int { get { return hash(self) } } init(rawString: String) throws { self.rawString = normalizeExpressionString(rawString) // Check for default expression. if self.rawString.range(of: Condition.ExpressionToken.Default.default.rawValue) != nil { self.expression = (.unspecified, .unspecified, .unspecified, 0) self.tautology = true // Expression. } else { self.tautology = false var terms = self.rawString.components(separatedBy: Condition.ExpressionToken.Operator.characterSet()) let opr = Condition.ExpressionToken.Operator.operatorContainedInString(self.rawString) if terms.count != 2 || opr == Condition.ExpressionToken.Operator.unspecified { throw ConditionError.malformedCondition(error: "No valid operator found in the string") } terms = terms.map({ return $0.trimmingCharacters(in: CharacterSet.whitespaces) }) let constant: Float let hasConstant: Bool if let c = Float(terms[1]) { constant = c hasConstant = true } else { constant = Float.nan hasConstant = false } guard let lhs = Condition.ExpressionToken.Lhs(rawValue: terms[0]), let rhs = hasConstant ? Condition.ExpressionToken.Rhs.constant : Condition.ExpressionToken.Rhs(rawValue: terms[1]) else { throw ConditionError.malformedCondition(error: "Terms of the condition not valid.") } self.expression = (lhs, opr, rhs, constant) } } } /// @see Parsable. let rawString: String var expressions: [Expression] = [Expression]() /// Hashable compliancy. var hashValue: Int { get { return hash(self) } } init(rawString: String) throws { self.rawString = normalizeExpressionString(rawString) let components = self.rawString.components(separatedBy: "and") for exprString in components { try expressions.append(Expression(rawString: exprString)) } } func isDefault() -> Bool { return self.rawString.contains("default") } } private func normalizeExpressionString(_ string: String, forceLowerCase: Bool = true) -> String { var ps = string.trimmingCharacters(in: CharacterSet.whitespaces) ps = (ps as NSString).replacingOccurrences(of: "\"", with: "") if forceLowerCase { ps = ps.lowercased() } ps = ps.replacingOccurrences(of: "\"", with: "") ps = ps.replacingOccurrences(of: "'", with: "") ps = ps.replacingOccurrences(of: "!=", with: Condition.ExpressionToken.Operator.notEqual.rawValue) ps = ps.replacingOccurrences(of: "<=", with: Condition.ExpressionToken.Operator.lessThanOrequal.rawValue) ps = ps.replacingOccurrences(of: ">=", with: Condition.ExpressionToken.Operator.greaterThanOrequal.rawValue) ps = ps.replacingOccurrences(of: "==", with: Condition.ExpressionToken.Operator.equal.rawValue) ps = ps.trimmingCharacters(in: CharacterSet.whitespaces) return ps }
bsd-3-clause
4d495acd9122814d29a6b20c4b34fa13
30.776398
100
0.613858
4.785781
false
false
false
false
vakoc/particle-swift
Sources/DeviceSpecification.swift
1
2521
// This source file is part of the vakoc.com open source project(s) // // Copyright © 2018 Mark Vakoc. All rights reserved. // Licensed under Apache License v2.0 // // See http://www.vakoc.com/LICENSE.txt for license information import Foundation /// Meta representation of Particle devices public struct DeviceSpecification: Codable { /// A unique identifier, within ParticleSwift, for the device public var id: String /// The identifier of the device type public var product: DeviceInformation.Product /// The URL to the product documentation public var documentationURL: URL /// The device capabilities public var traits: Traits /// The device pins, in no particular order public var pins: [Pin] /// Returns the pin with a given name on the specified side of the board. /// /// - Parameters: /// - name: The name of the pin /// - side: The side of the board as viewed with the USB connector on top /// - Returns: The matching pin, if found public func pin(_ name: String, on side: Pin.Side) -> Pin? { return pins.filter { $0.side == side && $0.name == name}.first } /// Traits define the capabilities of a device public struct Traits: OptionSet, Codable { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// Wehther the device has a WiFi radio public static let wifi = Traits(rawValue: 1<<0) /// Whether the device contains a cellular radio public static let cellular = Traits(rawValue: 1<<1) } public struct Pin: Codable { /// The name of the pin public var name: String /// The description of the pin. Reference product documentation for the most up to date /// description public var description: String /// The position of the pin. Positions are specific to the side they are located. Position is /// zero based with the top pin starting at zero when the device's USB connection is located on /// the top side public var position: Int /// The side on which the pin is located. Sides are determined when the device's USB connection /// oriented on the top public var side: Side public enum Side: String, Codable { case left case right } } }
apache-2.0
83901db20e08605fac44a9c8a46ad639
31.307692
104
0.612302
4.772727
false
false
false
false
mownier/photostream
Photostream/Modules/Liked Post/Presenter/LikedPostPresenter.swift
1
4902
// // LikedPostPresenter.swift // Photostream // // Created by Mounir Ybanez on 19/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // protocol LikedPostPresenterInterface: BaseModulePresenter, BaseModuleInteractable { var userId: String! { set get } var posts: [LikedPostData] { set get } var limit: UInt { set get } func indexOf(post id: String) -> Int? func appendPosts(_ data: [LikedPostData]) } class LikedPostPresenter: LikedPostPresenterInterface { typealias ModuleInteractor = LikedPostInteractorInput typealias ModuleView = LikedPostScene typealias ModuleWireframe = LikedPostWireframeInterface weak var view: ModuleView! var interactor: ModuleInteractor! var wireframe: ModuleWireframe! var userId: String! var posts = [LikedPostData]() var limit: UInt = 10 func indexOf(post id: String) -> Int? { return posts.index { item -> Bool in return item.id == id } } func appendPosts(_ data: [LikedPostData]) { let filtered = data.filter { post in return indexOf(post: post.id) == nil } posts.append(contentsOf: filtered) } } extension LikedPostPresenter: LikedPostModuleInterface { var postCount: Int { return posts.count } func exit() { var property = WireframeExitProperty() property.controller = view.controller wireframe.exit(with: property) } func viewDidLoad() { view.isLoadingViewHidden = false interactor.fetchNew(userId: userId, limit: limit) } func refresh() { view.isEmptyViewHidden = true view.isRefreshingViewHidden = false interactor.fetchNew(userId: userId, limit: limit) } func loadMore() { interactor.fetchNext(userId: userId, limit: limit) } func unlikePost(at index: Int) { guard var post = post(at: index), post.isLiked else { view.reload(at: index) return } post.isLiked = false post.likes -= 1 posts[index] = post view.reload(at: index) interactor.unlikePost(id: post.id) } func likePost(at index: Int) { guard var post = post(at: index), !post.isLiked else { view.reload(at: index) return } post.isLiked = true post.likes += 1 posts[index] = post view.reload(at: index) interactor.likePost(id: post.id) } func toggleLike(at index: Int) { guard let post = post(at: index) else { view.reload(at: index) return } if post.isLiked { unlikePost(at: index) } else { likePost(at: index) } } func post(at index: Int) -> LikedPostData? { guard posts.isValid(index) else { return nil } return posts[index] } } extension LikedPostPresenter: LikedPostInteractorOutput { func didRefresh(data: [LikedPostData]) { view.isLoadingViewHidden = true view.isRefreshingViewHidden = true posts.removeAll() appendPosts(data) if postCount == 0 { view.isEmptyViewHidden = false } view.didRefresh(error: nil) view.reload() } func didLoadMore(data: [LikedPostData]) { view.didLoadMore(error: nil) guard data.count > 0 else { return } appendPosts(data) view.reload() } func didRefresh(error: PostServiceError) { view.isLoadingViewHidden = true view.isRefreshingViewHidden = true view.didRefresh(error: error.message) } func didLoadMore(error: PostServiceError) { view.didLoadMore(error: error.message) } func didLike(error: PostServiceError?, postId: String) { view.didLike(error: error?.message) guard let index = indexOf(post: postId), var post = post(at: index), error != nil else { return } post.isLiked = false if post.likes > 0 { post.likes -= 1 } posts[index] = post view.reload(at: index) } func didUnlike(error: PostServiceError?, postId: String) { view.didUnlike(error: error?.message) guard let index = indexOf(post: postId), var post = post(at: index), error != nil else { return } post.isLiked = true post.likes += 1 posts[index] = post view.reload(at: index) } }
mit
e668d844b7379a76664c723fe93be493
23.262376
83
0.550704
4.504596
false
false
false
false
sarvex/SwiftRecepies
Basics/Implementing Range Pickers with UISlider/Implementing Range Pickers with UISlider/ViewController.swift
1
2676
// // ViewController.swift // Implementing Range Pickers with UISlider // // Created by Vandad Nahavandipoor on 6/28/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // var slider: UISlider! // // override func viewDidLoad() { // super.viewDidLoad() // // slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 23)) // slider.center = view.center // slider.minimumValue = 0 // slider.maximumValue = 100 // slider.value = slider!.maximumValue / 2.0 // view.addSubview(slider) // // } // //} /* 2 */ //import UIKit // //class ViewController: UIViewController { // // var slider: UISlider! // // func sliderValueChanged(slider: UISlider){ // println("Slider's new value is \(slider.value)") // } // // override func viewDidLoad() { // super.viewDidLoad() // // slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 23)) // slider.center = view.center // slider.minimumValue = 0 // slider.maximumValue = 100 // slider.value = slider!.maximumValue / 2.0 // // slider.addTarget(self, // action: "sliderValueChanged:", // forControlEvents: .ValueChanged) // // view.addSubview(slider) // // } // //} /* 3 */ import UIKit class ViewController: UIViewController { var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 23)) slider.center = view.center slider.minimumValue = 0 slider.maximumValue = 100 slider.value = slider!.maximumValue / 2.0 slider.setThumbImage(UIImage(named: "ThumbNormal"), forState: .Normal) slider.setThumbImage(UIImage(named: "ThumbHighlighted"), forState: .Highlighted) view.addSubview(slider) } }
isc
543a052646fd2a0c2f726108366b9981
26.316327
84
0.653961
3.701245
false
false
false
false
ivankorobkov/net
swift/Netx/MuxConn.swift
2
20447
// // MuxConn.swift // Net // // Created by Ivan Korobkov on 12/02/16. // Copyright © 2016 Ivan Korobkov. All rights reserved. // import Foundation let WindowMax: UInt32 = (1 << 31) - 1 let WindowInit: UInt32 = 1 << 16 // 64Kb let InitMaxStreams: UInt32 = 8 let MaxStreamId: UInt64 = (1 << 63) - 1 let InitClientId: UInt64 = 1 let InitServerId: UInt64 = 2 // MuxConn is a connection which multiplexes multiple data streams. public protocol MuxConn: class, Closer { var address: (host: String, port: Int)? { get } // Optional connection delegate. var delegate: MuxConnDelegate? { get set } // Enables or disables debug logs. func setDebug(debug: Bool) // Accepts an incoming stream. // It returns ConnRefused when the MuxConn is closed. func accept(callback: MuxConnAcceptCallback) // Opens an outgoing stream. // It returns ConnRefused when the MuxConn is closed. func connect(callback: MuxConnConnectCallback) // Sets a max total read buffer size. // It must be: 0 > window <= (1<<31)-1 func setMaxReadWindow(window: UInt32) // Sets a max number of opened accepted streams. func setMaxAcceptedStreams(maxStreams: UInt32) } public protocol MuxConnDelegate { func muxConnDidConnect(conn: MuxConn) func muxConnDidDisconnect(conn: MuxConn, error: ErrorType?) } public typealias MuxConnAcceptCallback = (MuxStream?, ErrorType?) -> Void public typealias MuxConnConnectCallback = (MuxStream?, ErrorType?) -> Void public func NewMuxConn(conn: Conn, server: Bool, delegate: MuxConnDelegate?) -> MuxConn { return MuxConnImpl(conn: conn, server: server, delegate: delegate) } enum MuxConnState { case New case Connected case Disconnected } typealias MuxWriteDone = ()->Void typealias MuxWriteTuple = (frame: MuxFrame, done: MuxWriteDone) class MuxConnImpl: MuxConn, ConnDelegate, CustomStringConvertible { // Some variables are visible only for tests. // Never access them directly. let queue: dispatch_queue_t private let conn: Conn private let server: Bool private var debug: Bool private var delegate_: MuxConnDelegate? private var delegateState: MuxConnState var error: ErrorType? var closed: Bool private var closedRemotely: Bool private var streamId: UInt64 // Next stream id. var streams: Dictionary<UInt64, MuxStreamImpl> private var acceptStreams: [MuxStreamImpl] // Pending accept streams. private var acceptCallbacks: [MuxConnAcceptCallback] // Pending accept callbacks. var accepted: UInt32 // Number of open accepted streams. var acceptedMax: UInt32 // Max number of simultaneously open accepted streams. private var connectCallbacks: [MuxConnConnectCallback] // Pending connect callbacks. var connected: UInt32 // Number of open connected streams. var connectedMax: UInt32 // Max number of simultaneously open connected streams. var readWindow: UInt32 // How much data can be received. private var readWindowMax: UInt32 // Max read buffers. var writeWindow: UInt32 // How much data can be written by all streams. private var writeQueue: [MuxFrame] // Pending control frames. private var writeDataQueue: [MuxWriteTuple] // Pendign data frames. private var writing: Bool convenience init(conn: Conn, server: Bool, delegate: MuxConnDelegate?) { self.init(conn: conn, server: server) self.delegate = delegate } init(conn: Conn, server: Bool) { self.queue = dispatch_queue_create("com.github.ivankorobkov.netx.MuxConnImpl", DISPATCH_QUEUE_SERIAL) self.conn = conn self.server = server self.debug = false self.delegate_ = nil self.delegateState = .New self.error = nil self.closed = false self.closedRemotely = false self.streams = [:] self.streamId = server ? InitServerId : InitClientId self.acceptStreams = [] self.acceptCallbacks = [] self.accepted = 0 self.acceptedMax = InitMaxStreams self.connectCallbacks = [] self.connected = 0 self.connectedMax = InitMaxStreams self.readWindow = WindowInit self.readWindowMax = WindowInit self.writing = false self.writeQueue = [] self.writeDataQueue = [] self.writeWindow = WindowInit conn.delegate = self self.receiveLoop() } var address: (host: String, port: Int)? { return self.conn.address } var description: String { guard let addr = self.conn.address else { return "{\(unsafeAddressOf(self)) \(self.conn)}" } return "{\(unsafeAddressOf(self)) \(addr.host):\(addr.port)}" } func setDebug(debug: Bool) { dispatch_sync(self.queue) { self.debug = debug } } // ConnDelegate func connDidConnect(conn: Conn) { dispatch_async(self.queue) { () -> Void in if self.debug { print("MuxConn did connect, conn=\(self)") } self.delegateState = .Connected self.notifyDelegate() } } func connDidDisconnect(conn: Conn, error: ErrorType?) { dispatch_async(self.queue) { () -> Void in if self.debug { print("MuxConn did disconnect, conn=\(self)") } self.delegateState = .Disconnected self.close(error) // If not closed already. self.notifyDelegate() } } // Public var delegate: MuxConnDelegate? { get { var result: MuxConnDelegate? dispatch_sync(self.queue) { () -> Void in result = self.delegate_ } return result } set(newDelegate) { dispatch_async(self.queue) { () -> Void in self.delegate_ = newDelegate self.notifyDelegate() } } } private func notifyDelegate() { switch self.delegateState { case .Connected: self.delegate_?.muxConnDidConnect(self) case .Disconnected: self.delegate_?.muxConnDidDisconnect(self, error: self.error) default: break } } func accept(callback: MuxConnAcceptCallback) { dispatch_async(self.queue) { () -> Void in guard !self.closed else { var error = IOError.ClosedPipe if self.closedRemotely { error = IOError.BrokenPipe } callback(nil, error) return } self.acceptCallbacks.append(callback) self.acceptFlush() } } func connect(callback: MuxConnConnectCallback) { dispatch_async(self.queue) { () -> Void in guard !self.closed else { var error = IOError.ClosedPipe if self.closedRemotely { error = IOError.BrokenPipe } callback(nil, error) return } self.connectCallbacks.append(callback) self.connectFlush() } } func setMaxReadWindow(window: UInt32) { assert(window > 0, "MuxConn maxReadWindow must be > 0") assert(window <= WindowMax, "MuxConn maxReadWindow must be <= \(WindowMax)") dispatch_async(self.queue) { () -> Void in guard !self.closed else { return } self.readWindowMax = window self.maybeWriteWindowMessage() } } func setMaxAcceptedStreams(maxStreams: UInt32) { dispatch_async(self.queue) { () -> Void in guard !self.closed else { return } self.acceptedMax = maxStreams self.writeFrame(MuxFrame.newMaxStreams(maxStreams)) self.acceptFlush() } } func close() { dispatch_async(self.queue) { () -> Void in self.close(nil) } } // Stream methods func streamDidClose(streamId: UInt64) { guard self.streams[streamId] != nil else { return } self.streams.removeValueForKey(streamId) if self.streamIdIsRemote(streamId) { self.accepted -= 1 } else { self.connected -= 1 self.connectFlush() } } private func streamIdIsRemote(streamId: UInt64) -> Bool { let serverId = (streamId % 2) == 0 if self.server { return !serverId } return serverId } // Accepting/connecting private func acceptFlush() { guard !self.closed else { var error = self.error if error == nil { if self.closedRemotely { error = IOError.BrokenPipe } else { error = IOError.ClosedPipe } } for callback in self.acceptCallbacks { callback(nil, error) } self.acceptCallbacks.removeAll() return } while self.acceptStreams.count > 0 && self.acceptCallbacks.count > 0 { let stream = self.acceptStreams.removeFirst() let callback = self.acceptCallbacks.removeFirst() callback(stream, nil) } } private func connectFlush() { guard !self.closed else { var error = self.error if error == nil { if self.closedRemotely { error = IOError.BrokenPipe } else { error = IOError.ClosedPipe } } for callback in self.connectCallbacks { callback(nil, error) } self.connectCallbacks.removeAll() return } while self.connectCallbacks.count > 0 && self.connected < self.connectedMax { let streamId = self.streamId self.streamId += 2 let stream = MuxStreamImpl(id: streamId, queue: self.queue, conn: self) self.streams[streamId] = stream self.connected += 1 let callback = self.connectCallbacks.removeFirst() callback(stream, nil) self.writeFrame(MuxFrame.newStreamOpen(streamId)) } } // Receiving private func receiveLoop() { MuxFrame.read(self.conn, callback: self.receiveCallback) } private func receiveCallback(msg: MuxFrame?, error: ErrorType?) { dispatch_async(self.queue) { () -> Void in self.receive(msg, error: error) } } private func receive(frame: MuxFrame?, error: ErrorType?) { guard !self.closed else { return } if self.debug { if error == nil { print("MuxConn did receive a frame, conn=\(self), frame=\(frame!)") } else { print("MuxConn did fail to receive a frame, conn=\(self), error=\(error!)") } } guard error == nil else { self.close(error) return } let f = frame! do { switch f.type { case .Close: self.receiveClose(f) case .Window: try self.receiveWindow(f) case .MaxStreams: self.receiveMaxStreams(f) case .StreamOpen: try self.receiveStreamOpen(f) case .StreamClose: try self.receiveStreamClose(f) case .StreamData: try self.receiveStreamData(f) case .StreamWindow: try self.receiveStreamWindow(f) case .StreamPriority: try self.receiveStreamPriority(f) default: throw MuxError.Error(.InvalidFrame, "Unsupported frame type \(f.type)") } } catch { self.close(error) return } // Continue reading from the connection. self.receiveLoop() } private func receiveClose(frame: MuxFrame) { var error: ErrorType? switch frame.status { case .OK: error = nil default: error = MuxError.Error(frame.status, frame.text ?? "Undefined error") } self.closedRemotely = true self.close(error) } private func receiveWindow(frame: MuxFrame) throws { let delta = frame.window guard delta <= (WindowMax - self.writeWindow) else { throw MuxError.Error( .FlowControlError, "Write window overflow: delta=\(delta), window=\(self.writeWindow), max=\(WindowMax)") } self.writeWindow += delta self.writeFlush() } private func receiveMaxStreams(frame: MuxFrame) { self.connectedMax = frame.maxStreams self.connectFlush() } private func receiveStreamOpen(frame: MuxFrame) throws { let streamId = frame.streamId guard streamId <= MaxStreamId else { throw MuxError.Error(.InvalidStreamId, "Open streamId overflow: streamId=\(streamId), max=\(MaxStreamId)") } guard self.streamIdIsRemote(streamId) else { throw MuxError.Error(.InvalidStreamId, "Non-remote open streamId: streamId=\(streamId), server=\(self.server)") } guard self.streams[streamId] == nil else { throw MuxError.Error(.DuplicateStreamId, "Duplicate open streamId: streamId=\(streamId)") } guard self.accepted < self.acceptedMax else { let frame = MuxFrame.newStreamClose(streamId, status: .StreamRefused, text: "Stream refused") self.writeFrame(frame) return } let stream = MuxStreamImpl(id: streamId, queue: self.queue, conn: self) self.streams[streamId] = stream self.accepted += 1 self.acceptStreams.append(stream) self.acceptFlush() } private func receiveStreamClose(frame: MuxFrame) throws { let streamId = frame.streamId if let stream = self.streams[streamId] { try stream.receive(frame) } } private func receiveStreamWindow(frame: MuxFrame) throws { let streamId = frame.streamId if let stream = self.streams[streamId] { try stream.receive(frame) } else { let frame = MuxFrame.newStreamEOF(streamId) self.writeFrame(frame) } } private func receiveStreamPriority(frame: MuxFrame) throws { let streamId = frame.streamId if let stream = self.streams[streamId] { try stream.receive(frame) } else { let frame = MuxFrame.newStreamEOF(streamId) self.writeFrame(frame) } } private func receiveStreamData(frame: MuxFrame) throws { let streamId = frame.streamId guard let data = frame.data else { return } let len = UInt32(data.length) guard len <= self.readWindow else { throw MuxError.Error(.FlowControlError, "Read window overflow: dataLen=\(len), window=\(self.readWindow)") } // Decrement the read window. self.readWindow -= len self.maybeWriteWindowMessage() // Pass the data to the stream. if let stream = self.streams[streamId] { try stream.receive(frame) } else { let frame = MuxFrame.newStreamEOF(streamId) self.writeFrame(frame) } } // Writing func writeFrame(frame: MuxFrame) { self.writeQueue.append(frame) self.writeFlush() } func writeDataFrame(frame: MuxFrame, done: MuxWriteDone) { self.writeDataQueue.append((frame, done)) self.writeFlush() } private func maybeWriteWindowMessage() { guard self.readWindow <= (self.readWindowMax / 2) else { return } let delta = self.readWindowMax - self.readWindow let frame = MuxFrame.newWindow(delta) self.readWindow += delta self.writeFrame(frame) } private func writeFlush() { guard !self.closed else { return } guard !self.writing else { return } // Flush a control frame if present. guard self.writeQueue.isEmpty else { self.writing = true let frame = self.writeQueue.removeFirst() frame.write(self.conn) { (_, error) in dispatch_async(self.queue, { self.writeDidComplete(error) }) } if self.debug { print("MuxConn did write a frame, conn=\(self), frame=\(frame)") } return } // Flush a data frames if present and the write window is available. guard self.writeDataQueue.count > 0 else { return } guard self.writeWindow >= UInt32(self.writeDataQueue[0].frame.len) else { return } let (frame, callback) = self.writeDataQueue.removeFirst() self.writing = true self.writeWindow -= UInt32(frame.len) frame.write(self.conn) { (n, error) in dispatch_async(self.queue, { callback() self.writeDidComplete(error) }) } if self.debug { print("MuxConn did write a frame, conn=\(self), frame=\(frame)") } } private func writeDidComplete(error: ErrorType?) { self.writing = false guard error == nil else { self.close(error) return } self.writeFlush() } // Closing private func close(error: ErrorType?) { guard !self.closed else { return } if self.debug { print("MuxConn will close, conn=\(self), error=\(error)") } self.error = error self.closed = true self.closeStreams() self.closeFlush() self.closeFrame() } private func closeStreams() { let error = self.error for (_, stream) in self.streams { stream.connDidClose(error) } self.streams.removeAll() } private func closeFlush() { self.acceptFlush() self.connectFlush() } private func closeFrame() { guard !self.closedRemotely else { self.conn.close() return } var frame = MuxFrame.newEOF() if self.error != nil { var status = MuxStatus.InternalError var text = "Internal error" switch self.error! { case MuxError.Error(let status0, let text0): status = status0 text = text0 default: break } frame = MuxFrame.newClose(status, text: text) } frame.write(self.conn) { (_, _) in self.conn.close() } if self.debug { print("MuxConn did write a frame, conn=\(self), frame=\(frame)") } } }
apache-2.0
1ae979caf79c9310b91d377c76ca5b7c
28.461095
123
0.53497
4.705639
false
false
false
false
tommeier/fastlane
snapshot/lib/assets/SnapshotHelper.swift
2
5883
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // import Foundation import XCTest var deviceLanguage = "" var locale = "" @available(*, deprecated, message: "use setupSnapshot: instead") func setLanguage(_ app: XCUIApplication) { setupSnapshot(app) } func setupSnapshot(_ app: XCUIApplication) { Snapshot.setupSnapshot(app) } func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) { Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator) } open class Snapshot: NSObject { open class func setupSnapshot(_ app: XCUIApplication) { setLanguage(app) setLocale(app) setLaunchArguments(app) } class func setLanguage(_ app: XCUIApplication) { guard let prefix = pathPrefix() else { return } let path = prefix.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let prefix = pathPrefix() else { return } let path = prefix.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } class func setLaunchArguments(_ app: XCUIApplication) { guard let prefix = pathPrefix() else { return } let path = prefix.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) { if waitForLoadingIndicator { waitForLoadingIndicatorToDisappear() } print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work sleep(1) // Waiting for the animation to be finished (kind of) #if os(tvOS) XCUIApplication().childrenMatchingType(.Browser).count #elseif os(OSX) XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else XCUIDevice.shared().orientation = .unknown #endif } class func waitForLoadingIndicatorToDisappear() { #if os(tvOS) return #endif let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other) while (0..<query.count).map({ query.element(boundBy: $0) }).contains(where: { $0.isLoadingIndicator }) { sleep(1) print("Waiting for loading indicator to disappear...") } } class func pathPrefix() -> URL? { let homeDir: URL //on OSX config is stored in /Users/<username>/Library //and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { print("Couldn't find Snapshot configuration files - can't detect current user ") return nil } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { print("Couldn't find Snapshot configuration files - can't detect `Users` dir") return nil } homeDir = usersDir.appendingPathComponent(user) #else guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { print("Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable.") return nil } guard let homeDirUrl = URL(string: simulatorHostHome) else { print("Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?") return nil } homeDir = URL(fileURLWithPath: homeDirUrl.path) #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } extension XCUIElement { var isLoadingIndicator: Bool { let whiteListedLoaders = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] if whiteListedLoaders.contains(self.identifier) { return false } return self.frame.size == CGSize(width: 10, height: 20) } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.3]
mit
976d74bf0bfd94ecbdf1d1278c11eb36
34.433735
151
0.623087
5.018771
false
false
false
false
coddingtonbear/taskwarrior-pomodoro
TWMenuTests/SwiftTaskWarrior.swift
1
3450
// // SwiftTaskWarrior.swift // TWMenuTests // // Created by Jarosław Wojtasik on 28/08/2018. // Copyright © 2018 Adam Coddington. All rights reserved. // import Foundation public class SwiftTaskWarrior { // MARK - ### Fields ### let overrides: [String] let environment: [String: String] lazy var myCustomQueue = DispatchQueue(label: "task worker") public init (overrides: [String] = [], environment: [String: String] = [:] ) { self.overrides = overrides self.environment = environment } // MARK: - ### Public API ### public func add(description: String) -> Int? { return add([description]) } public func add(_ raw: [String]) -> Int? { let out = run(cmd: "add", params: raw) let id = out.components(separatedBy: .whitespaces).last?.trimmingCharacters(in: CharacterSet(charactersIn: ".\n")) return Int(id ?? "") } public func next() { _ = run(cmd: "next") } public func config(key: String, val: String) { _ = run(cmd: "config", params: ["rc.confirmation=off", "\(key)", "\(val)"]) } public func show(_ name: String?) { _ = run(cmd: "show", params: [name ?? ""] + ["rc.confirmation=off"]) } public func log(_ raw: [String]) { _ = run(cmd: "log", params: raw) } public func annotate(filter: [String], text: String) { _ = run(filter: filter, cmd: "annotate", params: [text]) } public func uuids(filter: [String]) -> [String] { let uuids = run(filter: filter, cmd: "uuids") let list = uuids.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: " ").map { String($0) } return list } // MARK: - ### Private API ### func run(cmd: String, params: [String] = [], _ input: String? = nil) -> String { return run(filter: [], cmd: cmd, params: params, input) } func run(filter: [String], cmd: String, params: [String] = [], _ input: String? = nil) -> String { let arguments: [String] = filter + [cmd] + self.overrides + params var output: String = "" let queueStart = Date() myCustomQueue.sync { let task = Process() task.launchPath = "/usr/local/bin/task" task.arguments = arguments print("-> task \(task.arguments?.joined(separator: " ") ?? "")") print("----------------") let oPipe = Pipe() task.standardOutput = oPipe if let a = input { task.standardInput = Pipe(withInput: a) } task.environment = self.environment task.launch() let before = Date() task.waitUntilExit() let took = before.timeIntervalSinceNow print("----------------") print(": \(-took * 1000) ms") let data = oPipe.fileHandleForReading.readDataToEndOfFile() output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String print("^^^^^^^^^^^^") print(output) print("______") } print(": \(-queueStart.timeIntervalSinceNow * 1000) ms") return output } } extension Pipe { public convenience init(withInput input: String) { self.init() self.fileHandleForWriting.write(input.data(using: .utf8) ?? Data()) } }
mit
f5b5fad0750359779db8c7f24f67f245
32.153846
122
0.539153
4.210012
false
false
false
false
mtransitapps/mtransit-for-ios
MonTransit/Source/Utils/File.swift
1
5156
// // File.swift // MonTransit // // Created by Thibault on 16-01-07. // Copyright © 2016 Thibault. All rights reserved. // import Foundation class File { class func open(path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? { if NSFileManager().fileExistsAtPath(path) { do { return try String(contentsOfFile: path, encoding: encoding) } catch let error as NSError { print(error.code) return nil } } return nil } class func save(path: String, content: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool { do { try content.writeToFile(path, atomically: true, encoding: encoding) return true } catch let error as NSError { print(error.code) return false } } class func copy(sourcePath: String, destinationPath: String, delete: Bool = false) -> Bool{ if delete && NSFileManager().fileExistsAtPath(destinationPath) { File.delete(destinationPath) } if NSFileManager().fileExistsAtPath(sourcePath) { do { try NSFileManager().copyItemAtPath(sourcePath, toPath: destinationPath) return true } catch let error as NSError { print(error.code) return false } } return false } class func move(sourcePath: String, destinationPath: String, delete: Bool = false) -> Bool{ if delete && NSFileManager().fileExistsAtPath(destinationPath) { File.delete(destinationPath) } if NSFileManager().fileExistsAtPath(sourcePath) { do { try NSFileManager().moveItemAtPath(sourcePath, toPath: destinationPath) return true } catch let error as NSError { print(error.code) return false } } return false } class func createDirectory(path:String) { if !File.documentFileExist(path){ let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentsDirectory: AnyObject = paths[0] let dataPath = documentsDirectory.stringByAppendingPathComponent(path) do { try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription); } } } class func delete(path: String) -> Bool { do { try NSFileManager().removeItemAtPath(path) return true } catch let error as NSError { print(error.code) return false } } class func deleteContentsOfFolder(path: String) { if let enumerator = NSFileManager.defaultManager().enumeratorAtPath(path) { while let fileName = enumerator.nextObject() as? String { do { try NSFileManager.defaultManager().removeItemAtPath("\(path)\(fileName)") } catch let e as NSError { print(e) } catch { print("error") } } } } class func getBundleFilePath(iFileName:String, iOfType:String) -> String? { guard let path = NSBundle.mainBundle().pathForResource(iFileName, ofType: iOfType) else { return "" } return path } class func documentFileExist(iFileName:String) -> Bool { let wPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! let wgetFileNamePath = "\(wPaths)/\(iFileName)" let wCheckValidation = NSFileManager.defaultManager() return (wCheckValidation.fileExistsAtPath(wgetFileNamePath)) } class func getDocumentFilePath() -> String { return "\(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!)/" } class func getDocumentTempFolderPath() -> String { let wPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! + "/temporary/" return wPath } class func getDocumentDownloadFolderPath() -> String { let wPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! + "/download/" return wPath } } extension NSBundle { var releaseVersionNumber: String? { return self.infoDictionary?["CFBundleShortVersionString"] as? String } var buildVersionNumber: String? { return self.infoDictionary?["CFBundleVersion"] as? String } }
apache-2.0
7cd088f5ed0ed49548ccf57f18b6a239
30.82716
145
0.57323
5.785634
false
false
false
false
mcabasheer/table-cell-progress-bar
TableDownloadProgress/TableDownloadProgress/UICircularProgressRingGradientPosition.swift
1
2955
// // UICircularProgressRingGradientPosition.swift // UICircularProgressRing // // Copyright (c) 2016 Luis Padron // // 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. // /** # UICircularProgressRingGradientPosition This is an enumeration which is used to determine the position for a gradient. Used inside the `UICircularProgressRingLayer` to allow customization for the gradient. ## Author Luis Padron */ import UIKit @objc public enum UICircularProgressRingGradientPosition: Int { /// Gradient positioned at the top case top = 1 /// Gradient positioned at the bottom case bottom = 2 /// Gradient positioned to the left case left = 3 /// Gradient positioned to the right case right = 4 /// Gradient positioned in the top left corner case topLeft = 5 /// Gradient positioned in the top right corner case topRight = 6 /// Gradient positioned in the bottom left corner case bottomLeft = 7 /// Gradient positioned in the bottom right corner case bottomRight = 8 /** Returns a `CGPoint` in the coordinates space of the passed in `CGRect` for the specified position of the gradient. */ func pointForPosition(in rect: CGRect) -> CGPoint { switch self { case .top: return CGPoint(x: rect.midX, y: rect.minY) case .bottom: return CGPoint(x: rect.midX, y: rect.maxY) case .left: return CGPoint(x: rect.minX, y: rect.midY) case .right: return CGPoint(x: rect.maxX, y: rect.midY) case .topLeft: return CGPoint(x: rect.minX, y: rect.minY) case .topRight: return CGPoint(x: rect.maxX, y: rect.minY) case .bottomLeft: return CGPoint(x: rect.minX, y: rect.maxY) case .bottomRight: return CGPoint(x: rect.maxX, y: rect.maxY) } } }
gpl-3.0
de417eea33a6d86c2ea510af96a027fb
33.360465
87
0.677834
4.470499
false
false
false
false
DouKing/WYListView
WYListViewController/Demo/DetailViewController.swift
1
1577
// // DetailViewController.swift // WYListViewController // // Created by iosci on 2016/10/26. // Copyright © 2016年 secoo. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var contentView: UIView! override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false let listVC = WYListView() listVC.dataSource = self listVC.delegate = self listVC.view.frame = self.contentView.bounds self.addChildViewController(listVC) self.contentView.addSubview(listVC.view) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - WYListViewDataSource - extension DetailViewController: WYListViewDataSource, WYListViewDelegate { func numberOfSections(in listView: WYListView) -> Int { return 10 } func listView(_ listView: WYListView, numberOfRowsInSection section: Int) -> Int { return 15 } func listView(_ listView: WYListView, titleForSection section: Int) -> String? { return "section:\(section)" } func listView(_ listView: WYListView, titleForRowAtIndexPath indexPath: IndexPath) -> String? { return "section: \(indexPath.section), row: \(indexPath.row)" } func listView(_ listView: WYListView, didSelectRowAtIndexPath indexPath: IndexPath) { print("select: \(indexPath.section, indexPath.row)") } }
mit
9984c4797f23c5d7421be5fb85d059a9
28.148148
99
0.673443
5.061093
false
false
false
false
loganSims/wsdot-ios-app
wsdot/HighwayAlertItem.swift
2
1706
// // HighwayAlertItem.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import RealmSwift class HighwayAlertItem: Object { @objc dynamic var alertId: Int = 0 @objc dynamic var priority: String = "" @objc dynamic var region: String = "" @objc dynamic var eventCategory: String = "" @objc dynamic var headlineDesc: String = "" @objc dynamic var eventStatus: String = "" @objc dynamic var startDirection: String = "" @objc dynamic var lastUpdatedTime = Date() @objc dynamic var startTime = Date() @objc dynamic var startLatitude: Double = 0.0 @objc dynamic var startLongitude: Double = 0.0 @objc dynamic var endLatitude: Double = 0.0 @objc dynamic var endLongitude: Double = 0.0 @objc dynamic var county: String? = nil @objc dynamic var endTime: Date? = nil @objc dynamic var extendedDesc: String? = nil @objc dynamic var delete = false override static func primaryKey() -> String? { return "alertId" } }
gpl-3.0
856618e66282d4a4a6ad95ea17e8f958
33.816327
72
0.692263
4.181373
false
false
false
false
LongPF/FaceTube
FaceTube/Tool/Capture/FTPreviewView.swift
1
3262
// // FTPreviewView.swift // FaceTube // // Created by 龙鹏飞 on 2017/4/17. // Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved. // import GLKit /// 预览view class FTPreviewView: GLKView, FTImageTarget { public var coreImageContext: CIContext? fileprivate var drawableBounds: CGRect! fileprivate var devicePosition: AVCaptureDevicePosition! //MARK: ************************ life cycle ************************ override init(frame: CGRect, context: EAGLContext) { super .init(frame: frame, context: context) self.enableSetNeedsDisplay = false self.backgroundColor = UIColor.black self.isOpaque = true self.transform = transformWithDevice(devicePosition: .front) self.frame = frame self.devicePosition = AVCaptureDevicePosition.front //view与opengles绑定 self.bindDrawable() self.drawableBounds = self.bounds self.drawableBounds.size.width = CGFloat(self.drawableWidth) self.drawableBounds.size.height = CGFloat(self.drawableHeight) // NotificationCenter.default.addObserver(self, selector: #selector(filterChanged(notification:)), name: NSNotification.Name.FTFilterSelectionChangedNotification, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: ************************ interface methods *************** /// 根据前后摄像头设置transform public func setTransformWithDevice(devicePosition: AVCaptureDevicePosition){ if (devicePosition.rawValue == self.devicePosition.rawValue){ return } switch devicePosition { case .back: self.transform = CGAffineTransform.init(rotationAngle: .pi/2.0) self.devicePosition = AVCaptureDevicePosition.back break case .front: self.transform = CGAffineTransform.init(rotationAngle: .pi*1.5).scaledBy(x: -1.0, y: 1.0) self.devicePosition = AVCaptureDevicePosition.front break default: break } } //MARK: ************************ response methods *************** // func filterChanged(notification: Notification){ // self.filter = (notification.object as? CIFilter)?.copy() as? CIFilter // } } extension FTPreviewView{ func setImage(image: CIImage) { self.bindDrawable() FTPhotoFilters.shared.selectedFilter.setValue(image, forKey: kCIInputImageKey) let filteredImage = FTPhotoFilters.shared.selectedFilter.outputImage; if filteredImage != nil { self.coreImageContext?.draw(filteredImage!, in: CGRect.init(x: 0, y: 0, width: self.drawableWidth, height: self.drawableHeight), from: image.extent) }else{ self.coreImageContext?.draw(image, in: CGRect.init(x: 0, y: 0, width: self.drawableWidth, height: self.drawableHeight), from: image.extent) } self.display() FTPhotoFilters.shared.selectedFilter.setValue(nil, forKey: kCIInputImageKey) } }
mit
fb875d5044a17c78430f34f0eaa6b2b0
32.247423
182
0.617364
4.742647
false
false
false
false
YuhuaBillChen/Spartify
Spartify/Spartify/HostPartyViewController.swift
1
9585
// // HostPartyViewController.swift // Spartify // // Created by Bill on 1/23/16. // Copyright © 2016 pennapps. All rights reserved. // import UIKit import Parse import ParseUI import CoreMotion import AudioToolbox class HostPartyViewController: UIViewController { @IBOutlet weak var XYZLabel: UILabel! @IBOutlet weak var leavePartyButton: UIButton! @IBOutlet weak var setSeqButton: UIButton! @IBOutlet weak var seqLab: UILabel! @IBOutlet weak var seqLabel1: UILabel! @IBOutlet weak var seqLabel2: UILabel! @IBOutlet weak var seqLabel3: UILabel! @IBOutlet weak var seqLabel4: UILabel! @IBOutlet weak var clearSeqButton: UIButton! let SEQ_LENGTH = 4 let manager = CMMotionManager() let GRAVITY_MARGIN = 0.2 let ACCELE_TRH = 0.3 let DELAY_TRH = 50 var delayCounter = 0 var sucessfullyChangStatus = false var currentState = "Normal" let userObj = PFUser.currentUser()! var partyObj:PFObject! var isSettingSeq = false var settingSeqNo = -1 var seqArray = [String]() func changeMotionStatus(gx:Double,ax:Double,gy:Double,ay:Double,gz:Double,az:Double){ if (delayCounter > DELAY_TRH){ if (gx < (-1+self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3 ){ self.currentState = "Left" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (gx > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Right" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (gz < (-1+self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3 ){ self.currentState = "Forward" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (gz > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Backward" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (abs(gx) < (self.GRAVITY_MARGIN) && abs(gz) < self.GRAVITY_MARGIN && gy < -(1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Up" self.sucessfullyChangStatus = true self.delayCounter = 0 } else if (abs(gx) < (self.GRAVITY_MARGIN) && abs(gz) < self.GRAVITY_MARGIN && gy > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){ self.currentState = "Down" self.sucessfullyChangStatus = true self.delayCounter = 0 } else{ if (self.currentState != "Normal"){ self.currentState = "Normal" self.sucessfullyChangStatus = true } } } } func changeBackground(){ if (self.currentState == "Normal"){ self.view.backgroundColor = UIColor.whiteColor() } else if (self.currentState == "Left"){ self.view.backgroundColor = UIColor.redColor() } else if (self.currentState == "Right"){ self.view.backgroundColor = UIColor.greenColor() } else if (self.currentState == "Up"){ self.view.backgroundColor = UIColor.orangeColor() } else if (self.currentState == "Down"){ self.view.backgroundColor = UIColor.purpleColor() } else if (self.currentState == "Forward"){ self.view.backgroundColor = UIColor.blueColor() } else if (self.currentState == "Backward"){ self.view.backgroundColor = UIColor.yellowColor() } else{ self.view.backgroundColor = UIColor.grayColor() } } func vibrate(){ AudioToolbox.AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } func beep(){ AudioToolbox.AudioServicesPlaySystemSound(1109) } func addSeqUpdater(){ if (isSettingSeq){ if (self.settingSeqNo < self.SEQ_LENGTH ){ self.addOneSeq(self.currentState) self.delayCounter = -DELAY_TRH vibrate() if ( self.settingSeqNo == self.SEQ_LENGTH ){ self.setSeqEnd(); } } } } func updateCheck(){ if (self.sucessfullyChangStatus){ self.XYZLabel!.text = self.currentState changeBackground() beep() if (self.currentState != "Normal"){ addSeqUpdater() } self.sucessfullyChangStatus = false; } else{ self.delayCounter += 1 } } func motionInit(){ if manager.deviceMotionAvailable { let _:CMAccelerometerData! let _:NSError! manager.deviceMotionUpdateInterval = 0.01 manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler:{ accelerometerData, error in let x = accelerometerData!.gravity.x let y = accelerometerData!.gravity.y let z = accelerometerData!.gravity.z let x2 = accelerometerData!.userAcceleration.x; let y2 = accelerometerData!.userAcceleration.y; let z2 = accelerometerData!.userAcceleration.z; let dispStr = String(format:"g x: %1.2f, y: %1.2f, z: %1.2f a x: %1.2f y:%1.2f z:%1.2f",x,y,z,x2,y2,z2) self.changeMotionStatus(x,ax:x2,gy:y,ay:y2,gz:z,az:z2) self.updateCheck() print(dispStr) }) } } func jumpToMainMenu(){ let vc = self.storyboard?.instantiateViewControllerWithIdentifier("MainMenuVC") as! ViewController manager.stopDeviceMotionUpdates(); self.presentViewController(vc, animated: false, completion: nil) } @IBAction func leavePartyPressed(sender: UIButton) { sender.enabled = false; partyObj.deleteInBackgroundWithBlock{ (success: Bool, error: NSError?) -> Void in if (success) { // The object has been saved. self.jumpToMainMenu() } else { // There was a problem, check error.description print("failed to create a new party room") self.leavePartyButton.enabled = true; } } } func setSeqStart(){ clearSeq() isSettingSeq = true settingSeqNo = 0 self.setSeqButton.enabled = false self.seqLab.hidden = false } func setSeqEnd(){ isSettingSeq = false self.setSeqButton.enabled = true updateSeqArrayInParse() settingSeqNo = 0 } func updateSeqArrayInParse(){ partyObj["sequence"] = self.seqArray partyObj.saveInBackground() } func getCorrespondingSeqLabel(number:Int) -> UILabel{ switch (number){ case 1: return self.seqLabel1 case 2: return self.seqLabel2 case 3: return self.seqLabel3 case 4: return self.seqLabel4 default: return self.seqLabel1 } } func addOneSeq(motion:String){ self.seqArray.append(motion) settingSeqNo = seqArray.count let currentLabel = getCorrespondingSeqLabel(settingSeqNo) currentLabel.hidden = false currentLabel.text = motion } func clearSeq(){ self.isSettingSeq = false self.seqLab.hidden = true self.setSeqButton.enabled = true self.settingSeqNo = -1 seqArray.removeAll() updateSeqArrayInParse() for index in 1...5{ getCorrespondingSeqLabel(index).hidden = true } } @IBAction func setSeqPressed(sender: AnyObject) { if (!isSettingSeq){ setSeqStart() } } @IBAction func clearSeqPressed(sender: UIButton) { clearSeq(); } func parseInit(){ let partyQuery = PFQuery(className: "Party"); partyQuery.whereKey("userId", equalTo:userObj); partyQuery.getFirstObjectInBackgroundWithBlock{ (obj: PFObject?, error: NSError?) -> Void in if (error != nil){ print ("Fetching party query failed") } else{ self.partyObj = obj! } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. motionInit() parseInit() } 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. } */ }
gpl-3.0
05fc5be4657cc6aef37d3efb7976999f
30.735099
173
0.557387
4.422704
false
false
false
false
epiphanyapps/ProductivitySuite
ProductivitySuite/Classes/Model/DataManager.swift
1
3462
// // DataManager.swift // Pods // // Created by Walter Vargas-Pena on 3/12/17. // // import UIKit import CoreData public let SharedDataManager = DataManager.sharedInstance enum SerializationError: Error { case missing(String) case invalid(String, Any) } ///http://stackoverflow.com/questions/29670585/how-to-convert-unix-epoc-time-to-date-and-time-in-ios-swift func unixEpocToDate(timeStamp: Double) -> Date { let epocTime = TimeInterval(timeStamp) / 1000 return Date(timeIntervalSince1970: epocTime) } public class DataManager: NSObject { static var sharedInstance = DataManager() lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let bundle = Bundle(for: type(of: self)) ///This is due to cocoapods packaging assets in another bundle let embeddedBundleURL = bundle.url(forResource: "ProductivitySuite", withExtension: "bundle")! let embeddedBundle = Bundle(url: embeddedBundleURL)! let modelURL = embeddedBundle.url(forResource: "ProductivitySuite", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("ProductivitySuite.sqlite") let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true] do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch(let error){ print("Something went wrong during initialatzion of persistent store. \(error)") abort() } return coordinator }() // MARK: - Context management lazy var rootContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) moc.persistentStoreCoordinator = coordinator return moc }() public lazy var managedObjectContext: NSManagedObjectContext = { var moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) moc.parent = self.rootContext return moc }() public func newWorkerContext() -> NSManagedObjectContext { let moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) moc.parent = self.managedObjectContext return moc } public func saveContext () { guard self.managedObjectContext.hasChanges else { return } DispatchQueue.main.sync() { do { try self.managedObjectContext.save() } catch let error as NSError { print("Unresolved error while saving main context \(error), \(error.userInfo)") } } self.rootContext.performAndWait { do { try self.rootContext.save() } catch let error as NSError { print("Unresolved error while saving to persistent store \(error), \(error.userInfo)") } } } }
mit
48b4ecc6fd73daecd920d5643234db26
35.829787
124
0.676776
5.317972
false
false
false
false
dsteinkopf/tuerauf
tuerauf/SettingsViewController.swift
1
7464
// // SettingsViewController.swift // tuerauf // // Created by Dirk Steinkopf on 26.01.15. // Copyright (c) 2015 Dirk Steinkopf. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { @IBOutlet var activityIndicator: UIActivityIndicatorView! @IBOutlet var usernameCell: UITableViewCell! @IBOutlet var pinEntryCell: UITableViewCell! @IBOutlet var usernameTextField: UITextField! @IBOutlet var pinEntryTextField: UITextField! @IBOutlet var saveButton: UIBarButtonItem! @IBOutlet var infoLabel: UILabel! @IBOutlet var bottomView: UIView! private var userRegistration: UserRegistration? private let userdefaults = NSUserDefaults.standardUserDefaults() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate userRegistration = appDelegate.userRegistration usernameTextField.addTarget(self, action: #selector(SettingsViewController.usernameTextFieldValueChanged(_:)), forControlEvents: UIControlEvents.EditingChanged) pinEntryTextField.addTarget(self, action: #selector(SettingsViewController.pinEntryTextFieldValueChanged(_:)), forControlEvents: UIControlEvents.EditingChanged) fillViews() } private func fillViews() { usernameTextField.text = userRegistration!.username; pinEntryTextField.text = userRegistration!.pin; usernameCell.accessoryType = userRegistration!.registered! ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None; pinEntryCell.accessoryType = userRegistration!.registered! ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None; usernameTextField.becomeFirstResponder() // bottomView.sizeToFit() bottomView.backgroundColor = UIColor.clearColor() infoLabel.text = "(C) eCube GmbH, Dirk Steinkopf\n\nDiese App basiert auf einem Arduino-Projekt.\nsiehe https://github.com/dsteinkopf/tuerauf\n\nDiese App dient lediglich zu Informations- und Weiterbildungszwecken. Sie ist nicht für den Produktivbetrieb gedacht. Der Anbieter der App stellt sie, so wie sie ist, zur Verfügung - ohne jeglichen Support oder Haftung für etwaige direkte oder indirekte Schäden." if let baseUrl = userdefaults.stringForKey("tueraufConfigBaseUrl") { infoLabel.text = infoLabel.text! + "\n\n\nBackend: " + baseUrl } infoLabel.numberOfLines = 0 infoLabel.sizeToFit() enableDisableSaveButton() } private func enableDisableSaveButton() { saveButton.enabled = (pinEntryTextField.text!.characters.count == 4 && Backend.sharedInstance.isConfigured()) } private func saveUservalues() { userRegistration!.username = usernameTextField.text userRegistration!.pin = pinEntryTextField.text userRegistration!.registered = false self.usernameCell.accessoryType = UITableViewCellAccessoryType.None self.pinEntryCell.accessoryType = UITableViewCellAccessoryType.None } private func saveRegistration() { userRegistration!.username = usernameTextField.text userRegistration!.pin = pinEntryTextField.text userRegistration!.registered = true self.usernameCell.accessoryType = UITableViewCellAccessoryType.Checkmark self.pinEntryCell.accessoryType = UITableViewCellAccessoryType.Checkmark } @IBAction func usernameTextFieldValueChanged(sender: AnyObject) { NSLog("usernameTextFieldValueChanged") self.usernameCell.accessoryType = UITableViewCellAccessoryType.None self.pinEntryCell.accessoryType = UITableViewCellAccessoryType.None } @IBAction func pinEntryTextFieldValueChanged(sender: AnyObject) { NSLog("pinEntryTextFieldValueChanged") self.usernameCell.accessoryType = UITableViewCellAccessoryType.None self.pinEntryCell.accessoryType = UITableViewCellAccessoryType.None enableDisableSaveButton() } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { usernameTextField.becomeFirstResponder() } } @IBAction func saveButtonPressed(sender: AnyObject) { NSLog("saveButtonPressed"); if pinEntryTextField.text!.characters.count != 4 { return } // let installationId = self.userRegistration!.installationId if self.userRegistration!.error != nil { let alert = UIAlertController(title: "Problem", message: "installationId nicht gespeichert", preferredStyle: UIAlertControllerStyle.Alert) // TODO add action? self.presentViewController(alert, animated: true, completion: nil) return } self.activityIndicator.startAnimating() Backend.sharedInstance.registerUser(usernameTextField.text!, pin:pinEntryTextField.text!, installationid: self.userRegistration!.installationId, completionHandler: { (hasBeenSaved, info) -> () in NSLog("registerUser returned: hasBeenSaved:%@ info=%@", hasBeenSaved, info) dispatch_async(dispatch_get_main_queue(), { self.activityIndicator.stopAnimating() if hasBeenSaved { self.saveRegistration() let alert = UIAlertController(title: "Alles gut", message: "Deine Info ist gespeichert. Bitte Admin Bescheid geben.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { action in NSLog("ok pressed - now perform segue") self.performSegueWithIdentifier("saveRegistration", sender: self) })) self.presentViewController(alert, animated: true, completion: nil) } else { self.saveUservalues() // username/Pin bleiben erhalten, auch wenn reg. fehlschlägt let alert = UIAlertController(title: "Nicht registriert", message: info, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }) }) } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { NSLog("shouldPerformSegueWithIdentifier: %@", identifier); return true; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "cancelToMainViewController" { NSLog("SettingsViewController.cancelToMainViewController") } else if segue.identifier == "saveRegistration" { NSLog("SettingsViewController.saveRegistration") // let destinationViewController = segue.destinationViewController } } }
gpl-3.0
40fc393c176873e92d9f14ef2410f24c
43.664671
416
0.684408
5.393348
false
false
false
false
ijoshsmith/swift-array-compression
compression.playground/Contents.swift
1
1597
import Foundation /** Returns a compacted array, with repeated values coalesced. Example: [a, a, b, c, c, c] yields [(a, 2), (b, 1), (c, 3)] */ func compressArray<T: Comparable>(input: [T]) -> [(T, Int)] { var output = [(T, Int)]() for element in input { if let (value, occurrences) = output.last where value == element { output[output.count - 1] = (element, occurrences + 1) } else { output.append((element, 1)) } } return output } /** Returns the original, expanded form of a compressed array. Example: [(a, 2), (b, 1), (c, 3)] yields [a, a, b, c, c, c] */ func decompressArray<T>(input: [(T, Int)]) -> [T] { return input.flatMap { (value, occurrences) in Repeat(count: occurrences, repeatedValue: value) } } let uncompressedInts = [ 8, 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 8, 3, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 9] let expectedCompressedArray = [ (8, 3), (2, 9), (8, 1), (3, 1), (5, 4), (0, 7), (9, 1)] let compressedArray = compressArray(uncompressedInts) let isCompressionCorrect = compressedArray.elementsEqual(expectedCompressedArray) { $0.0 == $1.0 && $0.1 == $1.1 } if isCompressionCorrect { print("Compression success!") } else { print("Compression failure: \(compressedArray)") } let decompressedArray = decompressArray(compressedArray) let isDecompressionCorrect = decompressedArray == uncompressedInts if isDecompressionCorrect { print("Decompression success!") } else { print("Decompression failure: \(decompressedArray)") }
mit
0d05a04352e0de1d4de9cc8b18a0dbc2
24.349206
83
0.602379
3.286008
false
false
false
false
anlaital/Swan
Swan/SwanTests/ArrayExtensionsTests.swift
1
819
// // ArrayExtensionsTests.swift // Swan // // Created by Antti Laitala on 10/07/15. // // import Swan import Foundation import XCTest class ArrayExtensionsTests: XCTestCase { func testHex() { let bytes: [UInt8] = [0x30, 0xA5, 0xBC] XCTAssert(bytes.hex() == "0x30 0xA5 0xBC") XCTAssert(bytes.hex(format: "%02x", separator: ", ") == "30, a5, bc") } func testRandom() { XCTAssert([].random() == nil) XCTAssert([5].random() == 5) let a = [5, 10, 15] XCTAssert(a.contains(a.random()!)) } func testRemove() { var a = [5, 10, 15] XCTAssert(a.remove(1) == nil) XCTAssert(a.remove(5) == 5) XCTAssert(a == [10, 15]) a.remove(10) a.remove(15) XCTAssert(a.isEmpty) } }
mit
63dfbd76e0deabd03d403cb5e206c8ad
20.552632
77
0.525031
3.262948
false
true
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Tools/UIImage+MTLTexture.swift
1
6332
// // UIImage+MTLTexture.swift // Pods // // Created by Mohammad Fathi on 3/10/16. // // #if !(TARGET_OS_SIMULATOR) import Metal import MetalKit #endif extension UIImage { func texture(_ device: MTLDevice) -> MTLTexture? { let textureLoader = MTKTextureLoader(device: device) guard let cgImage = self.cgImage else { print("Error loading CGImage") return nil } let options = [ MTKTextureLoader.Option.SRGB : NSNumber(value: false) ] return try? textureLoader.newTexture(cgImage: cgImage, options: options) } // func texture(_ device: MTLDevice) -> MTLTexture? { // return texture(device, flip: false, size: size) // } func texture(_ device: MTLDevice, flip: Bool, size: CGSize) -> MTLTexture? { var width: Int = Int(size.width) var height: Int = Int(size.height) if width == 0 { width = Int(self.size.width ) } if height == 0 { height = Int(self.size.height) } let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let (_, _, data) = imageData(with: CGSize(width: width, height: height)) let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false) guard let texture = device.makeTexture(descriptor: textureDescriptor) else { return nil } let region = MTLRegionMake2D(0, 0, width, height) texture.replace(region: region, mipmapLevel: 0, withBytes: data!, bytesPerRow: bytesPerRow) free(data) return texture } func rotationAngle(_ orientation: UIImageOrientation) -> CGFloat { var angle: CGFloat = 0.0 switch orientation { case .down : angle = 180.0; break case .right: angle = 90.0 ; break case .left : angle = 270.0; break default: break } return CGFloat.pi * angle / 180.0 } func imageData(with size: CGSize) -> (CGContext?, CGImage?, UnsafeMutableRawPointer?) { guard let cgImage = cgImage else { return (nil, nil, nil) } var transform: CGAffineTransform = .identity switch (imageOrientation) { case .down, .downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat.pi) break; case .left, .leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat.pi/2.0) break; case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: -CGFloat.pi/2.0) break; default: break; } switch (imageOrientation) { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) break; case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: size.height, y: 0) transform = transform.scaledBy(x: -1, y: 1) break; default: break; } // guard let context = CGContext(data: data, // width: Int(size.width), height: Int(size.height), // bitsPerComponent: cgImage.bitsPerComponent, // bytesPerRow: cgImage.bytesPerRow, // space: cgImage.colorSpace!, // bitmapInfo: cgImage.bitmapInfo.rawValue) else { return (nil, nil) } let width: Int = Int(size.width) let height: Int = Int(size.height) let rawData: UnsafeMutableRawPointer = calloc(height * width * 4, MemoryLayout<Int>.size) let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerCompoment = 8 let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue).union(CGBitmapInfo.byteOrder32Little) // CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).union(CGBitmapInfo.byteOrder32Big) let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerCompoment, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return (nil, nil, nil) } context.concatenate(transform) switch (self.imageOrientation) { case .left, .leftMirrored, .right, .rightMirrored: context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width)) default: context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height)) } return (context, context.makeImage(), rawData) } } func minMax(from pixelBuffer: CVPixelBuffer, format: MTLPixelFormat) -> (Float, Float) { let width = CVPixelBufferGetWidth(pixelBuffer) let height = CVPixelBufferGetHeight(pixelBuffer) let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly) let pixelBufferPointer = CVPixelBufferGetBaseAddress(pixelBuffer) guard var pointer = pixelBufferPointer?.assumingMemoryBound(to: Float.self) else { return (0.0, 0.0) } let increment = bytesPerRow/MemoryLayout<Float>.size // Check this var min = Float.greatestFiniteMagnitude var max = -Float.greatestFiniteMagnitude for _ in 0 ..< height { for i in 0 ..< width { let val = pointer[i] if !val.isNaN { if val > max { max = val } if val < min { min = val } } } pointer += increment } CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly) return (min, max) }
mit
f5c07c2aaaf8c1f7b0521c8e6467d382
33.983425
146
0.586702
4.782477
false
false
false
false
naukri-engineering/Blooper
ios/Blooper/Blooper/CoreData/Model/Crash.swift
1
3574
// // Crash.swift // Blooper // // Created by Ikjot Kaur on 14/01/16. // Copyright © 2016 Naukri. All rights reserved. // import Foundation import CoreData import UIKit class Crash: NSManagedObject { static private var context: NSManagedObjectContext! static private var fetchRequest: NSFetchRequest! static private var entity1: NSEntityDescription! private var error:NSError! static private var debuggingEnabled:Bool! class func initCrash(debug:Bool) { debuggingEnabled = debug NSSetUncaughtExceptionHandler { (exception:NSException) -> Void in Crash.saveCrash(exception.description) } WebServiceManager.uploadCrashToServer(debug) } private class func saveCrash(crashDescription:String) { if(debuggingEnabled == true) { print("Crash occured -> \(crashDescription)") } context = CoreDataHelper.sharedInstance().writerMOC let obj = NSEntityDescription.insertNewObjectForEntityForName(CRASH_ENTITY_NAME, inManagedObjectContext: context) as! Crash obj.crashDescription = crashDescription do { try context.save() CoreDataHelper.saveDataContext() if(debuggingEnabled == true) { print("Crash saved") } } catch{ if(debuggingEnabled == true) { print("Error occured while saving crash \(error)") } } } class func getCrash() -> NSArray { var fetchedObjects: [Crash]! context = CoreDataHelper.sharedInstance().mainMOC fetchRequest = NSFetchRequest() entity1 = NSEntityDescription.entityForName(CRASH_ENTITY_NAME, inManagedObjectContext: context) fetchRequest.entity = entity1 do { try fetchedObjects = context.executeFetchRequest(fetchRequest) as! [Crash] if(debuggingEnabled == true) { print("No of entitites fetched -> \(fetchedObjects.count)") } return fetchedObjects; } catch let error{ if(debuggingEnabled == true) { print("error occured while fetching entities -> \(error)") } } return NSArray() } class func deleteCrash() { var fetchedObjects: NSArray! context = CoreDataHelper.sharedInstance().managedObjectContext fetchRequest = NSFetchRequest() entity1 = NSEntityDescription.entityForName(CRASH_ENTITY_NAME, inManagedObjectContext: context) fetchRequest.entity = entity1 do { try fetchedObjects = context.executeFetchRequest(fetchRequest) for obj in fetchedObjects { context.deleteObject(obj as! NSManagedObject) } } catch let error{ if(debuggingEnabled == true) { print("Error occured while deleting the entities -> \(error)") } } do { try context.save() CoreDataHelper.saveDataContext() if(debuggingEnabled == true) { print(("Enitites successfully deleted")) } } catch let error{ if(debuggingEnabled == true) { print("Error occured while deleting the enitties -> \(error)") } } } }
mit
49c559d84252dc7a9f34e95ebd7c43d6
28.04878
131
0.565351
5.707668
false
false
false
false
fireflyexperience/BSImagePicker
Pod/Classes/Controller/ZoomAnimator.swift
1
5237
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 final class ZoomAnimator : NSObject, UIViewControllerAnimatedTransitioning { var sourceImageView: UIImageView? var destinationImageView: UIImageView? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // Get to and from view controller if let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let sourceImageView = sourceImageView, let destinationImageView = destinationImageView { // Disable selection so we don't select anything while the push animation is running fromViewController.view?.isUserInteractionEnabled = false // Get views let containerView = transitionContext.containerView // Setup views sourceImageView.isHidden = true destinationImageView.isHidden = true toViewController.view.alpha = 0.0 fromViewController.view.alpha = 1.0 containerView.backgroundColor = toViewController.view.backgroundColor // Setup scaling image let scalingFrame = containerView.convert(sourceImageView.frame, from: sourceImageView.superview) let scalingImage = UIImageViewModeScaleAspect(frame: scalingFrame) scalingImage.contentMode = sourceImageView.contentMode scalingImage.image = sourceImageView.image! //Init image scale let destinationFrame = toViewController.view.convert(destinationImageView.bounds, from: destinationImageView.superview) if destinationImageView.contentMode == .scaleAspectFit { scalingImage.initToScaleAspectFitToFrame(destinationFrame) } else { scalingImage.initToScaleAspectFillToFrame(destinationFrame) } // Add views to container view containerView.addSubview(toViewController.view) containerView.addSubview(scalingImage) // Animate UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: UIViewAnimationOptions(), animations: { () -> Void in // Fade in fromViewController.view.alpha = 0.0 toViewController.view.alpha = 1.0 if destinationImageView.contentMode == .scaleAspectFit { scalingImage.animaticToScaleAspectFit() } else { scalingImage.animaticToScaleAspectFill() } }, completion: { (finished) -> Void in // Finish image scaling and remove image view if destinationImageView.contentMode == .scaleAspectFit { scalingImage.animateFinishToScaleAspectFit() } else { scalingImage.animateFinishToScaleAspectFill() } scalingImage.removeFromSuperview() // Unhide destinationImageView.isHidden = false sourceImageView.isHidden = false fromViewController.view.alpha = 1.0 // Finish transition transitionContext.completeTransition(!transitionContext.transitionWasCancelled) // Enable selection again fromViewController.view?.isUserInteractionEnabled = true }) } } }
mit
908dc894803bbc5fb48a0783a1b448ef
48.346154
315
0.623568
6.338983
false
false
false
false
Teleglobal/MHQuickBlockLib
MHQuickBlockLib/Classes/ContactServiceManager.swift
1
16721
// // AppContacts.swift // Pods // // Created by Muhammad Adil on 10/5/16. // // import Quickblox import RealmSwift import Realm open class ContactServiceManager : NSObject { /** * * */ private let UserTags = "UserTags" // MARK:- Delegates Managment /** * * */ open var contactDelegates : [ContactServiceDelegate] = [] /** * * */ open func addContactDelegate(_ contactDelegate: ContactServiceDelegate) { for i in 0..<contactDelegates.count { let object: ContactServiceDelegate = contactDelegates[i] if (object === contactDelegate) { return } } contactDelegates.append(contactDelegate) } /** * * */ open func removeContactDelegate(_ contactDelegate: ContactServiceDelegate) { for i in 0..<contactDelegates.count { let object: ContactServiceDelegate = contactDelegates[i] if (object === contactDelegate) { contactDelegates.remove(at: i) return } } } /** * * */ internal func removeAllContactDelegates() { self.contactDelegates.removeAll() } // MARK:- Fetch Contacts from Server /** * * */ open func getCountOfContactsInPractice() { QBRequest.countObjects(withClassName: self.UserTags, extendedRequest: ["tags[in]" : Messenger.tags], successBlock: { (response, count) in if (count > 0) { self.fetchAllContacts(1, totalCount: count) } }) { (error) in print(error) } } /** * * */ internal func fetchAllContacts(_ page: UInt = 1, totalCount : UInt = 0, skip : UInt = 0) { let request: ()->() = { QBRequest.objects(withClassName: "UserTags", extendedRequest: ["tags[in]" : Messenger.tags, "limit" : PageLimit, "skip" : skip], successBlock: { (response, contacts, responsePage) in for contact in contacts! { if (contact.userID != Messenger.chatAuthServiceManager.currentUser()?.id) { self.fetchContactWithId(contact.userID) } } let accountFetched = UInt(PageLimit) * page if (totalCount > accountFetched) { let accountsToSkip = (UInt(PageLimit) * (page + 1)) self.fetchAllContacts(page, totalCount: totalCount, skip: accountsToSkip) } }, errorBlock: { (response) in print(response) }) } DispatchQueue(label: "accountFetch", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil).async { request() } } /** * * */ open func fetchContactWithId(_ userId: UInt) { let request: ()->() = { QBRequest.user(withID: userId, successBlock: { (response, user) in self.sendContactRequest(user.id) let realm = try! Realm() try! realm.write { realm.add(self.qbUserToLocalContact(user), update: true) } for delegate in self.contactDelegates { delegate.contactUpdatedInStorage(user.id) } }, errorBlock: { (error) in }) } DispatchQueue(label: "accountFetch", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil).async { request() } } /** * * */ open func fetchContactWithIds(_ userIds: [UInt]) { for userId in userIds { self.fetchContactWithId(userId) } } // MARK:- Private Methods /** * * */ private func sendContactRequest(_ userId: UInt) { QBChat.instance.addUser(toContactListRequest: userId, completion: {(error) in if (error != nil) { print("Unable to send contact request") } }) } /** * * */ fileprivate func rejectContactRequest(_ userId: UInt) { QBChat.instance.rejectAddContactRequest(userId, completion: { (error) in if (error == nil) { self.deleteContact(userId) } }) } /** * * */ fileprivate func acceptContactRequest(_ userId: UInt) { QBChat.instance.confirmAddContactRequest(userId) { (error) in if (error == nil) { self.fetchContactWithId(userId) } } } /** * * */ open func deleteContact(_ userId: UInt) { QBChat.instance.removeUser(fromContactList: userId, completion: { (error) in if (error == nil) { if let contact = self.contactInMemoryWithContactId("\(userId)") { let realm = try! Realm() try! realm.write { realm.delete(contact) } for delegate in self.contactDelegates { delegate.contactsUpdatedInStorage() } } } }); } /** * * */ fileprivate func saveContacts(_ contactsObjects: [AnyObject]) { for _contact in contactsObjects { // TODO:- Remove this print print line print(_contact.userID) let contact = Contact() contact.userID = String(describing: _contact.userID) // Get the default Realm let realm = try! Realm() // You only need to do this once (per thread) // Add to the Realm inside a transaction try! realm.write { realm.add(contact, update: true) } } for delegate in contactDelegates { delegate.contactsUpdatedInStorage() } } /** * * */ fileprivate func qbUserToLocalContact(_ user_: QBUUser) -> Contact { let contact = Contact() contact.customData = user_.customData contact.externalUserID = "\(user_.externalUserID)" contact.fullName = user_.fullName contact.lastRequestAt = user_.lastRequestAt contact.userID = "\(user_.id)" for tag in user_.tags! { contact.tags.append(StringObject(value: [tag])) } return contact } // MARK:- In-Memory Fetch Requests /** * * */ private func contactsInMemory() -> Results<Contact>? { let realm = try! Realm() return realm.objects(Contact.self).sorted(byKeyPath: "online", ascending: false) } /** * * */ open func contactsInMemory() -> [Contact]? { let contacts : Results<Contact> = self.contactsInMemory()! return Array(contacts) } /** * * */ private func providerContactsInMemory(_ online: Bool = false, nameFilter: String = "") -> Results<Contact>? { // Patient, Guest, Care Giver let containsPredicate = NSPredicate(format: "fullName contains[c] %@", nameFilter) let tagsPredicate = NSPredicate(format: "ANY tags.value != 'patient' AND ANY tags.value != 'Patient' AND ANY tags.value != 'guest' AND ANY tags.value != 'Guest' AND ANY tags.value != 'caregiver' AND ANY tags.value != 'CareGiver'") var onlinePredicate : NSPredicate = NSPredicate(format: "online = true OR online = false") if (online) { onlinePredicate = NSPredicate(format: "online = \(online)") } let sortProperties = [SortDescriptor(keyPath: "online", ascending: false), SortDescriptor(keyPath: "idle", ascending: false), SortDescriptor(keyPath: "lastRequestAt", ascending: false), ] let realm = try! Realm() return realm.objects(Contact.self) .filter(tagsPredicate) .filter(containsPredicate) .filter(onlinePredicate) .sorted(by: sortProperties) } /** * * */ open func providerContactsInMemory(_ nameFilter: String = "") -> [Contact]? { let contacts : Results<Contact> = self.providerContactsInMemory(false, nameFilter: nameFilter)! return Array(contacts) } /** * * */ open func contactInMemoryWithContactId(_ contactId: String) -> Contact? { let predicate = NSPredicate(format: "userID = %@", contactId) let realm = try! Realm() return realm.objects(Contact.self).filter(predicate).first } /** * * */ open func contactInMemoryWithexternalUserID(_ externalUserID: String) -> Contact? { let predicate = NSPredicate(format: "externalUserID = %@", externalUserID) let realm = try! Realm() return realm.objects(Contact.self).filter(predicate).first } /** * * */ open func onlineProvidersInMemory(_ online: Bool = true, nameFilter: String = "") -> [Contact]? { let contacts : Results<Contact> = self.providerContactsInMemory(online, nameFilter: nameFilter)! return Array(contacts) } /** * * */ open func contactsInMemoryWithContactIds(_ Ids: [String]) -> [Contact]? { let realm = try! Realm() let contacts = realm.objects(Contact.self).filter("userID IN %@", Ids).sorted(byKeyPath: "userID") return Array(contacts) } // MARK:- Internal Methods internal func markAllContactsOffline() { let contacts: Results<Contact> = self.contactsInMemory()! for contact in contacts { let realm = try! Realm() try! realm.write { contact.online = false realm.add(contact, update: true) } } for delegate in self.contactDelegates { delegate.contactsUpdatedInStorage() } } public func updateContactStatus(_ userID: UInt, isOnline: Bool, isIdle: Bool) { if let contact = self.contactInMemoryWithContactId(String(describing: userID)) { let realm = try! Realm() try! realm.write { contact.online = isOnline contact.idle = isIdle realm.add(contact, update: true) } } } } // MARK:- QBChatDelegate extension ContactServiceManager : QBChatDelegate { /** * Called in case contact request was received. * * @param userID User ID from received contact request */ public func chatDidReceiveContactAddRequest(fromUser userID: UInt) { self.acceptContactRequest(userID) } /** * Called whenver contact list was changed. */ public func chatContactListDidChange(_ contactList: QBContactList) { } /** * Called in case when user's from contact list online status has been changed. * * @param userID User which online status has changed * @param isOnline New user status (online or offline) * @param status Custom user status */ public func chatDidReceiveContactItemActivity(_ userID: UInt, isOnline: Bool, status: String?) { if (Messenger.chatAuthServiceManager.isConnected()) { if let contact = self.contactInMemoryWithContactId(String(describing: userID)) { if (contact.online != isOnline) { let realm = try! Realm() try! realm.write { contact.online = isOnline realm.add(contact, update: true) for delegate in self.contactDelegates { delegate.contactUpdatedInStorage(userID) } } } } } } /** * Called whenever user has accepted your contact request. * * @param userID User ID who did accept your contact request */ public func chatDidReceiveAcceptContactRequest(fromUser userID: UInt) { self.fetchContactWithId(userID) } /** * Called whenever user has rejected your contact request. * * @param userID User ID who did reject your contact reqiest */ public func chatDidReceiveRejectContactRequest(fromUser userID: UInt) { self.deleteContact(userID) } /** * Called in case of receiving presence with status. * * @param status Recieved presence status * @param userID User ID who did send presence */ public func chatDidReceivePresence(withStatus status: String, fromUser userID: Int) { } public func chatDidReceiveSystemMessage(_ message: QBChatMessage) { print(message) } }
mit
ac452a2df791263fae780396edd2786d
28.699822
238
0.426111
6.027758
false
false
false
false
goodwall/ObjectMapper
ObjectMapper/Core/Mapper.swift
1
13504
// // Mapper.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol Mappable { static func newInstance(map: Map) -> Mappable? mutating func mapping(map: Map) } public enum MappingType { case FromJSON case ToJSON } /// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects public final class Mapper<N: Mappable> { public init(){} // MARK: Mapping functions that map to an existing object toObject /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is public func map(JSON: AnyObject?, toObject object: N) -> N { if let JSON = JSON as? [String : AnyObject] { return map(JSON, toObject: object) } return object } /// Map a JSON string onto an existing object public func map(JSONString: String, toObject object: N) -> N { if let JSON = parseJSONDictionary(JSONString) { return map(JSON, toObject: object) } return object } /// Maps a JSON dictionary to an existing object that conforms to Mappable. /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject public func map(JSONDictionary: [String : AnyObject], var toObject object: N) -> N { let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, toObject: true) object.mapping(map) return object } //MARK: Mapping functions that create an object /// Map an optional JSON string to an object that conforms to Mappable public func map(JSONString: String?) -> N? { if let JSONString = JSONString { return map(JSONString) } return nil } /// Map a JSON string to an object that conforms to Mappable public func map(JSONString: String) -> N? { if let JSON = parseJSONDictionary(JSONString) { return map(JSON) } return nil } /// Map a JSON NSString to an object that conforms to Mappable public func map(JSONString: NSString) -> N? { return map(JSONString as String) } /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. public func map(JSON: AnyObject?) -> N? { if let JSON = JSON as? [String : AnyObject] { return map(JSON) } return nil } /// Maps a JSON dictionary to an object that conforms to Mappable public func map(JSONDictionary: [String : AnyObject]) -> N? { let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary) if var object = N.newInstance(map) as? N { object.mapping(map) return object } return nil } // MARK: Mapping functions for Arrays and Dictionaries /// Maps a JSON array to an object that conforms to Mappable public func mapArray(JSONString: String) -> [N]? { let parsedJSON: AnyObject? = parseJSONString(JSONString) if let objectArray = mapArray(parsedJSON) { return objectArray } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(parsedJSON) { return [object] } return nil } /// Maps a optional JSON String into an array of objects that conforms to Mappable public func mapArray(JSONString: String?) -> [N]? { if let JSONString = JSONString { return mapArray(JSONString) } return nil } /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapArray(JSON: AnyObject?) -> [N]? { if let JSONArray = JSON as? [[String : AnyObject]] { return mapArray(JSONArray) } return nil } /// Maps an array of JSON dictionary to an array of Mappable objects public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]? { // map every element in JSON array to type N let result = JSONArray.flatMap(map) return result } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSON: AnyObject?) -> [String : N]? { if let JSONDictionary = JSON as? [String : [String : AnyObject]] { return mapDictionary(JSONDictionary) } return nil } /// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N]? { // map every value in dictionary to type N let result = JSONDictionary.filterMap(map) if result.isEmpty == false { return result } return nil } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String : N]) -> [String : N] { if let JSONDictionary = JSON as? [String : [String : AnyObject]] { return mapDictionary(JSONDictionary, toDictionary: dictionary) } return dictionary } /// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects public func mapDictionary(JSONDictionary: [String : [String : AnyObject]], var toDictionary dictionary: [String : N]) -> [String : N] { for (key, value) in JSONDictionary { if let object = dictionary[key] { Mapper().map(value, toObject: object) } else { dictionary[key] = Mapper().map(value) } } return dictionary } /// Maps a JSON object to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? { if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] { return mapDictionaryOfArrays(JSONDictionary) } return nil } ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]]? { // map every value in dictionary to type N let result = JSONDictionary.filterMap { mapArray($0) } if result.isEmpty == false { return result } return nil } /// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects public func mapArrayOfArrays(JSON: AnyObject?) -> [[N]]? { if let JSONArray = JSON as? [[[String : AnyObject]]] { var objectArray = [[N]]() for innerJSONArray in JSONArray { if let array = mapArray(innerJSONArray){ objectArray.append(array) } } if objectArray.isEmpty == false { return objectArray } } return nil } // MARK: Private utility functions for converting strings to JSON objects /// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization private func parseJSONDictionary(JSON: String) -> [String : AnyObject]? { let parsedJSON: AnyObject? = parseJSONString(JSON) return parseJSONDictionary(parsedJSON) } /// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization private func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? { if let JSONDict = JSON as? [String : AnyObject] { return JSONDict } return nil } /// Convert a JSON String into an Object using NSJSONSerialization private func parseJSONString(JSON: String) -> AnyObject? { let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) if let data = data { let parsedJSON: AnyObject? do { parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) } catch let error { print(error) parsedJSON = nil } return parsedJSON } return nil } } extension Mapper { // MARK: Functions that create JSON from objects ///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject> public func toJSON(var object: N) -> [String : AnyObject] { let map = Map(mappingType: .ToJSON, JSONDictionary: [:]) object.mapping(map) return map.JSONDictionary } ///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]] public func toJSONArray(array: [N]) -> [[String : AnyObject]] { return array.map { // convert every element in array to JSON dictionary equivalent self.toJSON($0) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] { return dictionary.map { k, v in // convert every value in dictionary to its JSON dictionary equivalent return (k, self.toJSON(v)) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] { return dictionary.map { k, v in // convert every value (array) in dictionary to its JSON dictionary equivalent return (k, self.toJSONArray(v)) } } /// Maps an Object to a JSON string public func toJSONString(object: N) -> String? { return toJSONString(object, prettyPrint: false) } /// Maps an Object to a JSON string with option of pretty formatting public func toJSONString(object: N, prettyPrint: Bool) -> String? { let JSONDict = toJSON(object) return toJSONString(JSONDict, prettyPrint: prettyPrint) } /// Maps an array of Objects to a JSON string public func toJSONString(array: [N]) -> String? { return toJSONString(array, prettyPrint: false) } /// Maps an array of Objects to a JSON string with option of pretty formatting public func toJSONString(array: [N], prettyPrint: Bool) -> String? { let JSONDict = toJSONArray(array) return toJSONString(JSONDict, prettyPrint: prettyPrint) } private func toJSONString(object: AnyObject, prettyPrint: Bool) -> String? { if NSJSONSerialization.isValidJSONObject(object) { let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : [] let JSONData: NSData? do { JSONData = try NSJSONSerialization.dataWithJSONObject(object, options: options) } catch let error { print(error) JSONData = nil } if let JSON = JSONData { return String(data: JSON, encoding: NSUTF8StringEncoding) } } return nil } } extension Mapper where N: Hashable { /// Maps a JSON array to an object that conforms to Mappable public func mapSet(JSONString: String) -> Set<N>? { let parsedJSON: AnyObject? = parseJSONString(JSONString) if let objectArray = mapArray(parsedJSON){ return Set(objectArray) } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(parsedJSON) { return Set([object]) } return nil } /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapSet(JSON: AnyObject?) -> Set<N>? { if let JSONArray = JSON as? [[String : AnyObject]] { return mapSet(JSONArray) } return nil } /// Maps an Set of JSON dictionary to an array of Mappable objects public func mapSet(JSONArray: [[String : AnyObject]]) -> Set<N> { // map every element in JSON array to type N return Set(JSONArray.flatMap(map)) } ///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]] public func toJSONSet(set: Set<N>) -> [[String : AnyObject]] { return set.map { // convert every element in set to JSON dictionary equivalent self.toJSON($0) } } } extension Dictionary { internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] { var mapped = [K : V]() for element in self { let newElement = f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] { var mapped = [K : [V]]() for element in self { let newElement = f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] { var mapped = [Key : U]() for (key, value) in self { if let newValue = f(value){ mapped[key] = newValue } } return mapped } }
mit
0bfba2eb466cfcb73dba08a91adabd54
29.901602
139
0.684168
4.008311
false
false
false
false
Stamates/30-Days-of-Swift
src/Day 8 - Dictionaries and Arrays.playground/section-1.swift
2
864
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var myStorage = [String:AnyObject]() var bookDictionary = [String:String]() myStorage["computer"] = "A device that does stuff" // var theComputer = myStorage["computer"] myStorage["computerSpeed"] = 1000.00 myStorage["computerSpeed2"] = 1230.120 myStorage.count //for someVar in 0..<myStorage.count{ // println(someVar) //} for (key, value) in myStorage { // println(key) // println(value) // println(myStorage[key]) var num = myStorage[key] as? Double println(num) var str = myStorage[key] as? String println(str) if (num != nil) { println(num! * 3) } else if (str != nil) { println(str!) println("The \(key): \(str!).") } else { println("Is not a string or Integer") } }
apache-2.0
c7a7f9deee61ed52521b55a3da3f1712
20.625
51
0.614583
3.540984
false
false
false
false
suragch/MongolAppDevelopment-iOS
Mongol App Componants/KeyboardKeyDemoVC.swift
1
2969
import UIKit class KeyboardKeyDemoVC: UIViewController, KeyboardKeyDelegate { let codeKey = KeyboardTextKey(frame: CGRect.zero) let renderer = MongolUnicodeRenderer.sharedInstance @IBOutlet weak var button: UIButton! @IBAction func buttonTapped(_ sender: UIButton) { storyboardKey.primaryStringFontSize = 25 storyboardKey.primaryString = "ᠮᠣᠩᠭᠤᠯ" storyboardKey.primaryStringDisplayOverride = renderer.unicodeToGlyphs("ᠮᠣᠩᠭᠤᠯ") } @IBOutlet weak var storyboardKey: KeyboardTextKey! override func viewDidLoad() { super.viewDidLoad() // code key codeKey.delegate = self view.addSubview(codeKey) // storyboard key setup storyboardKey.delegate = self storyboardKey.primaryString = MongolUnicodeRenderer.UniString.NA storyboardKey.secondaryString = MongolUnicodeRenderer.UniString.UE let ueOverride = MongolUnicodeRenderer.UniString.UE + MongolUnicodeRenderer.UniString.ZWJ storyboardKey.secondaryStringDisplayOverride = renderer.unicodeToGlyphs(ueOverride) storyboardKey.primaryStringFontSize = 60 storyboardKey.secondaryStringFontSize = 20 storyboardKey.cornerRadius = 100 // code key setup let margin: CGFloat = 30.0 codeKey.frame = CGRect(x: margin, y: margin + 80, width: 100, height: 150.0) codeKey.primaryString = MongolUnicodeRenderer.UniString.GA codeKey.secondaryString = MongolUnicodeRenderer.UniString.NA codeKey.primaryStringFontSize = 60 codeKey.secondaryStringFontSize = 20 codeKey.cornerRadius = 20 codeKey.addTarget(self, action: #selector(codeKeyTapped(_:)), for: UIControlEvents.touchUpInside) // button //let backgroundLayer = KeyboardKeyBackgroundLayer() //backgroundLayer.frame = button.bounds //button.backgroundColor = UIColor.clearColor() // button.layer.addSublayer(backgroundLayer) } // MARK: - Optional methods func codeKeyTapped(_ key: KeyboardKey) { print("Code Key tapped") } @IBAction func storyboardKeyTapped(_ sender: KeyboardKey) { print("Storyboard Key tapped") } // MARK: - KeyboardKeyDelegate protocol func keyTextEntered(_ keyText: String) { print("key text: \(keyText)") } func keyBackspaceTapped() { print("backspace tapped") } func keyFvsTapped(_ fvs: String) { print("key text: fvs") } func keyKeyboardTapped() { // for keyboard chooser key } func keyNewKeyboardChosen(_ keyboardName: String) { // for keyboard chooser key } func otherAvailableKeyboards(_ displayNames: [String]) { // for keyboard chooser key } }
mit
372a3897b87a7551f68cf10316862c77
29.677083
105
0.640407
4.682035
false
false
false
false
eoger/firefox-ios
Client/Frontend/Browser/FindInPageBar.swift
1
7597
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit protocol FindInPageBarDelegate: AnyObject { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) func findInPageDidPressClose(_ findInPage: FindInPageBar) } private struct FindInPageUX { static let ButtonColor = UIColor.black static let MatchCountColor = UIColor.Photon.Grey40 static let MatchCountFont = UIConstants.DefaultChromeFont static let SearchTextColor = UIColor.Photon.Orange60 static let SearchTextFont = UIConstants.DefaultChromeFont static let TopBorderColor = UIColor.Photon.Grey20 } class FindInPageBar: UIView { weak var delegate: FindInPageBarDelegate? fileprivate let searchText = UITextField() fileprivate let matchCountView = UILabel() fileprivate let previousButton = UIButton() fileprivate let nextButton = UIButton() var currentResult = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } } } var totalResults = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } previousButton.isEnabled = totalResults > 1 nextButton.isEnabled = previousButton.isEnabled } } var text: String? { get { return searchText.text } set { searchText.text = newValue didTextChange(searchText) } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white searchText.addTarget(self, action: #selector(didTextChange), for: .editingChanged) searchText.textColor = FindInPageUX.SearchTextColor searchText.font = FindInPageUX.SearchTextFont searchText.autocapitalizationType = .none searchText.autocorrectionType = .no searchText.inputAssistantItem.leadingBarButtonGroups = [] searchText.inputAssistantItem.trailingBarButtonGroups = [] searchText.enablesReturnKeyAutomatically = true searchText.returnKeyType = .search searchText.accessibilityIdentifier = "FindInPage.searchField" searchText.delegate = self addSubview(searchText) matchCountView.textColor = FindInPageUX.MatchCountColor matchCountView.font = FindInPageUX.MatchCountFont matchCountView.isHidden = true matchCountView.accessibilityIdentifier = "FindInPage.matchCount" addSubview(matchCountView) previousButton.setImage(UIImage(named: "find_previous"), for: []) previousButton.setTitleColor(FindInPageUX.ButtonColor, for: []) previousButton.accessibilityLabel = NSLocalizedString("Previous in-page result", tableName: "FindInPage", comment: "Accessibility label for previous result button in Find in Page Toolbar.") previousButton.addTarget(self, action: #selector(didFindPrevious), for: .touchUpInside) previousButton.accessibilityIdentifier = "FindInPage.find_previous" addSubview(previousButton) nextButton.setImage(UIImage(named: "find_next"), for: []) nextButton.setTitleColor(FindInPageUX.ButtonColor, for: []) nextButton.accessibilityLabel = NSLocalizedString("Next in-page result", tableName: "FindInPage", comment: "Accessibility label for next result button in Find in Page Toolbar.") nextButton.addTarget(self, action: #selector(didFindNext), for: .touchUpInside) nextButton.accessibilityIdentifier = "FindInPage.find_next" addSubview(nextButton) let closeButton = UIButton() closeButton.setImage(UIImage(named: "find_close"), for: []) closeButton.setTitleColor(FindInPageUX.ButtonColor, for: []) closeButton.accessibilityLabel = NSLocalizedString("Done", tableName: "FindInPage", comment: "Done button in Find in Page Toolbar.") closeButton.addTarget(self, action: #selector(didPressClose), for: .touchUpInside) closeButton.accessibilityIdentifier = "FindInPage.close" addSubview(closeButton) let topBorder = UIView() topBorder.backgroundColor = FindInPageUX.TopBorderColor addSubview(topBorder) searchText.snp.makeConstraints { make in make.leading.top.bottom.equalTo(self).inset(UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)) } searchText.setContentHuggingPriority(.defaultLow, for: .horizontal) searchText.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) matchCountView.snp.makeConstraints { make in make.leading.equalTo(searchText.snp.trailing) make.centerY.equalTo(self) } matchCountView.setContentHuggingPriority(.defaultHigh, for: .horizontal) matchCountView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) previousButton.snp.makeConstraints { make in make.leading.equalTo(matchCountView.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } nextButton.snp.makeConstraints { make in make.leading.equalTo(previousButton.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } closeButton.snp.makeConstraints { make in make.leading.equalTo(nextButton.snp.trailing) make.size.equalTo(self.snp.height) make.trailing.centerY.equalTo(self) } topBorder.snp.makeConstraints { make in make.height.equalTo(1) make.left.right.top.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult override func becomeFirstResponder() -> Bool { searchText.becomeFirstResponder() return super.becomeFirstResponder() } @objc fileprivate func didFindPrevious(_ sender: UIButton) { delegate?.findInPage(self, didFindPreviousWithText: searchText.text ?? "") } @objc fileprivate func didFindNext(_ sender: UIButton) { delegate?.findInPage(self, didFindNextWithText: searchText.text ?? "") } @objc fileprivate func didTextChange(_ sender: UITextField) { matchCountView.isHidden = searchText.text?.trimmingCharacters(in: .whitespaces).isEmpty ?? true delegate?.findInPage(self, didTextChange: searchText.text ?? "") } @objc fileprivate func didPressClose(_ sender: UIButton) { delegate?.findInPageDidPressClose(self) } } extension FindInPageBar: UITextFieldDelegate { // Keyboard with a .search returnKeyType doesn't dismiss when return pressed. Handle this manually. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { textField.resignFirstResponder() return false } return true } }
mpl-2.0
3f38bb640fa7426481e8131d1606d5bb
39.844086
197
0.681453
5.323756
false
false
false
false
mlilback/rc2SwiftClient
ClientCore/help/HelpController.swift
1
7233
// // HelpController.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Rc2Common import Foundation import MJLLogger import GRDB import ZIPFoundation import ReactiveSwift private let currentHelpVersion = 4 public class HelpController { let helpUrlFuncSeperator = "/html" static public let shared = HelpController() private let dbQueue: DatabaseQueue public let packages: [HelpTopic] public let allTopics: Set<HelpTopic> public let allTopicNames: Set<String> fileprivate let topicsByName: [String: [HelpTopic]] fileprivate var rootHelpUrl: URL public private(set) var baseHelpUrl: URL private let verified = Atomic<Bool>(false) ///loads topics from storage public init() { guard let dbpath = Bundle(for: type(of: self)).path(forResource: "helpindex", ofType: "db") else { fatalError("helpindex resource missing") } do { //load help index dbQueue = try DatabaseQueue(path: dbpath) var topsByPack = [String: [HelpTopic]]() var topsByName = [String: [HelpTopic]]() var all = Set<HelpTopic>() var names = Set<String>() try dbQueue.inDatabase { db in let rawRows = try Row.fetchAll(db, sql: "select rowid,package,name,topicname,title,aliases,desc from helptopic where name not like '.%' order by package, name COLLATE nocase") for row in rawRows { guard let package: String = row["package"] else { continue } let topic = HelpTopic(id: row["rowid"], name: row["name"], packageName: package, fileName: row["topicname"], title: row["title"], aliases: row["aliases"], description: row["desc"]) if topsByPack[package] == nil { topsByPack[package] = [] } topsByPack[package]!.append(topic) all.insert(topic) for anAlias in (topic.aliases! + [topic.name]) { names.insert(anAlias) if var atops = topsByName[anAlias] { atops.append(topic) } else { topsByName[anAlias] = [topic] } } } } var packs: [HelpTopic] = [] topsByPack.forEach { (pair) in let package = HelpTopic(name: pair.key, subtopics: pair.value.sorted(by: { return $0.compare($1) })) packs.append(package) } self.packages = packs.sorted(by: { return $0.compare($1) }) self.allTopics = all self.allTopicNames = names self.topicsByName = topsByName // ensure help files are installed rootHelpUrl = try AppInfo.subdirectory(type: .applicationSupportDirectory, named: "rdocs") baseHelpUrl = rootHelpUrl.appendingPathComponent("helpdocs/library", isDirectory: true) verifyDocumentationInstallation() } catch { Log.error("error loading help index: \(error)", .app) fatalError("failed to load help index") } } /// checks to make sure help files exist and if not, extract them from tarball public func verifyDocumentationInstallation() { if verified.value { return } defer { verified.value = true } let versionUrl = rootHelpUrl.appendingPathComponent("rc2help.json") // check to see if correct version installed if versionUrl.fileExists(), let vdata = try? Data(contentsOf: versionUrl), let vinfo = try? JSONDecoder().decode(HelpInfo.self, from: vdata), vinfo.version >= currentHelpVersion { return } // need to install do { let fm = FileManager() if versionUrl.fileExists() { // zip won't onverwrite, so nuke existing try fm.removeItem(at: rootHelpUrl) try fm.createDirectory(at: rootHelpUrl, withIntermediateDirectories: true, attributes: nil) } let archive = Bundle(for: type(of: self)).url(forResource: "help", withExtension: "zip")! DispatchQueue.global().async { [rootHelpUrl] in do { try fm.unzipItem(at: archive, to: rootHelpUrl) Log.info("help extracted", .app) } catch { fatalError("error unzipping help: \(error)") } } } catch { fatalError("failed to read help.zip from app bundle") } } /// returns true if there is a help topic with the specified name public func hasTopic(_ name: String) -> Bool { return allTopicNames.contains(name) } public func topic(withId topicId: Int) -> HelpTopic? { return allTopics.first(where: { $0.topicId == topicId }) } fileprivate func parse(rows: [Row]) throws -> [HelpTopic] { var topicsByPack = [String: [HelpTopic]]() for row in rows { guard let package: String = row["package"] else { continue } let topic = HelpTopic(name: row["name"], packageName: package, fileName: row["topicname"], title: row["title"], aliases: row["aliases"], description: row["desc"]) if topicsByPack[package] == nil { topicsByPack[package] = [] } topicsByPack[package]!.append(topic) } let matches: [HelpTopic] = topicsByPack.map { pair in return HelpTopic(name: pair.key, subtopics: pair.value) } return matches.sorted(by: { return $0.compare($1) }) } /// returns a list of HelpTopics that contain the searchString in their title public func searchTitles(_ searchString: String) -> [HelpTopic] { let results = allTopics.filter { $0.name.localizedCaseInsensitiveContains(searchString) } var topicsByPack = [String: [HelpTopic]]() for aMatch in results { if topicsByPack[aMatch.packageName] == nil { topicsByPack[aMatch.packageName] = [] } topicsByPack[aMatch.packageName]!.append(aMatch) } let matches: [HelpTopic] = topicsByPack.map { pair in return HelpTopic(name: pair.key, subtopics: pair.value) } return matches.sorted(by: { return $0.compare($1) }) } /// returns a list of HelpTpics that contain the searchString in their title or summary public func searchTopics(_ searchString: String) -> [HelpTopic] { guard searchString.count > 0 else { return packages } var results: [HelpTopic] = [] var rows: [Row] = [] do { try dbQueue.inDatabase { db in rows = try Row.fetchAll(db, sql: "select * from helpidx where helpidx match ?", arguments: [searchString]) } results = try parse(rows: rows) } catch { Log.warn("error searching help: \(error)", .app) } return results } //can't share code with initializer because functions can't be called in init before all properties are assigned public func topicsWithName(_ targetName: String) -> [HelpTopic] { var packs: [HelpTopic] = [] var topsByPack = [String: [HelpTopic]]() topicsByName[targetName]?.forEach { aTopic in if var existPacks = topsByPack[aTopic.packageName] { existPacks.append(aTopic) topsByPack[aTopic.name] = existPacks } else { topsByPack[aTopic.packageName] = [aTopic] } } topsByPack.forEach { (arg) in let package = HelpTopic(name: arg.key, subtopics: arg.value.sorted(by: { return $0.compare($1) })) packs.append(package) } packs = packs.reduce([], { (pks, ht) in var myPacks = pks if ht.subtopics != nil { myPacks.append(contentsOf: ht.subtopics!) } return myPacks }) packs = packs.sorted(by: { return $0.compare($1) }) return packs } public func urlForTopic(_ topic: HelpTopic) -> URL { let str = "\(topic.packageName)\(helpUrlFuncSeperator)/\(topic.fileName!).html" let helpUrl = baseHelpUrl.appendingPathComponent(str) if !helpUrl.fileExists() { Log.info("missing help file: \(str)", .app) } return helpUrl } private struct HelpInfo: Codable { let version: Int } }
isc
23bcc985d3484e70ae9a7c74507c7685
34.45098
185
0.689159
3.453677
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClientIntegrationTests/TestUtils/Offline Testing/RecorderTestSender.swift
1
3054
// // APIClientError.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 @testable import CreatubblesAPIClient class RecorderTestSender: RequestSender { var isLoggedIn: Bool? override func send(_ request: Request, withResponseHandler handler: ResponseHandler) -> RequestHandler { let fileName = TestRecorderNameUtils.filenameForRequest(request: request, isLoggedIn: isLoggedIn) let filePath = TestRecorderNameUtils.getInputFilePathForFileName(fileName: fileName) let recorderHandler = RecorderResponseHandler(originalHandler: handler, fileToSavePath: filePath, isLoggedIn: isLoggedIn) if TestConfiguration.mode == .useRecordedResponses { let testRecorder = TestRecorder(isLoggedIn: isLoggedIn) return testRecorder.handleRequest(request: request, recorderHandler: recorderHandler) } if TestConfiguration.mode == .useAPIAndRecord { return super.send(request, withResponseHandler: recorderHandler) } else { return super.send(request, withResponseHandler: handler) } } override func login(_ username: String, password: String, completion: ErrorClosure?) -> RequestHandler { if TestConfiguration.mode == .useAPIAndRecord { isLoggedIn = true } else if TestConfiguration.mode == .useRecordedResponses { isLoggedIn = true let request = AuthenticationRequest(username: username, password: password, settings: TestConfiguration.settings) completion?(nil) return RequestHandler(object: request as Cancelable) } return super.login(username, password: password, completion: completion) } override func logout() { if TestConfiguration.mode == .useRecordedResponses || TestConfiguration.mode == .useRecordedResponses { isLoggedIn = false } super.logout() } }
mit
c3ccfd4185551af617ba2eb6454c7287
43.911765
129
0.717092
4.909968
false
true
false
false
AaronMT/firefox-ios
Push/PushClient.swift
7
6801
/* 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 SwiftyJSON //public struct PushRemoteError { // static let MissingNecessaryCryptoKeys: Int32 = 101 // static let InvalidURLEndpoint: Int32 = 102 // static let ExpiredURLEndpoint: Int32 = 103 // static let DataPayloadTooLarge: Int32 = 104 // static let EndpointBecameUnavailable: Int32 = 105 // static let InvalidSubscription: Int32 = 106 // static let RouterTypeIsInvalid: Int32 = 108 // static let InvalidAuthentication: Int32 = 109 // static let InvalidCryptoKeysSpecified: Int32 = 110 // static let MissingRequiredHeader: Int32 = 111 // static let InvalidTTLHeaderValue: Int32 = 112 // static let UnknownError: Int32 = 999 //} public let PushClientErrorDomain = "org.mozilla.push.error" private let PushClientUnknownError = NSError(domain: PushClientErrorDomain, code: 999, userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]) private let log = Logger.browserLogger /// Bug 1364403 – This is to be put into the push registration private let apsEnvironment: [String: Any] = [ "mutable-content": 1, "alert": [ "title": " ", "body": " " ], ] public struct PushRemoteError { let code: Int let errno: Int let error: String let message: String? public static func from(json: JSON) -> PushRemoteError? { guard let code = json["code"].int, let errno = json["errno"].int, let error = json["error"].string else { return nil } let message = json["message"].string return PushRemoteError(code: code, errno: errno, error: error, message: message) } } public enum PushClientError: MaybeErrorType { case Remote(PushRemoteError) case Local(Error) public var description: String { switch self { case let .Remote(error): let errorString = error.error let messageString = error.message ?? "" return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>" case let .Local(error): return "<FxAClientError.Local Error \"\(error.localizedDescription)\">" } } } public class PushClient { let endpointURL: NSURL let experimentalMode: Bool lazy fileprivate var urlSession = makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.ephemeral) public init(endpointURL: NSURL, experimentalMode: Bool = false) { self.endpointURL = endpointURL self.experimentalMode = experimentalMode } } public extension PushClient { func register(_ apnsToken: String) -> Deferred<Maybe<PushRegistration>> { // POST /v1/{type}/{app_id}/registration let registerURL = endpointURL.appendingPathComponent("registration")! var mutableURLRequest = URLRequest(url: registerURL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let parameters: [String: Any] if experimentalMode { parameters = [ "token": apnsToken, "aps": apsEnvironment, ] } else { parameters = ["token": apnsToken] } mutableURLRequest.httpBody = JSON(parameters).stringify()?.utf8EncodedData if experimentalMode { log.info("curl -X POST \(registerURL.absoluteString) --data '\(JSON(parameters).stringify()!)'") } return send(request: mutableURLRequest) >>== { json in guard let response = PushRegistration.from(json: json) else { return deferMaybe(PushClientError.Local(PushClientUnknownError)) } return deferMaybe(response) } } func updateUAID(_ apnsToken: String, withRegistration creds: PushRegistration) -> Deferred<Maybe<PushRegistration>> { // PUT /v1/{type}/{app_id}/registration/{uaid} let registerURL = endpointURL.appendingPathComponent("registration/\(creds.uaid)")! var mutableURLRequest = URLRequest(url: registerURL) mutableURLRequest.httpMethod = HTTPMethod.put.rawValue mutableURLRequest.addValue("Bearer \(creds.secret)", forHTTPHeaderField: "Authorization") mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let parameters = ["token": apnsToken] mutableURLRequest.httpBody = JSON(parameters).stringify()?.utf8EncodedData return send(request: mutableURLRequest) >>== { json in KeychainStore.shared.setString(apnsToken, forKey: KeychainKey.apnsToken, withAccessibility: .afterFirstUnlock) return deferMaybe(creds) } } func unregister(_ creds: PushRegistration) -> Success { // DELETE /v1/{type}/{app_id}/registration/{uaid} let unregisterURL = endpointURL.appendingPathComponent("registration/\(creds.uaid)") var mutableURLRequest = URLRequest(url: unregisterURL!) mutableURLRequest.httpMethod = HTTPMethod.delete.rawValue mutableURLRequest.addValue("Bearer \(creds.secret)", forHTTPHeaderField: "Authorization") return send(request: mutableURLRequest) >>> succeed } } /// Utilities extension PushClient { fileprivate func send(request: URLRequest) -> Deferred<Maybe<JSON>> { log.info("\(request.httpMethod!) \(request.url?.absoluteString ?? "nil")") let deferred = Deferred<Maybe<JSON>>() urlSession.dataTask(with: request) { (data, response, error) in if let error = error { deferred.fill(Maybe(failure: PushClientError.Local(error))) return } guard let _ = validatedHTTPResponse(response, contentType: "application/json"), let data = data, !data.isEmpty else { deferred.fill(Maybe(failure: PushClientError.Local(PushClientUnknownError))) return } do { let json = try JSON(data: data) if let remoteError = PushRemoteError.from(json: json) { return deferred.fill(Maybe(failure: PushClientError.Remote(remoteError))) } deferred.fill(Maybe(success: json)) } catch { return deferred.fill(Maybe(failure: PushClientError.Local(error))) } }.resume() return deferred } }
mpl-2.0
7c58dd6f92b3106c1e5914c3ccf55202
37.40678
137
0.640188
4.940407
false
false
false
false
luanlzsn/pos
pos/Classes/pos/Home/Controller/MenuController.swift
1
13757
// // MenuController.swift // pos // // Created by luan on 2017/5/20. // Copyright © 2017年 luan. All rights reserved. // import UIKit class MenuController: AntController,UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate { @IBOutlet weak var bgView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var collection: UICollectionView! @IBOutlet weak var viewHeight: NSLayoutConstraint! @IBOutlet weak var changeView: UIView! @IBOutlet weak var changeHeight: NSLayoutConstraint! @IBOutlet weak var changeCollection: UICollectionView! @IBOutlet weak var changeCollectionBottom: NSLayoutConstraint! @IBOutlet weak var mergeConfirmBtn: UIButton! var confirmMenu: ConfirmBlock? var model: OrderModel? var tableType: String!//餐桌类型 var tableNo = 0//餐桌号 weak var home: HomeController? var menuTitleArray = [String]()//菜单数组 var changeArray = [[String : [NSNumber]]]()//可以被换桌的信息 var isChangeTable = false//是否是换桌 var mergeArray = [OrderModel]()//可合单的信息 var selectMergeArray = [Int]()//选择的合单的餐桌 deinit { confirmMenu = nil } override func viewDidLoad() { super.viewDidLoad() checkMenuData() } func checkMenuData() { if tableType == "D" { titleLabel.text = NSLocalizedString("堂食", comment: "") + " \(tableNo)" menuTitleArray += [NSLocalizedString("订单", comment: ""),NSLocalizedString("换桌", comment: ""),NSLocalizedString("付款", comment: ""),NSLocalizedString("变空桌", comment: ""),NSLocalizedString("合单", comment: ""),/*NSLocalizedString("分单", comment: ""),*/NSLocalizedString("历史订单", comment: "")] } else if tableType == "T" { titleLabel.text = NSLocalizedString("外卖", comment: "") + " \(tableNo)" menuTitleArray += [NSLocalizedString("订单", comment: ""),NSLocalizedString("换桌", comment: ""),NSLocalizedString("付款", comment: ""),NSLocalizedString("变空桌", comment: ""),NSLocalizedString("历史订单", comment: "")] } else { titleLabel.text = NSLocalizedString("送餐", comment: "") + " \(tableNo)" menuTitleArray += [NSLocalizedString("订单", comment: ""),NSLocalizedString("换桌", comment: ""),NSLocalizedString("付款", comment: ""),NSLocalizedString("清空", comment: "")] } if model != nil { menuTitleArray.append(NSLocalizedString("打印收据", comment: "")) } if menuTitleArray.count % 2 == 1 { menuTitleArray.append("") } viewHeight.constant = CGFloat(55 + (menuTitleArray.count / 2) * 51 + 1) } // MARK: 获取换桌信息 func checkChangeTableData() { changeArray.removeAll() changeCollectionBottom.constant = 0 mergeConfirmBtn.isHidden = true var height = 0.0 var dineSet = Set<NSNumber>() for i in 1...home!.dineNum { dineSet.insert(NSNumber(integerLiteral: i)) } let dineArray = [NSNumber](dineSet.subtracting(Set((home!.dineDic as NSDictionary).allKeys as! [NSNumber]))).sorted { (num1, num2) -> Bool in num1.intValue < num2.intValue } if dineArray.count > 0 { changeArray.append([NSLocalizedString("堂食", comment: "") : dineArray]) height += 45.0 * (ceil(Double(dineArray.count) / 3.0) + 1) } var takeoutSet = Set<NSNumber>() for i in 1...home!.takeoutNum { takeoutSet.insert(NSNumber(integerLiteral: i)) } let takeoutArray = [NSNumber](takeoutSet.subtracting(Set((home!.takeoutDic as NSDictionary).allKeys as! [NSNumber]))).sorted { (num1, num2) -> Bool in num1.intValue < num2.intValue } if takeoutArray.count > 0 { changeArray.append([NSLocalizedString("外卖", comment: "") : takeoutArray]) height += 45.0 * (ceil(Double(takeoutArray.count) / 3.0) + 1) } var deliverySet = Set<NSNumber>() for i in 1...home!.deliveryNum { deliverySet.insert(NSNumber(integerLiteral: i)) } let deliveryArray = [NSNumber](deliverySet.subtracting(Set((home!.deliveryDic as NSDictionary).allKeys as! [NSNumber]))).sorted { (num1, num2) -> Bool in num1.intValue < num2.intValue } if deliveryArray.count > 0 { changeArray.append([NSLocalizedString("送餐", comment: "") : deliveryArray]) height += 45.0 * (ceil(Double(deliveryArray.count) / 3.0) + 1) } if height > Double(kScreenHeight - 75) { height = Double(kScreenHeight - 75) } changeHeight.constant = CGFloat(35.0 + height) changeCollection.reloadData() } // MAKR: 获取合单信息 func checkMerge() { mergeArray.removeAll() changeCollectionBottom.constant = 55 mergeConfirmBtn.isHidden = false var height = 0.0 for (num, order) in home!.dineDic { if order.table_status != "R", num != tableNo { mergeArray.append(order) } } mergeArray.sort { (order1, order2) -> Bool in order1.table_no < order2.table_no } height += 45.0 * (ceil(Double(mergeArray.count) / 3.0) + 1) + 55 if height > Double(kScreenHeight - 75) { height = Double(kScreenHeight - 75) } changeHeight.constant = CGFloat(35.0 + height) changeCollection.reloadData() } // MARK: 确认合单 @IBAction func mergeConfirmClick() { var orderIdArray = selectMergeArray orderIdArray.insert(model!.table_no, at: 0) home!.performSegue(withIdentifier: "MergeBill", sender: orderIdArray) dismiss(animated: false, completion: nil) } @IBAction func cancelChangeViewClick() { changeView.isHidden = true } @IBAction func dismissMenuClick(_ sender: UITapGestureRecognizer) { dismiss(animated: true, completion: nil) } // MARK: 换桌 func changeTable(tableNo: NSNumber, tableType: String) { weak var weakSelf = self AntManage.postRequest(path: "orderHandler/moveOrder", params: ["type":tableType, "table":tableNo, "order_no":model!.order_no, "access_token":AntManage.userModel!.token], successResult: { (response) in NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ChangeTableSuccsee"), object: nil) weakSelf?.dismiss(animated: true, completion: nil) }) { AntManage.showDelayToast(message: NSLocalizedString("换桌失败,请重试!", comment: "")) } } // MARK: UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if touch.view == bgView || touch.view == changeView || touch.view?.className() == "UIButton" { return false } return true } // MARK: UICollectionViewDelegate,UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { if collectionView == collection { return 1 } else { if isChangeTable { return changeArray.count } else { return 1 } } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == collection { return menuTitleArray.count } else { if isChangeTable { return ((changeArray[section].values.first != nil) ? changeArray[section].values.first!.count : 0) } else { return mergeArray.count } } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if collectionView == changeCollection, kind == UICollectionElementKindSectionHeader { let header: ChangeTableHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ChangeTableHeaderView", for: indexPath) as! ChangeTableHeaderView if isChangeTable { header.headerTitle.text = changeArray[indexPath.section].keys.first } else { header.headerTitle.text = NSLocalizedString("合单", comment: "") } return header } else { return UICollectionReusableView() } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == collection { let cell: MenuCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MenuCell", for: indexPath) as! MenuCell cell.menuBtn.setTitle(menuTitleArray[indexPath.row], for: .normal) cell.menuBtn.setTitleColor(UIColor.white, for: .normal) weak var weakSelf = self cell.confirmMenu = {(_) -> () in if weakSelf?.menuTitleArray[indexPath.row] == NSLocalizedString("换桌", comment: "") { weakSelf?.isChangeTable = true weakSelf?.checkChangeTableData() weakSelf?.changeView.isHidden = false } else if weakSelf?.menuTitleArray[indexPath.row] == NSLocalizedString("合单", comment: "") { weakSelf?.isChangeTable = false weakSelf?.selectMergeArray.removeAll() weakSelf?.checkMerge() weakSelf?.changeView.isHidden = false } else { if weakSelf?.confirmMenu != nil { weakSelf?.confirmMenu!(weakSelf!.menuTitleArray[indexPath.row]) weakSelf?.dismiss(animated: false, completion: nil) } } } if model == nil { if !(menuTitleArray[indexPath.row] == NSLocalizedString("订单", comment: "") || menuTitleArray[indexPath.row] == NSLocalizedString("历史订单", comment: "")) { cell.menuBtn.setTitleColor(UIColor.init(rgb: 0x808080), for: .normal) cell.confirmMenu = nil } } else if model!.table_status == "R", (menuTitleArray[indexPath.row] == NSLocalizedString("变空桌", comment: "") || menuTitleArray[indexPath.row] == NSLocalizedString("合单", comment: "")) { cell.menuBtn.setTitleColor(UIColor.init(rgb: 0x808080), for: .normal) cell.confirmMenu = nil } return cell } else { let cell: ChangeTableCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChangeTableCell", for: indexPath) as! ChangeTableCell if isChangeTable { cell.changeNumBtn.setTitle("\(changeArray[indexPath.section].values.first![indexPath.row])", for: .normal) cell.changeNumBtn.layer.borderColor = UIColor.init(rgb: 0x808080).cgColor weak var weakSelf = self cell.changeTable = {(_) -> () in let tableNo = (weakSelf?.changeArray[indexPath.section].values.first![indexPath.row])! let tableType: String! if weakSelf?.changeArray[indexPath.section].keys.first == NSLocalizedString("堂食", comment: "") { tableType = "D" } else if weakSelf?.changeArray[indexPath.section].keys.first == NSLocalizedString("外卖", comment: "") { tableType = "T" } else { tableType = "W" } weakSelf?.changeTable(tableNo:tableNo , tableType:tableType ) } } else { cell.changeNumBtn.setTitle("\(mergeArray[indexPath.row].table_no)", for: .normal) if selectMergeArray.contains(mergeArray[indexPath.row].table_no) { cell.changeNumBtn.layer.borderColor = UIColor.init(rgb: 0x5BC0DE).cgColor } else { cell.changeNumBtn.layer.borderColor = UIColor.init(rgb: 0x808080).cgColor } weak var weakSelf = self cell.changeTable = {(_) -> () in if weakSelf!.selectMergeArray.contains(weakSelf!.mergeArray[indexPath.row].table_no) { weakSelf?.selectMergeArray.remove(at: weakSelf!.selectMergeArray.index(of: weakSelf!.mergeArray[indexPath.row].table_no)!) } else { weakSelf?.selectMergeArray.append(weakSelf!.mergeArray[indexPath.row].table_no) } weakSelf?.changeCollection.reloadData() } } return cell } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
b5656491e28a080db27e563e031b52a7
43.76412
297
0.593736
4.726061
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Order/Controller/SAMOrderInfoEditController.swift
1
9238
// // SAMOrderInfoEditController.swift // SaleManager // // Created by apple on 16/12/17. // Copyright © 2016年 YZH. All rights reserved. // import UIKit class SAMOrderInfoEditController: UIViewController { //对外提供的类方法 class func editInfo(orderTitleModel: SAMOrderBuildTitleModel, employeeModel: SAMOrderBuildEmployeeModel?) -> SAMOrderInfoEditController { let editVC = SAMOrderInfoEditController() editVC.orderTitleModel = orderTitleModel editVC.orderBuildEmployeeModel = employeeModel return editVC } //MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //初始主标题 navigationItem.title = orderTitleModel?.cellTitle //设置左按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(SAMOrderInfoEditController.leftButtonClick)) //设置右按钮 navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) if orderTitleModel?.cellTitle == "业务员" { rightButton.isEnabled = true }else { rightButton.isEnabled = false } //监听文本框,并设置代理 contentTextField.addTarget(self, action: #selector(SAMOrderInfoEditController.textFieldEditChange), for: .editingChanged) contentTextField.delegate = self //设置订单业务员数据模型数组 if SAMOrderBuildEmployeeModel.shareModelArr().count == 0 { SAMOrderBuildEmployeeModel.setupModels() } } //MARK: - viewWillAppear override func viewWillAppear(_ animated: Bool) { //赋值文本框 contentTextField.text = orderTitleModel?.cellContent //设置不同内容设置键盘类型 if orderTitleModel!.cellTitle == "备注" { contentTextField.keyboardType = UIKeyboardType.default }else if orderTitleModel!.cellTitle == "交货日期" { contentTextField.inputView = datePicker }else if orderTitleModel!.cellTitle == "业务员" { contentTextField.inputView = employeePicker }else { contentTextField.keyboardType = UIKeyboardType.decimalPad } } //MARK: - viewDidAppear override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) contentTextField.becomeFirstResponder() } //MARK: - 左边按钮点击事件 func leftButtonClick() { navigationController!.popViewController(animated: true) } //MARK: - 右边按钮点击事件 func rightButtonClick() { contentTextField.resignFirstResponder() orderTitleModel?.cellContent = contentTextField.text!.lxm_stringByTrimmingWhitespace()! navigationController!.popViewController(animated: true) } //MARK: - 文本框监听方法 func textFieldEditChange() { if contentTextField.text == orderTitleModel?.cellContent { rightButton.isEnabled = false }else { rightButton.isEnabled = true } } //时间选择器 选择时间 func dateChanged(_ datePicker: UIDatePicker) { //设置文本框时间 contentTextField.text = datePicker.date.yyyyMMddStr() //调用文本框监听方法 textFieldEditChange() } //MARK: - 属性 ///编辑的数据模型 fileprivate var orderTitleModel: SAMOrderBuildTitleModel? { didSet{ isEditTitle = (orderTitleModel?.cellTitle == "备注" || orderTitleModel?.cellTitle == "交货日期") ? true : false } } ///接收的订单业务员数据模型 fileprivate var orderBuildEmployeeModel: SAMOrderBuildEmployeeModel? ///当前是编辑文字,否则是编辑数字 fileprivate var isEditTitle: Bool = true ///右边按钮 fileprivate lazy var rightButton: UIButton = { let button = UIButton(type: .custom) button.setTitle("保存", for: .normal) button.setTitleColor(UIColor(red: 22 / 255.0, green: 122 / 255.0, blue: 189 / 255.0, alpha: 1.0), for: .normal) button.setTitleColor(UIColor(red: 82 / 255.0, green: 182 / 255.0, blue: 249 / 255.0, alpha: 1.0), for: .disabled) button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -15) button.addTarget(self, action: #selector(SAMOrderInfoEditController.rightButtonClick), for: .touchUpInside) button.sizeToFit() return button }() ///时间选择器 fileprivate lazy var datePicker: UIDatePicker? = { let datePicker = UIDatePicker() datePicker.datePickerMode = UIDatePickerMode.date datePicker.addTarget(self, action: #selector(SAMOrderInfoEditController.dateChanged(_:)), for: .valueChanged) return datePicker }() ///业务员选择器 fileprivate lazy var employeePicker: UIPickerView? = { let pickerView = UIPickerView() pickerView.delegate = self pickerView.dataSource = self return pickerView }() //MARK: - xib链接属性 @IBOutlet weak var contentTextField: UITextField! //MARK: - 其他方法 fileprivate init() { super.init(nibName: nil, bundle: nil) } fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { //从xib加载view view = Bundle.main.loadNibNamed("SAMOrderInfoEditController", owner: self, options: nil)![0] as! UIView } } //MARK: - 文本框代理 UITextFieldDelegate extension SAMOrderInfoEditController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { if orderTitleModel?.cellTitle == "业务员" { } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //如果当前是文本编辑 if isEditTitle { return true } //获取当前文本 let str = textField.text if str == "" { return true } //如果第一个是小数点就删除小数点 if str == "." { textField.text = "" return true } //如果第一个是0 if str == "0" { //如果第二个是小数点,允许输入 if string == "." { return true }else { //如果第二个不是是小数点,删除第一个0 textField.text = "" return true } } //如果输入小数点,且当前文本已经有小数点,不让输入 if (str!.contains(".")) && (string == ".") { return false } return true } func textFieldDidEndEditing(_ textField: UITextField) { //如果是文本编辑就直接返回 if isEditTitle { return } //获取文本字符串 var str = textField.text //如果是空字符串,就赋值文本框,返回 if str == "" { contentTextField.text = "0" return } //截取最后一个小数点 str = str?.lxm_stringByTrimmingLastIfis(".") //如果截取后没有字符,或者为0,则赋值 if str == "" || str == "0" { contentTextField.text = "0" return } //赋值文本框 textField.text = str } func textFieldShouldReturn(_ textField: UITextField) -> Bool { //结束第一响应者 textField.resignFirstResponder() return true } } //MARK: - PickerViewDataSource PickerViewDelegate extension SAMOrderInfoEditController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return SAMOrderBuildEmployeeModel.shareModelArr().count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let model = SAMOrderBuildEmployeeModel.shareModelArr()[row] as! SAMOrderBuildEmployeeModel return model.name } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let model = SAMOrderBuildEmployeeModel.shareModelArr()[row] as! SAMOrderBuildEmployeeModel contentTextField.text = model.name orderBuildEmployeeModel?.employeeID = model.employeeID orderBuildEmployeeModel?.name = model.name } }
apache-2.0
617b2b73290bd614edddb5c6896dbc5e
29.455197
162
0.605272
4.787042
false
false
false
false
V1C0D3R/KubiServerApp
KubiServer/Helpers/KubiManager.swift
2
5681
/* * Software License Agreement(New BSD License) * Copyright © 2017, Victor Nouvellet * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * 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. */ // // KubiManager.swift // KubiServer // // Created by Victor Nouvellet on 1/23/17. // Copyright © 2017 Victor Nouvellet Inc. All rights reserved. // import Foundation import KubiDeviceSDK class KubiManager: NSObject { static let sharedInstance = KubiManager() //HERE is the bug: deviceSDK not available in Swift... Waiting for a framework update... let kubiSdk: RRDeviceSDK = RRDeviceSDK.init(swiftSDK: ()) var connectedDevice: RRDevice? { return self.kubiSdk.connectedDevice } var deviceConnectionState: RRDeviceConnectionState { return self.kubiSdk.deviceConnectionState } var deviceDidUpdateDeviceListCallback: ((_ deviceList: [Any]) -> ())? = nil var deviceDidChangeConnectionCallback: ((_ connectionState: RRDeviceConnectionState) -> ())? = nil // MARK: Parent methods override init() { super.init() self.configureRRDeviceSDKDelegate() } // MARK: Public methods func disconnectDevice() { self.kubiSdk.disconnectDevice() } func startScan() -> Bool { return self.kubiSdk.startScan() } func endScan() { self.kubiSdk.endScan() } } // MARK: - RRDeviceSDK delegate extension extension KubiManager: RRDeviceSDKDelegate { func configureRRDeviceSDKDelegate() { self.kubiSdk.delegate = self } func deviceSDK(_ deviceSDK: RRDeviceSDK, didUpdateDeviceList deviceList: [Any]) { self.deviceDidUpdateDeviceListCallback?(deviceList) } func deviceSDK(_ deviceSDK: RRDeviceSDK, didChange connectionState: RRDeviceConnectionState) { self.deviceDidChangeConnectionCallback?(connectionState) } } // MARK: - Sample movements extension extension KubiManager { func tiltUp() { guard let kubi = self.connectedDevice as? RRKubi else { print("[Warning] No Kubi connected = No remote control") return } do { try kubi.incrementalMove(withPanDelta: NSNumber(value: 0), atPanSpeed: NSNumber(value: 0), andTiltDelta: NSNumber(value: 20), atTiltSpeed: NSNumber(value: 150)) } catch { print("Error doing incremental") } } func tiltDown() { guard let kubi = self.connectedDevice as? RRKubi else { print("[Warning] No Kubi connected = No remote control") return } do { try kubi.incrementalMove(withPanDelta: NSNumber(value: 0), atPanSpeed: NSNumber(value: 0), andTiltDelta: NSNumber(value: -20), atTiltSpeed: NSNumber(value: 150)) } catch { print("Error doing incremental") } } func panLeft() { guard let kubi = self.connectedDevice as? RRKubi else { print("[Warning] No Kubi connected = No remote control") return } do { try kubi.incrementalMove(withPanDelta: NSNumber(value: -20), atPanSpeed: NSNumber(value: 150), andTiltDelta: NSNumber(value: 0), atTiltSpeed: NSNumber(value: 0)) } catch { print("Error doing incremental") } } func panRight() { guard let kubi = self.connectedDevice as? RRKubi else { print("[Warning] No Kubi connected = No remote control") return } do { try kubi.incrementalMove(withPanDelta: NSNumber(value: 20), atPanSpeed: NSNumber(value: 150), andTiltDelta: NSNumber(value: 0), atTiltSpeed: NSNumber(value: 0)) } catch { print("Error doing incremental") } } }
bsd-3-clause
80f4ced1e3826492ed21bd06e0b4684f
39.276596
758
0.613488
5.030115
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloadRequest.swift
1
1458
// // HTTPDownloadRequest.swift // KeymanEngine // // Created by Gabriel Wong on 2017-09-15. // Copyright © 2017 SIL International. All rights reserved. // import Foundation enum DownloadType: String { case downloadFile } class HTTPDownloadRequest: NSObject { let url: URL let typeCode: DownloadType // TODO: Make values of this dict properties of the class var userInfo: [String: Any] var task: URLSessionTask? var destinationFile: String? var rawResponseData: Data? var tag: Int = 0 init(url: URL, downloadType type: DownloadType, userInfo info: [String: Any]) { self.url = url typeCode = type userInfo = info super.init() } convenience init(url: URL) { self.init(url: url, downloadType: DownloadType.downloadFile, userInfo: [:]) } convenience init(url: URL, userInfo info: [String: Any]) { self.init(url: url, downloadType: DownloadType.downloadFile, userInfo: info) } convenience init(url: URL, downloadType type: DownloadType) { self.init(url: url, downloadType: type, userInfo: [:]) } var responseStatusCode: Int? { if let response = task?.response as? HTTPURLResponse { return response.statusCode } return nil } var responseStatusMessage: String? { guard let statusCode = responseStatusCode else { return nil } return HTTPURLResponse.localizedString(forStatusCode: statusCode) } var error: Error? { return task?.error } }
apache-2.0
a9e97ce84057babd4ede0d6b9c738eee
22.885246
81
0.691833
4.115819
false
false
false
false
allenngn/firefox-ios
Sync/HistoryPayload.swift
10
1988
/* 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 Storage public class HistoryPayload: CleartextPayloadJSON { public class func fromJSON(json: JSON) -> HistoryPayload? { let p = HistoryPayload(json) if p.isValid() { return p } return nil } override public func isValid() -> Bool { if !super.isValid() { return false } if self["deleted"].isBool { return true } return self["histUri"].isString && // TODO: validate URI. self["title"].isString && self["visits"].isArray } public func asPlace() -> Place { return Place(guid: self.id, url: self.histURI, title: self.title) } var visits: [Visit] { return optFilter(self["visits"].asArray!.map(Visit.fromJSON)) } private var histURI: String { return self["histUri"].asString! } var historyURI: NSURL { return self.histURI.asURL! } var title: String { return self["title"].asString! } override public func equalPayloads(obj: CleartextPayloadJSON) -> Bool { if let p = obj as? HistoryPayload { if !super.equalPayloads(p) { return false; } if p.deleted { return self.deleted == p.deleted } // If either record is deleted, these other fields might be missing. // But we just checked, so we're good to roll on. if p.title != self.title { return false } if p.historyURI != self.historyURI { return false } // TODO: compare visits. return true } return false } }
mpl-2.0
48b627116b2638b757274e6bd7c0dac1
24.487179
80
0.54326
4.570115
false
false
false
false
TalkingBibles/Talking-Bible-iOS
TalkingBible/Book.swift
1
1876
// // Copyright 2015 Talking Bibles International // // 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. // @objc(Book) final class Book: _Book { // Custom logic goes here. class func exists(bookId bookId: BookId?, withLanguageId languageId: LanguageId?) -> Bool { if let bookId = bookId { if let languageId = languageId { let bookQuery = Query<Book>(entityName: Book.entityName()) let predicate = NSPredicate(format: "bookId == %@ AND collection.language.languageId == %@", bookId, languageId) if bookQuery.first(predicate, sortDescriptors: []) != nil { return true } } } return false } class func defaultBookId(languageId languageId: LanguageId?) -> BookId? { if let languageId = languageId { let predicate = NSPredicate(format: "collection.language.languageId == %@", languageId) let sortDescriptors = [NSSortDescriptor(key: "position", ascending: true)] let bookQuery = Query<Book>(entityName: Book.entityName()) if let entity = bookQuery.first(predicate, sortDescriptors: sortDescriptors) { return entity.bookId } } return nil } } typealias BookId = String
apache-2.0
63df1ef7910c712c4270ce1a40585c47
35.096154
128
0.623134
4.69
false
false
false
false
RunningCharles/Arithmetic
src/13PopOrder.swift
1
1169
#!/usr/bin/swift class Stack { var values: [Int] = [] func push(_ value: Int) { values.append(value) } func peek() -> Int { if values.count == 0 { return -1 } return values[values.count - 1] } func pop() -> Int { if values.count == 0 { return -1 } let value = values[values.count - 1] values.removeLast() return value } func isEmpty() -> Bool { return values.count == 0 } } func isPopOrder(_ push: [Int], _ pop: [Int]) -> Bool { if push.count == 0 || pop.count == 0 || push.count != pop.count { return false } let stack = Stack() var pushIndex = 0 var popIndex = 0 while popIndex < pop.count { while pushIndex < push.count && (stack.isEmpty() || stack.peek() != pop[popIndex]) { stack.push(push[pushIndex]) pushIndex += 1 } if stack.peek() == pop[popIndex] { stack.pop() popIndex += 1 } else { return false } } return true } print(isPopOrder([4,5,3,2,1], [4,3,5,1,2]))
bsd-3-clause
be9e2c35d4724150704a9bddd30e1662
20.648148
92
0.473909
3.711111
false
false
false
false
TherapyChat/Reach
Source/Reach.swift
1
3765
// // Reach.swift // Reach // // Created by sergio on 22/05/2017. // Copyright © 2017 nc43tech. All rights reserved. // import Foundation #if !os(watchOS) import SystemConfiguration #endif /// Delegate responsible to notify of changes in `Network` connection public protocol ReachDelegate: class { /// Called when network is available func networkIsReachable() /// Called when network is not available func networkIsNotReachable() /// Always notify from network changes and spicify `Network` type func networkDidChange(status: Network) } public extension ReachDelegate { func networkIsReachable() { } func networkIsNotReachable() { } func networkDidChange(status: Network) { } } /// Responsible to observe network changes public final class Reach { #if !os(watchOS) private let reachability: SCNetworkReachability? private let queue = DispatchQueue(label: "com.reach.queue", qos: .background) #endif /// Delegate object to notify events public weak var delegate: ReachDelegate? /// Current status of `Network` public var status: Network = .notReachable { didSet { if status == oldValue { return } delegate?.networkDidChange(status: status) switch status { case .notReachable: delegate?.networkIsNotReachable() case .reachable: delegate?.networkIsReachable() } } } // MARK: - Lifecycle /// Creates an instance with specific `hostname` /// /// - parameter hostname: URL for hostname /// public init(with hostname: String) { #if !os(watchOS) reachability = SCNetworkReachabilityCreateWithName(nil, hostname) #endif } /// Creates an instance without specific `hostname` public init() { #if !os(watchOS) var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) reachability = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) #endif } deinit { stop() } // MARK: - Runtime /// Function to start observe `Network` changes public func start() { #if !os(watchOS) var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reach>.passUnretained(self).toOpaque()) guard let network = reachability else { return } SCNetworkReachabilitySetCallback(network, callback, &context) SCNetworkReachabilitySetDispatchQueue(network, queue) #endif } /// Function to remove observer on `Network` changes public func stop() { #if !os(watchOS) guard let network = reachability else { return } SCNetworkReachabilitySetCallback(network, nil, nil) SCNetworkReachabilitySetDispatchQueue(network, nil) #endif } #if !os(watchOS) /// Change `Network` status func reachability(change flags: SCNetworkReachabilityFlags) { var network: Network = .notReachable if flags.contains(.reachable) { network = .reachable(.wifi) } #if os(iOS) if flags.contains(.isWWAN) { network = .reachable(.wwan) } #endif status = network } #endif }
apache-2.0
64477d45d2b61a45f635cf0b586199e4
25.885714
100
0.585282
5.235049
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/BaseViewController/BFBaseViewController+Nav.swift
1
5099
// // BFBaseViewController+Nav.swift // BeeFun // // Created by WengHengcong on 2017/4/16. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit extension BFBaseViewController { func customView() { self.view.backgroundColor = UIColor.bfViewBackgroundColor //下面语句添加在CPBaseNavigationController中无效 self.navigationController?.navigationBar.barTintColor = UIColor.bfRedColor self.navigationController?.navigationBar.titleTextAttributes = BFStyleGuide.navTitleTextAttributes() //返回按钮颜色与文字 self.navigationController?.navigationBar.tintColor = UIColor.white //启用滑动返回(swipe back) self.navigationController?.interactivePopGestureRecognizer!.delegate = self customLeftItem() customRightItem() } func customLeftItem() { leftItem = UIButton() leftItem!.setImage(UIImage(named: "arrow_left"), for: UIControlState()) leftItem!.setImage(UIImage(named: "arrow_left"), for: .selected) leftItem?.titleLabel?.font = UIFont.bfSystemFont(ofSize: 17.0) leftItem?.setTitleColor(.white, for: .normal) leftItem?.setTitleColor(UIColor.bfLineBackgroundColor, for: .disabled) leftItem!.addTarget(self, action: #selector(BFBaseViewController.navigationShouldPopOnBackButton), for: .touchUpInside) leftItem!.isHidden = false layoutLeftItem() } func layoutLeftItem() { if leftItem?.currentImage != nil { leftItem!.frame = CGRect(x: 0, y: 5, width: 25, height: 25) } else { leftItem!.frame = CGRect(x: 0, y: 5, width: 40, height: 25) } let leftBarButton = UIBarButtonItem(customView: leftItem!) let leftSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) leftSpace.width = -8; //越小越靠左 self.navigationItem.leftBarButtonItems = [leftSpace, leftBarButton] } func customRightItem() { rightItem = UIButton() rightItem?.titleLabel?.font = UIFont.bfSystemFont(ofSize: 17.0) rightItem?.titleLabel?.adjustsFontSizeToFitWidth = true rightItem?.titleLabel?.minimumScaleFactor = 0.7 rightItem?.setTitleColor(.white, for: .normal) rightItem?.setTitleColor(UIColor.bfLineBackgroundColor, for: .disabled) rightItem!.addTarget(self, action: #selector(BFBaseViewController.rightItemAction(_:)), for: .touchUpInside) rightItem!.isHidden = true layoutRightItem() } func layoutRightItem() { if rightItem?.currentImage != nil { rightItem!.frame = CGRect(x: 0, y: 5, width: 25, height: 25) } else { rightItem!.frame = CGRect(x: 0, y: 5, width: 40, height: 25) } if #available(iOS 11, *) { let view = UIView(frame: CGRect(x: 0, y: 5, w: 0, h: 25)) view.backgroundColor = .blue if rightItem?.currentImage != nil { rightItem!.frame = CGRect(x: 0, y: 0, width: 25, height: 25) } else { rightItem!.frame = CGRect(x: 0, y: 0, width: 40, height: 25) } view.addSubview(rightItem!) let rightBarButton = UIBarButtonItem(customView: view) self.navigationItem.rightBarButtonItem = rightBarButton } else { //.... Set Right/Left Bar Button item let rightBarButton = UIBarButtonItem(customView: rightItem!) let rightSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) rightSpace.width = -8; //越小越靠右 self.navigationItem.rightBarButtonItems = [rightSpace, rightBarButton] } } func setLeftBarItem(_ left: UIButton) { //.... Set Right/Left Bar Button item let leftBarButton = UIBarButtonItem(customView: left) let leftSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) leftSpace.width = -8; //越小越靠左 self.navigationItem.leftBarButtonItems = [leftSpace, leftBarButton] } func setRightBarItem(_ right: UIButton) { let rightBarButton = UIBarButtonItem(customView: right) let rightSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) rightSpace.width = -8; //越小越靠右 self.navigationItem.rightBarButtonItems = [rightSpace, rightBarButton] } } extension BFBaseViewController: NavigationControllerBackButtonDelegate { @objc func navigationShouldPopOnBackButton() -> Bool { leftItemAction(leftItem!) return false } /// 导航栏左边按钮点击 /// /// - Parameter sender: <#sender description#> @objc func leftItemAction(_ sender: UIButton?) { } /// 导航栏右边按钮点击 /// /// - Parameter sender: <#sender description#> @objc func rightItemAction(_ sender: UIButton?) { } }
mit
8d337dda3654cee91bf1f49fc931cc77
36.059701
127
0.636931
4.720532
false
false
false
false
akaralar/siesta
Source/Siesta/Support/Collection+Siesta.swift
3
3066
// // Collection+Siesta.swift // Siesta // // Created by Paul on 2015/7/19. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation internal extension Collection { func any(match predicate: (Iterator.Element) -> Bool) -> Bool { for elem in self where predicate(elem) { return true } return false } func all(match predicate: (Iterator.Element) -> Bool) -> Bool { return !any { !predicate($0) } } } internal extension Array { // Wat? There’s really no in-place counterpart for filter()? mutating func remove(matching predicate: (Iterator.Element) -> Bool) { var dst = startIndex for src in indices { let elem = self[src] if !predicate(elem) { self[dst] = elem dst = dst.advanced(by: 1) } } removeSubrange(dst ..< endIndex) } } internal extension Dictionary { static func fromArray<K, V>(_ arrayOfTuples: [(K, V)]) -> [K:V] { var dict = Dictionary<K, V>(minimumCapacity: arrayOfTuples.count) for (k, v) in arrayOfTuples { dict[k] = v } return dict } func mapDict<MappedKey, MappedValue>(transform: (Key, Value) -> (MappedKey, MappedValue)) -> [MappedKey:MappedValue] { return Dictionary.fromArray(map(transform)) } func flatMapDict<MappedKey, MappedValue>(transform: (Key, Value) -> (MappedKey?, MappedValue?)) -> [MappedKey:MappedValue] { return Dictionary.fromArray( flatMap { let (k, v) = transform($0, $1) if let k = k, let v = v { return (k, v) } else { return nil } } ) } mutating func cacheValue(forKey key: Key, ifNone newValue: () -> Value) -> Value { return self[key] ?? { let newValue = newValue() self[key] = newValue return newValue }() } mutating func removeValues(matching predicate: (Value) -> Bool) -> Bool { var anyRemoved = false for (key, value) in self { if predicate(value) { removeValue(forKey: key) anyRemoved = true } } return anyRemoved } } internal extension Set { mutating func filterInPlace(predicate: (Iterator.Element) -> Bool) { if !all(match: predicate) { // There's apparently no more performant way of doing this filter in place than creating a whole new set. // Even the stdlib’s internal implementation does this for its similar mutating union/intersection methods. self = Set(filter(predicate)) } } }
mit
8689ebac6850b6bcc4166eb180801ef4
25.617391
119
0.50343
4.616893
false
false
false
false
zhugejunwei/Algorithms-in-Java-Swift-CPP
Dijkstra & Floyd/Dijkstra & Floyd/Floyd-1D.swift
1
1618
// // Floyd-1D.swift // Dijkstra & Floyd // // Created by 诸葛俊伟 on 10/1/16. // Copyright © 2016 University of Pittsburgh. All rights reserved. // import Foundation func floyd1D(_ graph: [Int]) { var path = Array(repeating: 0, count: graph.count) let n = Int(sqrt(Double(2 * graph.count))) + 1 var dist = graph for i in 0..<graph.count { if graph[i] == 0 { dist[i] = Int(Int32.max) } } // var path = Array(repeating: Array(repeatElement(0, count: n)), count: n) for k in 0..<n { for i in 0..<n { for j in 0..<n { var ij = 0, ik = 0, kj = 0 if i < j { ij = (2*n-1-i)*i/2+j-i-1 } else if i > j { ij = (2*n-1-j)*j/2+i-j-1 } if i < k { ik = (2*n-1-i)*i/2+k-i-1 } else if i > k { ik = (2*n-1-k)*k/2+i-k-1 } if k < j { kj = (2*n-1-k)*k/2+j-k-1 } else if k > j { kj = (2*n-1-j)*j/2+k-j-1 } // guard ij != ik && ij != kj && ik != kj else { // break // } // print(i, j, dist[ij], dist[ik], dist[kj]) if dist[ij] > dist[ik] + dist[kj] { path[ij] = k dist[ij] = dist[ik] + dist[kj] } } } } // return path }
mit
077d84e03263fc24a946acfd58904752
27.732143
82
0.340584
3.283673
false
false
false
false
cforlando/orlando-walking-tours-ios
Orlando Walking Tours/Services/FirebaseDataService.swift
1
3653
// // FirebaseDataService.swift // Orlando Walking Tours // // Created by Keli'i Martin on 5/9/16. // Copyright © 2016 Code for Orlando. All rights reserved. // import Foundation import SwiftyJSON import Firebase import FirebaseStorage import Alamofire import AlamofireImage struct FirebaseDataService : DataService { //////////////////////////////////////////////////////////// // MARK: - Properties //////////////////////////////////////////////////////////// let databaseRef = FIRDatabase.database().reference() let storageRef = FIRStorage.storage().reference(forURL: "gs://orlando-walking-tours.appspot.com") let imageCache = AutoPurgingImageCache() //////////////////////////////////////////////////////////// func getLocations(completion: @escaping ([HistoricLocation]) -> Void) { let historicLocationsRef = databaseRef.child("historic-locations").child("orlando") historicLocationsRef.observeSingleEvent(of: .value, with: { snapshot in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000" var locations = [HistoricLocation]() if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshots { if let locationDict = snap.value as? [String : AnyObject] { let locationJSON = JSON(locationDict) if let location = HistoricLocation.mr_createEntity() { if let title = locationJSON["name"].string, let description = locationJSON["description"].string, let address = locationJSON["address"].string, let locationType = locationJSON["type"].string { location.locationTitle = title location.locationDescription = description location.address = address location.locationType = locationType } if let latitude = locationJSON["location"]["latitude"].double, let longitude = locationJSON["location"]["longitude"].double { location.latitude = latitude as NSNumber location.longitude = longitude as NSNumber } if let localRegistryDate = locationJSON["localRegistryDate"].string { location.localRegistryDate = formatter.date(from: localRegistryDate) as NSDate? } if let nationalRegistryDate = locationJSON["nationalRegistryDate"].string { location.nrhpDate = formatter.date(from: nationalRegistryDate) as NSDate? } locations.append(location) } } } print(locations.count) completion(locations) } }) } //////////////////////////////////////////////////////////// func getPhotos(for location: HistoricLocation, at path: String, completion: ([UIImage]?) -> Void) { // TODO: Implement this function completion(nil) } }
mit
15faf2ae68cbf46f918e6e77923fe308
37.442105
111
0.473439
6.362369
false
false
false
false
Moonsownner/DearFace
DearFace/DearFace/MakeFaceLayout.swift
1
1656
// // MakeFaceLayout.swift // DearFace // // Created by J HD on 16/9/10. // Copyright © 2016年 Joker. All rights reserved. // import UIKit class MakeFaceLayout: UICollectionViewLayout { var sz: CGSize = CGSize.zero var atts = [IndexPath: UICollectionViewLayoutAttributes]() override func prepare() { guard let collect = self.collectionView else{ return } let sections = collect.numberOfSections let items = collect.numberOfItems(inSection: 0) sz = collect.contentSize let cellWidth = floor(sz.width/CGFloat(sections)) let cellHeight = floor(sz.height/CGFloat(items)) var x = 0 var y = 0 var atts = [UICollectionViewLayoutAttributes]() for i in 0..<sections{ for j in 0..<items{ let att = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: j, section: i)) att.frame = CGRect(x: CGFloat(x)*cellWidth, y: CGFloat(y)*cellHeight, width: cellWidth, height: cellHeight) atts.append(att) x = (x + 1) } x = 0 y = y + 1 } for att in atts{ self.atts[att.indexPath] = att } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return atts[indexPath] } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return Array(self.atts.values) } override var collectionViewContentSize : CGSize { return sz } }
mit
9d23521ca5ae242652aad95577a4cf6a
28.517857
123
0.594071
4.709402
false
false
false
false
burning-git/swift-PlaceholderTextView
swfit_PlaceholderTextView/PlaceholderTextView.swift
1
2392
// // PlaceholderTextView.swift // swfit_PlaceholderTextView // // Created by gitBurning on 14/12/10. // Copyright (c) 2014年 gitBurning. All rights reserved. // import UIKit class PlaceholderProperty:NSObject { var PlaceholderString:String! var PlaceholderColor :UIColor = UIColor.lightGrayColor() var PlaceholderFont :UIFont! } class PlaceholderTextView: UITextView { private var PlaceholderLabel:UILabel?; private var PlaceholderColor:UIColor? func addPlaceholder(){ let leff:CGFloat=5,top:CGFloat=0,height:CGFloat=30; PlaceholderLabel=UILabel(frame: CGRectMake(leff, top, CGRectGetWidth(self.frame)-2*leff, height)); self.addSubview(PlaceholderLabel!); PlaceholderLabel!.backgroundColor=UIColor.clearColor() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("changeDidText:"), name: UITextViewTextDidChangeNotification, object: nil); } /// 重载 原来 text 属性 override var text:String!{ get{ return super.text; } set(Newtext){ if Newtext.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 { PlaceholderLabel?.hidden=true; } super.text=Newtext; } } func changeDidText(noti : NSNotification){ if self.text!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)==0 { PlaceholderLabel!.hidden=false } else { PlaceholderLabel!.hidden=true } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(frame: CGRect, textContainer: NSTextContainer? ,Placeholder: PlaceholderProperty) { super.init(frame: frame, textContainer: textContainer) self.addPlaceholder() PlaceholderLabel!.text=Placeholder.PlaceholderString; PlaceholderLabel!.textColor=Placeholder.PlaceholderColor PlaceholderLabel!.font=Placeholder.PlaceholderFont==nil ? Placeholder.PlaceholderFont:self.font; //PlaceholderLabel!.font=UIFont(name: self.font.fontName, size: 13)! } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } }
apache-2.0
f40041d00e18c4c925970c2d9ab69cda
23.265306
157
0.624895
5.059574
false
false
false
false
stulevine/firefox-ios
StorageTests/TestSQLiteRemoteClientsAndTabs.swift
1
6326
/* 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 XCTest public class MockRemoteClientsAndTabs: RemoteClientsAndTabs { public let clientsAndTabs: [ClientAndTabs] public init() { let now = NSDate.now() let client1GUID = Bytes.generateGUID() let client2GUID = Bytes.generateGUID() let u11 = NSURL(string: "http://test.com/test1")! let tab11 = RemoteTab(clientGUID: client1GUID, URL: u11, title: "Test 1", history: [], lastUsed: (now - OneMinuteInMilliseconds), icon: nil) let u12 = NSURL(string: "http://test.com/test2")! let tab12 = RemoteTab(clientGUID: client1GUID, URL: u12, title: "Test 2", history: [], lastUsed: (now - OneHourInMilliseconds), icon: nil) let tab21 = RemoteTab(clientGUID: client2GUID, URL: u11, title: "Test 1", history: [], lastUsed: (now - OneDayInMilliseconds), icon: nil) let u22 = NSURL(string: "http://different.com/test2")! let tab22 = RemoteTab(clientGUID: client2GUID, URL: u22, title: "Different Test 2", history: [], lastUsed: now + OneHourInMilliseconds, icon: nil) let client1 = RemoteClient(guid: client1GUID, name: "Test client 1", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS") let client2 = RemoteClient(guid: client2GUID, name: "Test client 2", modified: (now - OneHourInMilliseconds), type: "desktop", formfactor: "laptop", os: "Darwin") // Tabs are ordered most-recent-first. self.clientsAndTabs = [ClientAndTabs(client: client1, tabs: [tab11, tab12]), ClientAndTabs(client: client2, tabs: [tab22, tab21])] } public func wipeClients() -> Deferred<Result<()>> { return Deferred(value: Result(success: ())) } public func wipeTabs() -> Deferred<Result<()>> { return Deferred(value: Result(success: ())) } public func insertOrUpdateClients(clients: [RemoteClient]) -> Deferred<Result<()>> { return Deferred(value: Result(success: ())) } public func insertOrUpdateClient(client: RemoteClient) -> Deferred<Result<()>> { return Deferred(value: Result(success: ())) } public func insertOrUpdateTabsForClientGUID(clientGUID: String, tabs: [RemoteTab]) -> Deferred<Result<Int>> { return Deferred(value: Result(success: -1)) } public func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> { return Deferred(value: Result(success: self.clientsAndTabs)) } public func getClients() -> Deferred<Result<[RemoteClient]>> { return Deferred(value: Result(success: self.clientsAndTabs.map { $0.client })) } } func byGUID(a: ClientAndTabs, b: ClientAndTabs) -> Bool { return a.client.guid < b.client.guid } class SQLRemoteClientsAndTabsTests: XCTestCase { var clientsAndTabs: SQLiteRemoteClientsAndTabs! lazy var clients: [ClientAndTabs] = MockRemoteClientsAndTabs().clientsAndTabs override func setUp() { let files = MockFiles() files.remove("browser.db") clientsAndTabs = SQLiteRemoteClientsAndTabs(files: files) } func testInsertGetClear() { // Insert some test data. for c in clients { let e = self.expectationWithDescription("Insert.") clientsAndTabs.insertOrUpdateClient(c.client).upon { XCTAssertTrue($0.isSuccess) e.fulfill() } clientsAndTabs.insertOrUpdateTabsForClientGUID(c.client.guid, tabs: c.tabs) } let f = self.expectationWithDescription("Get after insert.") clientsAndTabs.getClientsAndTabs().upon { if let got = $0.successValue { let expected = self.clients.sorted(byGUID) let actual = got.sorted(byGUID) // This comparison will fail if the order of the tabs changes. We sort the result // as part of the DB query, so it's not actively sorted in Swift. XCTAssertEqual(expected, actual) } else { XCTFail("Expected clients!") } f.fulfill() } // Update the test data with a client with new tabs, and one with no tabs. let client0NewTabs = clients[1].tabs.map { $0.withClientGUID(self.clients[0].client.guid) } let client1NewTabs: [RemoteTab] = [] let expected = [ ClientAndTabs(client: clients[0].client, tabs: client0NewTabs), ClientAndTabs(client: clients[1].client, tabs: client1NewTabs), ].sorted(byGUID) func doUpdate(guid: String, tabs: [RemoteTab]) { let g0 = self.expectationWithDescription("Update client \(guid).") clientsAndTabs.insertOrUpdateTabsForClientGUID(guid, tabs: tabs).upon { if let rowID = $0.successValue { XCTAssertTrue(rowID > -1) } else { XCTFail("Didn't successfully update.") } g0.fulfill() } } doUpdate(clients[0].client.guid, client0NewTabs) doUpdate(clients[1].client.guid, client1NewTabs) let h = self.expectationWithDescription("Get after update.") clientsAndTabs.getClientsAndTabs().upon { if let clients = $0.successValue { XCTAssertEqual(expected, clients.sorted(byGUID)) } else { XCTFail("Expected clients!") } h.fulfill() } // Now clear everything, and verify we have no clients or tabs whatsoever. let i = self.expectationWithDescription("Clear.") clientsAndTabs.clear().upon { XCTAssertTrue($0.isSuccess) i.fulfill() } let j = self.expectationWithDescription("Get after clear.") clientsAndTabs.getClientsAndTabs().upon { if let clients = $0.successValue { XCTAssertEqual(0, clients.count) } else { XCTFail("Expected clients!") } j.fulfill() } self.waitForExpectationsWithTimeout(10, handler: nil) } }
mpl-2.0
5fa8ac9fffbd0f3919628e5f14cc9af8
39.037975
173
0.620297
4.63104
false
true
false
false
alexruperez/LaunchScreenSnapshot
LaunchScreenSnapshotTests/LaunchScreenSnapshotTests.swift
1
3778
// // LaunchScreenSnapshotTests.swift // LaunchScreenSnapshotTests // // Created by Alex Rupérez on 19/5/17. // Copyright © 2017 alexruperez. All rights reserved. // import XCTest @testable import LaunchScreenSnapshot class LaunchScreenSnapshotTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testApplicationWillResignActive() { let window = UIWindow() let view = UIView() let notificationCenter = NotificationCenter.default let launchScreenSnapshot = LaunchScreenSnapshot(notificationCenter: notificationCenter) launchScreenSnapshot.window = window launchScreenSnapshot.protect(with: view) XCTAssertFalse(window.subviews.contains(view)) notificationCenter.post(name: .UIApplicationWillResignActive, object: nil) XCTAssertTrue(window.subviews.contains(view)) } func testApplicationDidEnterBackground() { let window = UIWindow() let view = UIView() let notificationCenter = NotificationCenter.default let launchScreenSnapshot = LaunchScreenSnapshot(notificationCenter: notificationCenter) launchScreenSnapshot.window = window launchScreenSnapshot.protect(with: view, trigger: .didEnterBackground) XCTAssertFalse(window.subviews.contains(view)) notificationCenter.post(name: .UIApplicationDidEnterBackground, object: nil) XCTAssertTrue(window.subviews.contains(view)) } func testApplicationDidBecomeActive() { let window = UIWindow() let view = UIView() let notificationCenter = NotificationCenter.default let launchScreenSnapshot = LaunchScreenSnapshot(notificationCenter: notificationCenter) launchScreenSnapshot.window = window XCTAssertFalse(window.subviews.contains(view)) launchScreenSnapshot.protect(with: view, force: true) notificationCenter.post(name: .UIApplicationDidBecomeActive, object: nil) XCTAssertTrue(window.subviews.contains(view)) } func testApplicationWillEnterForeground() { let window = UIWindow() let view = UIView() let notificationCenter = NotificationCenter.default let launchScreenSnapshot = LaunchScreenSnapshot(notificationCenter: notificationCenter) launchScreenSnapshot.window = window launchScreenSnapshot.protect(with: view) XCTAssertFalse(window.subviews.contains(view)) notificationCenter.post(name: .UIApplicationWillResignActive, object: nil) XCTAssertTrue(window.subviews.contains(view)) notificationCenter.post(name: .UIApplicationWillEnterForeground, object: nil) XCTAssertFalse(window.subviews.contains(view)) } func testStaticProtectUnprotect() { let window = UIWindow() let view = UIView() let launchScreenSnapshot = LaunchScreenSnapshot.protect(with: view) launchScreenSnapshot.window = window XCTAssertFalse(window.subviews.contains(view)) NotificationCenter.default.post(name: .UIApplicationWillResignActive, object: nil) XCTAssertTrue(window.subviews.contains(view)) LaunchScreenSnapshot.unprotect() XCTAssertFalse(window.subviews.contains(view)) } func testViewFromStoryboard() { let window = UIWindow() let launchScreenSnapshot = LaunchScreenSnapshot(bundle: Bundle(identifier: "com.alexruperez.LaunchScreenSnapshot.Example")!) launchScreenSnapshot.window = window launchScreenSnapshot.protect() NotificationCenter.default.post(name: .UIApplicationWillResignActive, object: nil) XCTAssertGreaterThan(window.subviews.count, 0) } }
mit
1bb3a6d58526dc4668a4946bf39d33a4
39.602151
132
0.715837
5.433094
false
true
false
false
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Group/AAGroupTypeController.swift
1
7147
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAGroupTypeViewController: AAContentTableController { fileprivate let isCreation: Bool fileprivate var isChannel: Bool = false fileprivate var isPublic: Bool = false fileprivate var linkSection: AAManagedSection! fileprivate var publicRow: AACommonRow! fileprivate var privateRow: AACommonRow! fileprivate var shortNameRow: AAEditRow! public init(gid: Int, isCreation: Bool) { self.isCreation = isCreation super.init(style: .settingsGrouped) self.gid = gid self.isChannel = group.groupType == ACGroupType.channel() if (isChannel) { navigationItem.title = AALocalized("GroupTypeTitleChannel") } else { navigationItem.title = AALocalized("GroupTypeTitle") } if isCreation { navigationItem.rightBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationNext"), style: .done, target: self, action: #selector(saveDidTap)) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationSave"), style: .done, target: self, action: #selector(saveDidTap)) } } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func tableDidLoad() { self.isPublic = group.shortName.get() != nil _ = section { (s) in if isChannel { s.headerText = AALocalized("GroupTypeTitleChannel").uppercased() if self.isPublic { s.footerText = AALocalized("GroupTypeHintPublicChannel") } else { s.footerText = AALocalized("GroupTypeHintPrivateChannel") } } else { s.headerText = AALocalized("GroupTypeTitle").uppercased() if self.isPublic { s.footerText = AALocalized("GroupTypeHintPublic") } else { s.footerText = AALocalized("GroupTypeHintPrivate") } } self.publicRow = s.common({ (r) in if isChannel { r.content = AALocalized("ChannelTypePublicFull") } else { r.content = AALocalized("GroupTypePublicFull") } r.selectAction = { () -> Bool in if !self.isPublic { self.isPublic = true self.publicRow.rebind() self.privateRow.rebind() if self.isChannel { s.footerText = AALocalized("GroupTypeHintPublicChannel") } else { s.footerText = AALocalized("GroupTypeHintPublic") } self.tableView.reloadSection(0, with: .automatic) self.managedTable.sections.append(self.linkSection) self.tableView.insertSection(1, with: .fade) } return true } r.bindAction = { (r) in if self.isPublic { r.style = .checkmark } else { r.style = .normal } } }) self.privateRow = s.common({ (r) in if isChannel { r.content = AALocalized("ChannelTypePrivateFull") } else { r.content = AALocalized("GroupTypePrivateFull") } r.selectAction = { () -> Bool in if self.isPublic { self.isPublic = false self.publicRow.rebind() self.privateRow.rebind() if self.isChannel { s.footerText = AALocalized("GroupTypeHintPrivateChannel") } else { s.footerText = AALocalized("GroupTypeHintPrivate") } self.tableView.reloadSection(0, with: .automatic) self.managedTable.sections.remove(at: 1) self.tableView.deleteSection(1, with: .fade) } return true } r.bindAction = { (r) in if !self.isPublic { r.style = .checkmark } else { r.style = .normal } } }) } self.linkSection = section { (s) in if self.isChannel { s.footerText = AALocalized("GroupTypeLinkHintChannel") } else { s.footerText = AALocalized("GroupTypeLinkHint") } self.shortNameRow = s.edit({ (r) in r.autocapitalizationType = .none r.prefix = ActorSDK.sharedActor().invitePrefixShort r.text = self.group.shortName.get() }) } if !self.isPublic { managedTable.sections.remove(at: 1) } } open func saveDidTap() { let nShortName: String? if self.isPublic { if let shortNameVal = self.shortNameRow.text?.trim() { if shortNameVal.length > 0 { nShortName = shortNameVal } else { nShortName = nil } } else { nShortName = nil } } else { nShortName = nil } if nShortName != group.shortName.get() { _ = executePromise(Actor.editGroupShortName(withGid: jint(self.gid), withAbout: nShortName).then({ (r:ARVoid!) in if (self.isCreation) { if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.group(with: jint(self.gid))) { self.navigateDetail(customController) } else { self.navigateDetail(ConversationViewController(peer: ACPeer.group(with: jint(self.gid)))) } self.dismissController() } else { self.navigateBack() } })) } else { if (isCreation) { if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.group(with: jint(self.gid))) { self.navigateDetail(customController) } else { self.navigateDetail(ConversationViewController(peer: ACPeer.group(with: jint(self.gid)))) } self.dismissController() } else { navigateBack() } } } }
agpl-3.0
ff27ea791504b2ccad57792f9c9a2ef9
37.842391
160
0.484399
5.373684
false
false
false
false
bourvill/HydraKit
HydraKit/Classes/Hydra.swift
1
3713
// // Hydra.swift // HydraKit // // Created by maxime marinel on 26/06/2017. // import Foundation public class Hydra { /** Encapsulate result - success: return the T - failure: return error */ public enum Result<T: HydraObject> { case success(Results<T>) case failure(Error) } /// endpoint url let endpoint: String /// session for task let urlSession: URLSessionProtocol /** Create a new hydra query manager - Parameter endpoint: The string endpoint - Parameter urlSession: urlSession needed for task */ public init(endpoint: String, urlSession: URLSessionProtocol) { self.endpoint = endpoint self.urlSession = urlSession } /** Create a new hydra query manager - Parameter endpoint: The string endpoint */ public convenience init (endpoint: String) { self.init(endpoint: endpoint, urlSession: URLSession.shared) } /** Get results from endpoint, a collection of HydraObject - Parameter hydraObject: an object Type conform to protocol HydraObject - Parameter parameters: Optional dictionary with url parameters - Parameter completion: Result from task */ public func get<T: HydraObject>(_ hydraObject: T.Type, parameters: [String:Any] = [:], completion: @escaping (Result<T>) -> Void) { var urlComponents = URLComponents(string: endpoint + hydraObject.hydraPoint()) urlComponents?.queryItems = [] for (key, value) in parameters { urlComponents?.queryItems?.append(URLQueryItem(name: key, value: (String(describing: value)))) } urlSession.dataTask(with: urlComponents!.url!) { data, _, error in guard error == nil else { completion(Result.failure(error!)) return } guard let data = data else { completion(Result.failure(HydraError.emptyData)) print("Data is empty") return } do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] { var members: [T] = [] for member in (json["hydra:member"] as? [[String:Any]]) ?? [] { members.append(hydraObject.init(hydra: member)) } completion(Result.success(Results<T>(hydraObject, json: json))) } } catch let errorjson { print(errorjson) } }.resume() } /** Get one result from endpoint - Parameter hydraObject: an object Type conform to protocol HydraObject - Parameter id: id of ressource - Parameter completion: Result from task */ public func get<T: HydraObject>(_ hydraObject: T.Type, id: Int, completion: @escaping (Result<T>) -> Void) { let url = URL(string: endpoint + hydraObject.hydraPoint() + "/" + String(id)) urlSession.dataTask(with: url!) { data, _, error in guard error == nil else { completion(Result.failure(error!)) return } guard let data = data else { print("Data is empty") return } do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] { completion(Result.success(Results<T>(hydraObject, json: json))) } } catch let errorjson { completion(Result.failure(errorjson)) print(errorjson) } }.resume() } }
mit
c5486efb99e006681c389dc8cfce9918
31.570175
135
0.562618
4.688131
false
false
false
false
BrunoMazzo/CocoaHeadsApp
CocoaHeadsApp/Classes/Events/Models/Event.swift
3
1559
import Foundation import CoreLocation struct Event { let id: Int let name: String let description: String let chapterId: Int let venue: String let date: NSDate let address: String let location: CLLocationCoordinate2D? let passbook: String? let published: Bool let meetupURL: NSURL? } extension Event: JSONParselable { static func withJSON(json: [String : AnyObject]) -> Event? { guard let id = int(json, key: "id"), name = string(json, key: "nome"), description = string(json, key: "descricao"), date = nsdate(json, key: "data"), venue = string(json, key: "local"), address = string(json, key: "endereco"), published = bool(json, key: "published"), chapterId = int(json, key: "cidade_id") else { return nil } var location: CLLocationCoordinate2D? = nil if let latitude = double(json, key: "latitude"), longitude = double(json, key: "longitude") { location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } return Event( id: id, name: name, description: description, chapterId: chapterId, venue: venue, date: date, address: address, location: location, passbook: string(json, key: "passbook"), published: published, meetupURL: url(json, key: "meetup") ) } }
mit
ec508a796bd2edc4225557cf28a2f51e
29
101
0.552919
4.441595
false
false
false
false
apple/swift-argument-parser
Tests/ArgumentParserEndToEndTests/SourceCompatEndToEndTests.swift
1
10322
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import XCTest import ArgumentParserTestHelpers import ArgumentParser /// The goal of this test class is to validate source compatibility. By running /// this class's tests, all property wrapper initializers should be called. final class SourceCompatEndToEndTests: XCTestCase {} // MARK: - Property Wrapper Initializers fileprivate struct AlmostAllArguments: ParsableArguments { @Argument(help: "") var a_newDefaultSyntax: Int = 0 @Argument() var a0: Int @Argument(help: "") var a1: Int @Argument var a2_newDefaultSyntax: Int = 0 @Argument(help: "", transform: { _ in 0 }) var b_newDefaultSyntax: Int = 0 @Argument var b1_newDefaultSyntax: Int = 0 @Argument(help: "") var b2: Int @Argument(transform: { _ in 0 }) var b3: Int @Argument(help: "", transform: { _ in 0 }) var b4: Int @Argument(transform: { _ in 0 }) var b5_newDefaultSyntax: Int = 0 @Argument(help: "") var b6_newDefaultSyntax: Int = 0 @Argument() var c0: Int? @Argument(help: "") var c1: Int? @Argument(help: "") var d2: Int? @Argument(transform: { _ in 0 }) var d3: Int? @Argument(help: "", transform: { _ in 0 }) var d4: Int? @Argument(parsing: .remaining, help: "") var e: [Int] = [1, 2] @Argument(parsing: .remaining, help: "") var e1: [Int] @Argument(parsing: .remaining) var e2: [Int] = [1, 2] @Argument(help: "") var e3: [Int] = [1, 2] @Argument() var e4: [Int] @Argument(help: "") var e5: [Int] @Argument(parsing: .remaining) var e6: [Int] @Argument() var e7: [Int] = [1, 2] @Argument(parsing: .remaining, help: "", transform: { _ in 0 }) var e8: [Int] = [1, 2] @Argument(parsing: .remaining, help: "", transform: { _ in 0 }) var e9: [Int] @Argument(parsing: .remaining, transform: { _ in 0 }) var e10: [Int] = [1, 2] @Argument(help: "", transform: { _ in 0 }) var e11: [Int] = [1, 2] @Argument(transform: { _ in 0 }) var e12: [Int] @Argument(help: "", transform: { _ in 0 }) var e13: [Int] @Argument(parsing: .remaining, transform: { _ in 0 }) var e14: [Int] @Argument(transform: { _ in 0 }) var e15: [Int] = [1, 2] } fileprivate struct AllOptions: ParsableArguments { @Option(name: .long, parsing: .next, help: "") var a_newDefaultSyntax: Int = 0 @Option(parsing: .next, help: "") var a1_newDefaultSyntax: Int = 0 @Option(name: .long, parsing: .next, help: "") var a2: Int @Option(name: .long, help: "") var a3_newDefaultSyntax: Int = 0 @Option(parsing: .next, help: "") var a4: Int @Option(help: "") var a5_newDefaultSyntax: Int = 0 @Option(parsing: .next) var a6_newDefaultSyntax: Int = 0 @Option(name: .long, help: "") var a7: Int @Option(name: .long, parsing: .next) var a8: Int @Option(name: .long) var a9_newDefaultSyntax: Int = 0 @Option(name: .long) var a10: Int @Option var a11_newDefaultSyntax: Int = 0 @Option(parsing: .next) var a12: Int @Option(help: "") var a13: Int @Option(name: .long, parsing: .next, help: "") var b2: Int? @Option(parsing: .next, help: "") var b4: Int? @Option(name: .long, help: "") var b7: Int? @Option(name: .long, parsing: .next) var b8: Int? @Option(name: .long) var b10: Int? @Option(parsing: .next) var b12: Int? @Option(help: "") var b13: Int? @Option(name: .long, parsing: .next, help: "", transform: { _ in 0 }) var c_newDefaultSyntax: Int = 0 @Option(parsing: .next, help: "", transform: { _ in 0 }) var c1_newDefaultSyntax: Int = 0 @Option(name: .long, parsing: .next, help: "", transform: { _ in 0 }) var c2: Int @Option(name: .long, help: "", transform: { _ in 0 }) var c3_newDefaultSyntax: Int = 0 @Option(parsing: .next, help: "", transform: { _ in 0 }) var c4: Int @Option(help: "", transform: { _ in 0 }) var c5_newDefaultSyntax: Int = 0 @Option(parsing: .next, transform: { _ in 0 }) var c6_newDefaultSyntax: Int = 0 @Option(name: .long, help: "", transform: { _ in 0 }) var c7: Int @Option(name: .long, parsing: .next, transform: { _ in 0 }) var c8: Int @Option(name: .long, transform: { _ in 0 }) var c9_newDefaultSyntax: Int = 0 @Option(name: .long, transform: { _ in 0 }) var c10: Int @Option(transform: { _ in 0 }) var c11_newDefaultSyntax: Int = 0 @Option(parsing: .next, transform: { _ in 0 }) var c12: Int @Option(help: "", transform: { _ in 0 }) var c13: Int @Option(name: .long, parsing: .next, help: "", transform: { _ in 0 }) var d2: Int? @Option(parsing: .next, help: "", transform: { _ in 0 }) var d4: Int? @Option(name: .long, help: "", transform: { _ in 0 }) var d7: Int? @Option(name: .long, parsing: .next, transform: { _ in 0 }) var d8: Int? @Option(name: .long, transform: { _ in 0 }) var d10: Int? @Option(parsing: .next, transform: { _ in 0 }) var d12: Int? @Option(help: "", transform: { _ in 0 }) var d13: Int? @Option(name: .long, parsing: .singleValue, help: "") var e: [Int] = [1, 2] @Option(parsing: .singleValue, help: "") var e1: [Int] = [1, 2] @Option(name: .long, parsing: .singleValue, help: "") var e2: [Int] @Option(name: .long, help: "") var e3: [Int] = [1, 2] @Option(parsing: .singleValue, help: "") var e4: [Int] @Option(help: "") var e5: [Int] = [1, 2] @Option(parsing: .singleValue) var e6: [Int] = [1, 2] @Option(name: .long, help: "") var e7: [Int] @Option(name: .long, parsing: .singleValue) var e8: [Int] @Option(name: .long) var e9: [Int] = [1, 2] @Option(name: .long) var e10: [Int] @Option() var e11: [Int] = [1, 2] @Option(parsing: .singleValue) var e12: [Int] @Option(help: "") var e13: [Int] @Option(name: .long, parsing: .singleValue, help: "", transform: { _ in 0 }) var f: [Int] = [1, 2] @Option(parsing: .singleValue, help: "", transform: { _ in 0 }) var f1: [Int] = [1, 2] @Option(name: .long, parsing: .singleValue, help: "", transform: { _ in 0 }) var f2: [Int] @Option(name: .long, help: "", transform: { _ in 0 }) var f3: [Int] = [1, 2] @Option(parsing: .singleValue, help: "", transform: { _ in 0 }) var f4: [Int] @Option(help: "", transform: { _ in 0 }) var f5: [Int] = [1, 2] @Option(parsing: .singleValue, transform: { _ in 0 }) var f6: [Int] = [1, 2] @Option(name: .long, help: "", transform: { _ in 0 }) var f7: [Int] @Option(name: .long, parsing: .singleValue, transform: { _ in 0 }) var f8: [Int] @Option(name: .long, transform: { _ in 0 }) var f9: [Int] = [1, 2] @Option(name: .long, transform: { _ in 0 }) var f10: [Int] @Option(transform: { _ in 0 }) var f11: [Int] = [1, 2] @Option(parsing: .singleValue, transform: { _ in 0 }) var f12: [Int] @Option(help: "", transform: { _ in 0 }) var f13: [Int] } struct AllFlags: ParsableArguments { enum E: String, EnumerableFlag { case one, two, three } @Flag(name: .long, help: "") var a_explicitFalse: Bool = false @Flag() var a0_explicitFalse: Bool = false @Flag(name: .long) var a1_explicitFalse: Bool = false @Flag(help: "") var a2_explicitFalse: Bool = false @Flag(name: .long, inversion: .prefixedNo, exclusivity: .chooseLast, help: "") var b: Bool @Flag(inversion: .prefixedNo, exclusivity: .chooseLast, help: "") var b1: Bool @Flag(name: .long, inversion: .prefixedNo, help: "") var b2: Bool @Flag(name: .long, inversion: .prefixedNo, exclusivity: .chooseLast) var b3: Bool @Flag(inversion: .prefixedNo, help: "") var b4: Bool @Flag(inversion: .prefixedNo, exclusivity: .chooseLast) var b5: Bool @Flag(name: .long, inversion: .prefixedNo) var b6: Bool @Flag(inversion: .prefixedNo) var b7: Bool @Flag(name: .long, inversion: .prefixedNo, exclusivity: .chooseLast, help: "") var c_newDefaultSyntax: Bool = false @Flag(inversion: .prefixedNo, exclusivity: .chooseLast, help: "") var c1_newDefaultSyntax: Bool = false @Flag(name: .long, inversion: .prefixedNo, help: "") var c2_newDefaultSyntax: Bool = false @Flag(name: .long, inversion: .prefixedNo, exclusivity: .chooseLast) var c3_newDefaultSyntax: Bool = false @Flag(inversion: .prefixedNo, help: "") var c4_newDefaultSyntax: Bool = false @Flag(inversion: .prefixedNo, exclusivity: .chooseLast) var c5_newDefaultSyntax: Bool = false @Flag(name: .long, inversion: .prefixedNo) var c6_newDefaultSyntax: Bool = false @Flag(inversion: .prefixedNo) var c7_newDefaultSyntax: Bool = false @Flag(name: .long, inversion: .prefixedNo, exclusivity: .chooseLast, help: "") var d_implicitNil: Bool @Flag(inversion: .prefixedNo, exclusivity: .chooseLast, help: "") var d1_implicitNil: Bool @Flag(name: .long, inversion: .prefixedNo, help: "") var d2_implicitNil: Bool @Flag(name: .long, inversion: .prefixedNo, exclusivity: .chooseLast) var d3_implicitNil: Bool @Flag(inversion: .prefixedNo, help: "") var d4_implicitNil: Bool @Flag(inversion: .prefixedNo, exclusivity: .chooseLast) var d5_implicitNil: Bool @Flag(name: .long, inversion: .prefixedNo) var d6_implicitNil: Bool @Flag(inversion: .prefixedNo) var d7_implicitNil: Bool @Flag(name: .long, help: "") var e: Int @Flag() var e0: Int @Flag(name: .long) var e1: Int @Flag(help: "") var e2: Int @Flag(exclusivity: .chooseLast, help: "") var f_newDefaultSyntax: E = .one @Flag() var f1: E @Flag(exclusivity: .chooseLast, help: "") var f2: E @Flag(help: "") var f3_newDefaultSyntax: E = .one @Flag(exclusivity: .chooseLast) var f4_newDefaultSyntax: E = .one @Flag(help: "") var f5: E @Flag(exclusivity: .chooseLast) var f6: E @Flag var f7_newDefaultSyntax: E = .one @Flag(exclusivity: .chooseLast, help: "") var g: E? @Flag() var g1: E? @Flag(help: "") var g2: E? @Flag(exclusivity: .chooseLast) var g3: E? @Flag(help: "") var h: [E] = [] @Flag() var h1: [E] = [] @Flag(help: "") var h2: [E] @Flag() var h3: [E] } extension SourceCompatEndToEndTests { func testParsingAll() throws { // This is just checking building the argument definitions, not the actual // validation or usage of these definitions, which would fail. _ = AlmostAllArguments() _ = AllOptions() _ = AllFlags() } }
apache-2.0
3df723bad87556e751f74e97dfa701e2
48.152381
117
0.629239
3.037669
false
false
false
false
mikaelm1/Teach-Me-Fast
Teach Me Fast/CommentCell.swift
1
3371
// // PostDetailCell.swift // Teach Me Fast // // Created by Mikael Mukhsikaroyan on 6/24/16. // Copyright © 2016 MSquaredmm. All rights reserved. // import UIKit class CommentCell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() //setupViews() } let containerView: CustomView = { let v = CustomView() return v }() let profileImageView: UIImageView = { let imgView = UIImageView() imgView.contentMode = .scaleAspectFill imgView.layer.cornerRadius = 15 imgView.layer.masksToBounds = true imgView.contentMode = .scaleAspectFill imgView.image = UIImage(named: "profile_placeholder") return imgView }() let usernameLabel: UILabel = { let lbl = UILabel() lbl.text = "Username" lbl.font = UIFont.systemFont(ofSize: 14) return lbl }() let timestampLabel: UILabel = { let lbl = UILabel() lbl.text = "6/12/2016" lbl.font = UIFont.systemFont(ofSize: 14) return lbl }() let commentView: UITextView = { let v = UITextView() v.font = UIFont.systemFont(ofSize: 12) v.isUserInteractionEnabled = false v.layer.backgroundColor = UIColor.clear().cgColor v.text = "This is where the comment will be. This is just a placeholder." return v }() func setupViews() { backgroundColor = UIColor.white() addSubview(containerView) containerView.addSubview(profileImageView) containerView.addSubview(usernameLabel) containerView.addSubview(timestampLabel) containerView.addSubview(commentView) addConstraintsWithFormat(format: "H:|-5-[v0]-5-|", views: containerView) addConstraintsWithFormat(format: "V:|-5-[v0]-5-|", views: containerView) containerView.addConstraintsWithFormat(format: "H:|-5-[v0(30)]-5-[v1(100)]-5-[v2(100)]", views: profileImageView, usernameLabel, timestampLabel) containerView.addConstraintsWithFormat(format: "H:|-5-[v0]-5-|", views: commentView) containerView.addConstraintsWithFormat(format: "V:|-5-[v0(30)]-10-[v1]-10-|", views: profileImageView, commentView) containerView.addConstraintsWithFormat(format: "V:|-10-[v0(30)]", views: usernameLabel) containerView.addConstraintsWithFormat(format: "V:|-10-[v0(30)]", views: timestampLabel) } func configureCell(comment: Comment) { timestampLabel.text = comment.timestamp commentView.text = comment.commentContent usernameLabel.text = comment.userName setupViews() if let url = comment.userProfilePhotoUrl { FirebaseClient.sharedInstance.storageRefProfileImages.child(url).data(withMaxSize: INT64_MAX, completion: { (data, error) in if let err = error { print("Error downloading user profile photo for comment: \(err)") return } guard let data = data else { print("Data for profile photo was nil") return } self.profileImageView.image = UIImage(data: data) }) } } }
mit
2b03382b18042320eee4577d5aabcc6d
31.718447
152
0.597923
4.919708
false
false
false
false
ifLab/WeCenterMobile-iOS
WeCenterMobile/AppDelegate.swift
3
3374
// // AppDelegate.swift // WeCenterMobile // // Created by Darren Liu on 14/7/14. // Copyright (c) 2014年 ifLab. All rights reserved. // import AFNetworking import CoreData import DTCoreText import DTFoundation import SinaWeiboSDK import SVProgressHUD import UIKit import WeChatSDK let userStrings: (String) -> String = { return NSLocalizedString($0, tableName: "User", comment: "") } let discoveryStrings: (String) -> String = { return NSLocalizedString($0, tableName: "Discovery", comment: "") } let welcomeStrings: (String) -> String = { return NSLocalizedString($0, tableName: "Welcome", comment: "") } var appDelegate: AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { lazy var window: UIWindow? = { let v = UIWindow(frame: UIScreen.mainScreen().bounds) return v }() lazy var loginViewController: LoginViewController = { let vc = NSBundle.mainBundle().loadNibNamed("LoginViewController", owner: nil, options: nil).first as! LoginViewController return vc }() var cacheFileURL: NSURL { let directory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last! let url = directory.URLByAppendingPathComponent("WeCenterMobile.sqlite") return url } var mainViewController: MainViewController! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // clearCaches() UIScrollView.msr_installPanGestureTranslationAdjustmentExtension() UIScrollView.msr_installTouchesCancellingExtension() AFNetworkActivityIndicatorManager.sharedManager().enabled = true DTAttributedTextContentView.setLayerClass(DTTiledLayerWithoutFade.self) SVProgressHUD.setDefaultMaskType(.Gradient) WeiboSDK.registerApp("3758958382") WXApi.registerApp("wx4dc4b980c462893b") NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTheme", name: CurrentThemeDidChangeNotificationName, object: nil) updateTheme() window!.rootViewController = loginViewController window!.makeKeyAndVisible() return true } func applicationWillTerminate(application: UIApplication) { NSNotificationCenter.defaultCenter().removeObserver(self) try! DataManager.defaultManager!.saveChanges() } func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { return WeiboSDK.handleOpenURL(url, delegate: nil) || WXApi.handleOpenURL(url, delegate: nil) } func clearCaches() { NetworkManager.clearCookies() do { try NSFileManager.defaultManager().removeItemAtURL(cacheFileURL) } catch _ { } DataManager.defaultManager = nil DataManager.temporaryManager = nil } func updateTheme() { let theme = SettingsManager.defaultManager.currentTheme mainViewController?.contentViewController.view.backgroundColor = theme.backgroundColorA UINavigationBar.appearance().barStyle = theme.navigationBarStyle UINavigationBar.appearance().tintColor = theme.navigationItemColor } }
gpl-2.0
a9960e009a473305f0b31e9a7dc7db86
33.762887
145
0.710261
5.327014
false
false
false
false
coodly/ios-gambrinus
Packages/Sources/KioskUI/Menu/MenuViewController.swift
1
4870
/* * Copyright 2018 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Assets import KioskCore import Localization import UIKit private enum Accessory { case asc case desc case check case none } private struct MenuOption { let name: String let accessory: Accessory let switchesTo: PostsSortOrder } public class MenuViewController: UIViewController, StoryboardLoaded, PersistenceConsumer { public static var storyboardName: String { return "Menu" } public var persistence: Persistence! private lazy var accessoryDesc = UIImageView(image: Asset.arrowDown.image) private lazy var accessoryAsc = UIImageView(image: Asset.arrowUp.image) private var options: [[MenuOption]] = [[]] { didSet { tableView.reloadData() } } @IBOutlet private var tableView: UITableView! public override func viewDidLoad() { super.viewDidLoad() let powered: MenuFooterView = MenuFooterView.loadInstance() tableView.tableFooterView = powered tableView.registerCell(forType: MenuCell.self) } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let activeSort = persistence.mainContext.sortOrder let sortByPost = activeSort == .byPostName let sortByScore = activeSort == .byRBScore let sortByUntappd = activeSort == .byUntappd var sortOptions = [MenuOption]() if activeSort == .byDateAsc { sortOptions.append(MenuOption(name: L10n.Menu.Controller.Sort.By.date, accessory: .asc, switchesTo: .byDateDesc)) } else if activeSort == .byDateDesc { sortOptions.append(MenuOption(name: L10n.Menu.Controller.Sort.By.date, accessory: .desc, switchesTo: .byDateAsc)) } else { sortOptions.append(MenuOption(name: L10n.Menu.Controller.Sort.By.date, accessory: .none, switchesTo: .byDateDesc)) } sortOptions.append(MenuOption(name: L10n.Menu.Controller.Sort.By.posts, accessory: sortByPost ? .check : .none, switchesTo: .byPostName)) sortOptions.append(MenuOption(name: L10n.Menu.Controller.Sort.By.score, accessory: sortByScore ? .check : .none, switchesTo: .byRBScore)) sortOptions.append(MenuOption(name: L10n.Menu.Controller.Sort.By.untappd, accessory: sortByUntappd ? .check : .none, switchesTo: .byUntappd)) self.options = [sortOptions] } } extension MenuViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return options.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options[section].count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: MenuCell = tableView.dequeueReusableCell(for: indexPath) let option = options[indexPath.section][indexPath.row] cell.textLabel?.text = option.name if option.accessory == .check { cell.accessoryType = .checkmark cell.accessoryView = nil } else if option.accessory == .desc { cell.accessoryType = .none cell.accessoryView = accessoryDesc } else if option.accessory == .asc { cell.accessoryType = .none cell.accessoryView = accessoryAsc } else { cell.accessoryView = nil cell.accessoryType = .none } return cell } } extension MenuViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let option = options[indexPath.section][indexPath.row] NotificationCenter.default.post(name: .closeMenu, object: nil) persistence.write() { context in context.sortOrder = option.switchesTo } } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return L10n.Menu.Controller.Sort.Section.title } return nil } }
apache-2.0
09b7c1d2b404f0250fba1e3edb313ccc
34.547445
149
0.662218
4.611742
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Unit/Editing/Controller/UnitEditingController.swift
1
19153
// // UnitEditingController.swift // DereGuide // // Created by zzk on 2017/6/16. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit import EasyTipView import CoreData import AudioToolbox protocol UnitEditingControllerDelegate: class { func unitEditingController(_ unitEditingController: UnitEditingController, didModify units: Set<Unit>) } class UnitEditingController: BaseViewController { weak var delegate: UnitEditingControllerDelegate? var collectionView: UICollectionView! var titleLabel: UILabel! var editableView = MemberGroupView() lazy var context: NSManagedObjectContext = self.parentContext.newChildContext() fileprivate var parentContext: NSManagedObjectContext { return CoreDataStack.default.viewContext } private var observer: ManagedObjectObserver? var parentUnit: Unit? { didSet { if let unit = parentUnit { observer = ManagedObjectObserver(object: unit, changeHandler: { [weak self] (type) in if type == .delete { self?.navigationController?.popViewController(animated: true) } }) setup(withParentUnit: unit) } } } var unit: Unit? var members = [Int: Member]() lazy var recentMembers: [Member] = { return self.generateRecentMembers() }() fileprivate func fetchAllUnitsOfParentContext() -> [Unit] { let request: NSFetchRequest<Unit> = Unit.sortedFetchRequest request.returnsObjectsAsFaults = false let units = try! parentContext.fetch(request) return units } fileprivate func generateRecentMembers() -> [Member] { var members = [Member]() let units = fetchAllUnitsOfParentContext() for unit in units { for i in 0..<(UnitEditingAdvanceOptionsManager.default.includeGuestLeaderInRecentUsedIdols ? 6 : 5) { let member = unit[i] if !members.contains{$0 == member} { members.append(member) } } } return members } lazy var cardSelectionViewController: UnitCardSelectTableViewController = { let vc = UnitCardSelectTableViewController() vc.delegate = self return vc }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white prepareToolbar() prepareNavigationBar() automaticallyAdjustsScrollViewInsets = false let layout = UICollectionViewFlowLayout() collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) let maxWidth = min(floor((Screen.shortSide - 70) / 6), 96) layout.itemSize = CGSize(width: maxWidth, height: maxWidth + 29) collectionView.backgroundColor = UIColor.white collectionView.delegate = self collectionView.dataSource = self collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) collectionView.register(RecentUsedMemberCell.self, forCellWithReuseIdentifier: RecentUsedMemberCell.description()) layout.minimumLineSpacing = 10 layout.minimumInteritemSpacing = 10 view.addSubview(collectionView) titleLabel = UILabel() titleLabel.text = NSLocalizedString("最近使用", comment: "") view.addSubview(titleLabel) titleLabel.font = UIFont.systemFont(ofSize: 16) titleLabel.snp.makeConstraints { (make) in make.top.equalTo(topLayoutGuide.snp.bottom).offset(10) make.left.equalTo(10) } let infoButton = UIButton(type: .detailDisclosure) view.addSubview(infoButton) infoButton.snp.makeConstraints { (make) in make.right.equalTo(-10) make.centerY.equalTo(titleLabel) } infoButton.addTarget(self, action: #selector(handleInfoButton), for: .touchUpInside) editableView.delegate = self editableView.backgroundColor = Color.cool.mixed(withColor: .white, weight: 0.9) view.addSubview(editableView) editableView.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.bottom.equalTo(bottomLayoutGuide.snp.top) } else { make.bottom.equalTo(traitCollection.verticalSizeClass == .compact ? -32 : -44) } make.left.right.equalToSuperview() } collectionView.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom) make.left.right.equalToSuperview() make.bottom.equalTo(editableView.snp.top) } collectionView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .vertical) editableView.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .vertical) collectionView.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical) editableView.setContentHuggingPriority(UILayoutPriority.defaultLow, for: .vertical) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (context) in self.editableView.snp.updateConstraints { (update) in if #available(iOS 11.0, *) { } else { update.bottom.equalTo(self.traitCollection.verticalSizeClass == .compact ? -32 : -44) } } self.view.layoutIfNeeded() }, completion: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if UserDefaults.standard.firstTimeUsingUnitEditingPage { showHelpTips() UserDefaults.standard.firstTimeUsingUnitEditingPage = false } } func prepareToolbar() { let item1 = UIBarButtonItem(title: NSLocalizedString("高级选项", comment: ""), style: .plain, target: self, action: #selector(openAdvanceOptions)) let spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let item2 = UIBarButtonItem(title: NSLocalizedString("队伍模板", comment: ""), style: .plain, target: self, action: #selector(openTemplates)) toolbarItems = [item1, spaceItem, item2] } @objc func openAdvanceOptions() { let vc = UnitCardSelectionAdvanceOptionsController() vc.delegate = self navigationController?.pushViewController(vc, animated: true) } @objc func openTemplates() { let vc = UnitTemplateController() vc.parentContext = self.context vc.delegate = self navigationController?.pushViewController(vc, animated: true) } @objc func handleInfoButton() { showHelpTips() } var tip1: EasyTipView! var tip2: EasyTipView! var maskView: UIView? private func showHelpTips() { if tip1 == nil || tip2 == nil { var preferences = EasyTipView.Preferences() preferences.drawing.font = UIFont.boldSystemFont(ofSize: 14) preferences.drawing.foregroundColor = UIColor.white preferences.drawing.backgroundColor = Color.cute if Screen.width < 375 { preferences.positioning.maxWidth = Screen.width - 40 } tip1 = EasyTipView(text: NSLocalizedString("最近使用中将潜能和特技等级相同的同一张卡视作同一偶像。单击将偶像添加至底部编辑区域。长按编辑偶像的潜能和特技等级,会自动更新所有包含该偶像的队伍。另外该偶像的潜能等级会自动同步到同角色所有卡片(此功能高级选项中可关闭)", comment: ""), preferences: preferences, delegate: nil) preferences.drawing.backgroundColor = Color.passion tip2 = EasyTipView(text: NSLocalizedString("单击选择要修改的位置,双击可以从全部卡片中选择,长按可以编辑潜能和技能等级", comment: ""), preferences: preferences, delegate: nil) } tip1.show(forView: titleLabel) tip2.show(forView: editableView) maskView = UIView() navigationController?.view.addSubview(maskView!) maskView?.snp.makeConstraints { (make) in make.edges.equalToSuperview() } maskView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hideHelpTips))) } @objc func hideHelpTips() { tip1?.dismiss() tip2?.dismiss() maskView?.removeFromSuperview() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) hideHelpTips() } fileprivate func setup(withParentUnit unit: Unit) { self.unit = context.object(with: unit.objectID) as? Unit for i in 0...5 { self.members[i] = self.unit?.orderedMembers[i] } editableView.setup(with: unit) } @objc func saveUnit() { if self.unit != nil { context.saveOrRollback() parentContext.saveOrRollback() navigationController?.popViewController(animated: true) } else { if members.values.count == 6 { Unit.insert(into: context, members: members.sorted{ $0.key < $1.key }.map { $0.value }) context.saveOrRollback() parentContext.saveOrRollback() navigationController?.popViewController(animated: true) } else { let alvc = UIAlertController.init(title: NSLocalizedString("队伍不完整", comment: "弹出框标题"), message: NSLocalizedString("请完善队伍后,再点击存储", comment: "弹出框正文"), preferredStyle: .alert) alvc.addAction(UIAlertAction.init(title: NSLocalizedString("确定", comment: "弹出框按钮"), style: .cancel, handler: nil)) self.tabBarController?.present(alvc, animated: true, completion: nil) } } } private func prepareNavigationBar() { let saveItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveUnit)) saveItem.style = .done navigationItem.rightBarButtonItem = saveItem navigationItem.title = NSLocalizedString("编辑队伍", comment: "") } fileprivate func reload(index: Int) { if let member = members[index] { editableView.setup(with: member, at: index) } } fileprivate func createOrReplaceMember(cardID: Int, skillLevel: Int, potential: CGSSPotential, at index: Int) { let member: Member if members[index] != nil { member = members[index]! member.setBy(cardID: cardID, skillLevel: skillLevel, potential: potential) } else { member = Member.insert(into: context, cardID: cardID, skillLevel: skillLevel, potential: potential, participatedPostion: index) members[index] = member } if index == 0 && members[5] == nil { createOrReplaceMember(cardID: cardID, skillLevel: skillLevel, potential: potential, at: 5) } reload(index: index) } } extension UnitEditingController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recentMembers.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecentUsedMemberCell.description(), for: indexPath) as! RecentUsedMemberCell cell.delegate = self cell.setup(with: recentMembers[indexPath.item]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let member = recentMembers[indexPath.item] createOrReplaceMember(cardID: Int(member.cardID), skillLevel: Int(member.skillLevel), potential: member.potential, at: editableView.currentIndex) editableView.moveIndexToNext() } } extension UnitEditingController: RecentUsedMemberCellDelegate { func didLongPressAt(_ recentUsedMemberCell: RecentUsedMemberCell) { guard let index = collectionView.indexPath(for: recentUsedMemberCell)?.item else { return } let tevc = MemberEditingViewController() tevc.modalPresentationStyle = .popover tevc.preferredContentSize = CGSize.init(width: 240, height: 350) let member = recentMembers[index] guard let card = member.card else { return } tevc.setupWith(member: member, card: card) let pc = tevc.popoverPresentationController pc?.delegate = self pc?.permittedArrowDirections = .any pc?.sourceView = recentUsedMemberCell pc?.sourceRect = CGRect.init(x: recentUsedMemberCell.fwidth / 2, y: recentUsedMemberCell.fheight / 2, width: 0, height: 0) present(tevc, animated: true, completion: nil) // play sound like peek(3d touch) AudioServicesPlaySystemSound(1519) } } extension UnitEditingController: MemberGroupViewDelegate { func memberEditableView(_ memberGroupView: MemberGroupView, didDoubleTap item: MemberEditableItemView) { navigationController?.pushViewController(cardSelectionViewController, animated: true) } func memberGroupView(_ memberGroupView: MemberGroupView, didLongPressAt item: MemberEditableItemView) { guard let index = memberGroupView.editableItemViews.index(of: item), let _ = members[index] else { return } let tevc = MemberEditingViewController() tevc.modalPresentationStyle = .popover tevc.preferredContentSize = CGSize.init(width: 240, height: 350) guard let member = members[index], let card = member.card else { return } tevc.setupWith(member: member, card: card) let pc = tevc.popoverPresentationController pc?.delegate = self pc?.permittedArrowDirections = .down pc?.sourceView = item pc?.sourceRect = CGRect.init(x: item.fwidth / 2, y: 0, width: 0, height: 0) present(tevc, animated: true, completion: nil) // play sound like peek(3d touch) AudioServicesPlaySystemSound(1519) } } extension UnitEditingController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } /// commit the change to idols skill level and potential levels /// /// - Parameters: /// - member: unit member need to commit /// - vc: view controller that holds new data /// - modifySkill: modify skill level or not (when the commit is synced by another card of the same chara, need not to modify skill level fileprivate func modify(_ member: Member, using vc: MemberEditingViewController, modifySkill: Bool = true) { if modifySkill { member.skillLevel = Int16(round(vc.editView.skillStepper.value)) } member.vocalLevel = Int16(round(vc.editView.vocalStepper.value)) member.danceLevel = Int16(round(vc.editView.danceStepper.value)) member.visualLevel = Int16(round(vc.editView.visualStepper.value)) member.lifeLevel = Int16(round(vc.editView.lifeStepper.value)) } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { let vc = popoverPresentationController.presentedViewController as! MemberEditingViewController if let sourceView = popoverPresentationController.sourceView as? RecentUsedMemberCell { if let index = collectionView.indexPath(for: sourceView)?.item { let selectedMember = recentMembers[index] let units = fetchAllUnitsOfParentContext() var modifiedUnits = Set<Unit>() for unit in units { for i in 0..<(UnitEditingAdvanceOptionsManager.default.includeGuestLeaderInRecentUsedIdols ? 6 : 5) { let member = unit[i] if member == selectedMember { modify(member, using: vc) modifiedUnits.insert(unit) } else if UnitEditingAdvanceOptionsManager.default.editAllSameChara && member.card?.charaId == selectedMember.card?.charaId { modify(member, using: vc, modifySkill: false) modifiedUnits.insert(unit) } } } parentContext.saveOrRollback() delegate?.unitEditingController(self, didModify: modifiedUnits) NotificationCenter.default.post(name: .unitModified, object: nil) collectionView.reloadData() } } else if let _ = popoverPresentationController.sourceView as? MemberEditableItemView { if let member = members[editableView.currentIndex] { modify(member, using: vc) reload(index: editableView.currentIndex) } } } } extension UnitEditingController: BaseCardTableViewControllerDelegate { func selectCard(_ card: CGSSCard) { let skillLevel = UnitEditingAdvanceOptionsManager.default.defaultSkillLevel let potentialLevel = UnitEditingAdvanceOptionsManager.default.defaultPotentialLevel createOrReplaceMember(cardID: card.id, skillLevel: skillLevel, potential: card.properPotentialByLevel(potentialLevel), at: editableView.currentIndex) } } extension UnitEditingController: UnitCardSelectionAdvanceOptionsControllerDelegate { func recentUsedIdolsNeedToReload() { self.recentMembers = generateRecentMembers() collectionView.reloadData() } } extension UnitEditingController: UnitTemplateControllerDelegate { func unitTemplateController(_ unitTemplateController: UnitTemplateController, didSelect unit: Unit) { for i in stride(from: 5, through: 0, by: -1) { let member = unit[i] createOrReplaceMember(cardID: Int(member.cardID), skillLevel: Int(member.skillLevel), potential: member.potential, at: i) } } }
mit
52283782aff0a133f8f29b1b779bf311
40.045952
222
0.646444
5.019534
false
false
false
false
mergesort/Communicado
Sources/Communicado/ShareParameters.swift
1
4493
import UIKit /// A protocol for types which share values to a `ShareDestination`. protocol ShareParameters { var shareDestination: ShareDestination { get } } /// Parameters which are used when sharing via the built in `UIActivityViewController`. public struct ActivityShareParameters: ShareParameters { let shareDestination: ShareDestination = ActivityControllerShareDestination() public let activityItems: [Any] public let excludedActivityTypes: [UIActivity.ActivityType]? public let applicationActivites: [UIActivity]? public let completionItemsHandler: UIActivityViewController.CompletionWithItemsHandler? public let sourceView: UIView? public init(activityItems: [Any], excludedActivityTypes: [UIActivity.ActivityType]? = nil, applicationActivites: [UIActivity]? = nil, completionItemsHandler: UIActivityViewController.CompletionWithItemsHandler? = nil, sourceView: UIView? = nil) { self.activityItems = activityItems self.excludedActivityTypes = excludedActivityTypes self.applicationActivites = applicationActivites self.completionItemsHandler = completionItemsHandler self.sourceView = sourceView } } /// Parameters which are used when sharing via the built in `MFMessageComposeViewController`. public struct MessagesShareParameters: ShareParameters { let shareDestination: ShareDestination = MessagesShareDestination() public let message: String? public let attachments: [Attachment]? public init(message: String? = nil, attachments: [Attachment]? = nil) { self.message = message self.attachments = attachments } } /// Parameters which are used when sharing via the built in `MFMailComposeViewController`. public struct MailShareParameters: ShareParameters { let shareDestination: ShareDestination = MailShareDestination() public let subject: String? public let message: String? public let isHTML: Bool public let toRecepients: [String]? public let ccRecepients: [String]? public let bccRecepients: [String]? public let attachments: [Attachment]? public init(subject: String? = nil, message: String? = nil, isHTML: Bool = false, toRecepients: [String]? = nil, ccRecepients: [String]? = nil, bccRecepients: [String]? = nil, attachments: [Attachment]? = nil) { self.subject = subject self.message = message self.isHTML = isHTML self.toRecepients = toRecepients self.ccRecepients = ccRecepients self.bccRecepients = bccRecepients self.attachments = attachments } } /// Parameters which are used when saving a `PasteboardShareParameters.Value` to the user's pasteboard. public struct PasteboardShareParameters: ShareParameters { public enum Value { case string(String?) case image(UIImage?) case url(URL?) } let shareDestination: ShareDestination = PasteboardShareDestination() public let string: String? public let image: UIImage? public let url: URL? public init(value: PasteboardShareParameters.Value) { switch value { case .string(let string): self.string = string self.image = nil self.url = nil case .image(let image): self.image = image self.string = nil self.url = nil case .url(let url): self.url = url self.string = nil self.image = nil } } } /// Parameters which are used when saving an image to the user's camera roll. public struct PhotosShareParameters: ShareParameters { let shareDestination: ShareDestination = PhotosShareDestination() public let image: UIImage public init(image: UIImage) { self.image = image } } /// Parameters which are used when posting to a social network. /// Deprecated in iOS 11, as Apple removed the Social framework, which this was based on. @available(iOS, deprecated: 11.0) public struct SocialShareParameters { public let network: SocialShareDestination public let message: String? public let images: [UIImage]? public let urls: [URL]? public init(network: SocialShareDestination, message: String? = nil, images: [UIImage]? = nil, urls: [URL]? = nil) { self.network = network self.message = message self.images = images self.urls = urls } }
mit
a65eea9e66f3ad93e4861c1dddcbdca9
32.036765
250
0.685288
4.846818
false
false
false
false
jimmy623/Introduction_To_Algorithms_3rd
Charpter 2/2_1_2.playground/section-1.swift
1
614
import XCPlayground var data = [31,41,59,26,41,58] func insertionSort(inout data:[Int]) { for index in 1 ..< data.count { for sortedIndex in 0 ..< index { if data[index] > data[sortedIndex] { let key = data[index] for var moveIndex = index; moveIndex > sortedIndex; moveIndex-- { data[moveIndex] = data[moveIndex - 1] } data[sortedIndex] = key break } } for value in data { XCPCaptureValue("\(index)",value) } } } insertionSort(&data)
mit
5b94f58b4f5786c0c3a292d98ef9318a
25.695652
81
0.495114
4.293706
false
false
false
false
Scior/Spica
Spica/ImageViewController.swift
1
5577
// // ImageViewController.swift // Spica // // Created by Scior on 2016/10/17. // Copyright © 2017年 Scior All rights reserved. // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { // MARK: プロパティ var photo : Photo? { didSet { image = nil if view.window != nil { fetchImage() } titleLabel.text = photo?.title == "" ? " " : photo?.title userNameLabel.text = photo?.ownerName } } var photos : [Photo]? /// ダウンロードした画像を格納する private var imageHolder : [URL : UIImage] = [:] private var imageView = UIImageView() private var image: UIImage? { get { return imageView.image } set { scrollView?.zoomScale = 1.0 imageView.image = newValue imageView.sizeToFit() if let image = newValue { scrollView?.contentSize = imageView.frame.size scrollView.minimumZoomScale = min(scrollView.frame.size.height / image.size.height, scrollView.frame.size.width / image.size.width) scrollView.zoomScale = scrollView.minimumZoomScale updateScrollInset() } } } private var fetchingURL : URL? @IBOutlet weak var scrollView: UIScrollView! { didSet { scrollView.contentSize = imageView.frame.size scrollView.delegate = self scrollView.minimumZoomScale = 1.0 scrollView.maximumZoomScale = 2.0 } } @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.accessibilityIdentifier = "Title Label" } } @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var exifButton: UIButton! { didSet { exifButton.accessibilityIdentifier = "Exif Button" } } // MARK: - メソッド override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(imageView) } override func viewDidAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChanging(notification:)), name: .UIDeviceOrientationDidChange, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if image == nil { fetchImage() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// スワイプ時の処理 // @IBAction func recognizeSwipe(_ sender: UISwipeGestureRecognizer) { // guard let photo = photo, // let photos = photos, // let index = photos.index(of: photo) else { return } // // let count = photos.count // // if sender.direction == .right { // if index + 1 < count { // self.photo = photos[index + 1] // } // } else if sender.direction == .left { // if index - 1 >= 0 { // self.photo = photos[index - 1] // } // } // } /// ダブルタップの処理 @IBAction func recognizeTap(_ sender: UITapGestureRecognizer) { let scale = scrollView.zoomScale == scrollView.minimumZoomScale ? 1.0 : scrollView.minimumZoomScale UIView.animate(withDuration: 0.5) { self.scrollView.zoomScale = scale } } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { updateScrollInset() } func onOrientationChanging(notification: Notification) { if let image = image { scrollView.minimumZoomScale = min(scrollView.frame.size.height / image.size.height, scrollView.frame.size.width / image.size.width) } } /// 画像を非同期で取得 private func fetchImage() { guard let url = photo?.urls.largeImageURL ?? photo?.urls.originalImageURL else { return } // 既に取得していたらそれを使う if let image = imageHolder[url] { self.image = image return } fetchingURL = url spinner?.startAnimating() DispatchQueue.global(qos: .userInitiated).async { var contentsOfURL : Data? = nil do { contentsOfURL = try Data(contentsOf: url) } catch let error { log?.error(error) self.spinner?.stopAnimating() return } DispatchQueue.main.async { if url == self.fetchingURL, let contents = contentsOfURL { self.image = UIImage(data: contents) self.imageHolder[url] = self.image self.spinner?.stopAnimating() } } } } /// 画像を中央に持ってくるように調整 private func updateScrollInset() { scrollView.contentInset = UIEdgeInsetsMake( max((scrollView.frame.height - imageView.frame.height) / 2, 0), max((scrollView.frame.width - imageView.frame.width) / 2, 0), 0, 0 ) } }
mit
75646da9726ea8bebed8b56ef5ed4d2e
28.423913
161
0.551533
4.895118
false
false
false
false
chrisjmendez/swift-exercises
Basic/Measure Distance.playground/section-1.swift
1
480
// Playground - noun: a place where people can play import UIKit class Distance{ let FEET_PER_METERS = 3.28084 var meters: Double = 0 var feet:Double{ get{ return self.meters * FEET_PER_METERS } set{ self.meters = newValue / FEET_PER_METERS } } init(meters:Double){ self.meters = meters } } let dist = Distance(meters: 34) dist.meters dist.feet dist.feet = 102 dist.meters
mit
20951ffc3563a5de2587dfc18e472905
15.551724
52
0.56875
3.609023
false
false
false
false
savelii/Swift-cfenv
Tests/CloudFoundryEnv/UtilsTests.swift
1
3313
/** * Copyright IBM Corporation 2016 * * 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. **/ #if os(Linux) import Glibc #else import Darwin #endif import XCTest import Foundation import SwiftyJSON @testable import CloudFoundryEnv /** * Online tool for escaping JSON: http://www.freeformatter.com/javascript-escape.html * Online tool for removing new lines: http://www.textfixer.com/tools/remove-line-breaks.php * Online JSON editor: http://jsonviewer.stack.hu/ */ class UtilsTests : XCTestCase { static var allTests : [(String, (UtilsTests) -> () throws -> Void)] { return [ ("testConvertStringToJSON", testConvertStringToJSON), ("testConvertJSONArrayToStringArray", testConvertJSONArrayToStringArray) ] } func testConvertStringToJSON() { let VCAP_APPLICATION = "{ \"users\": null, \"instance_id\": \"7d4f24cfba06462ba23d68aaf1d7354a\", \"instance_index\": 0, \"host\": \"0.0.0.0\", \"port\": 61263, \"started_at\": \"2016-03-04 02:43:07 +0000\", \"started_at_timestamp\": 1457059387 }" if let json = JSONUtils.convertStringToJSON(text: VCAP_APPLICATION) { //print("JSON object is: \(json)") //print("Type is \(json["users"].dynamicType)") XCTAssertNil(json["users"] as? AnyObject) XCTAssertEqual(json["instance_id"], "7d4f24cfba06462ba23d68aaf1d7354a", "instance_id should match.") XCTAssertEqual(json["instance_index"], 0, "instance_index should match.") XCTAssertEqual(json["host"], "0.0.0.0", "host should match.") XCTAssertEqual(json["port"], 61263, "port should match.") XCTAssertEqual(json["started_at"], "2016-03-04 02:43:07 +0000", "started_at should match.") XCTAssertEqual(json["started_at_timestamp"], 1457059387, "started_at_timestamp should match.") } else { XCTFail("Could not generate JSON object!") } } func testConvertJSONArrayToStringArray() { let jsonStr = "{ \"tags\": [ \"data_management\", \"ibm_created\", \"ibm_dedicated_public\" ] }" if let json = JSONUtils.convertStringToJSON(text: jsonStr) { let strArray: [String] = JSONUtils.convertJSONArrayToStringArray(json: json, fieldName: "tags") XCTAssertEqual(strArray.count, 3, "There should be 3 elements in the string array.") UtilsTests.verifyElementInArrayExists(strArray: strArray, element: "data_management") UtilsTests.verifyElementInArrayExists(strArray: strArray, element: "ibm_created") UtilsTests.verifyElementInArrayExists(strArray: strArray, element: "ibm_dedicated_public") } else { XCTFail("Could not generate JSON object!") } } private class func verifyElementInArrayExists(strArray: [String], element: String) { let index: Int? = strArray.index(of: element) XCTAssertNotNil(index, "Array should contain element: \(element)") } }
apache-2.0
6a4d911dfca3a89ab7cefef9400eb94e
41.474359
257
0.703894
3.81682
false
true
false
false
leo150/Pelican
Sources/Pelican/Pelican/Files/Cache+Error.swift
1
823
// // CacheError.swift // Pelican // // Created by Takanu Kyriako on 21/08/2017. // import Foundation // Errors related to update processing. Might merge the two? enum CacheError: String, Error { case BadPath = "Can't build url from path that was provided." case BadBundle = "The cache path for Telegram could not be found. Please ensure Public/ is a folder in your project directory." case WrongType = "The file could not be added because it has the wrong type." case LocalNotFound = "The local resource you attempted to upload could not be found." case RemoteNotFound = "The remote resource you attempted to upload could not be found." case NoBytes = "The resource could not be obtained." } enum CacheFormError: String, Error { case LinkNotFound = "The MessageFile provided had no URL or fileID to use." }
mit
1df94aa07987507154457a86913ee9fc
36.409091
129
0.744836
3.882075
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/OpenTelemetryApi/Baggage/Baggage.swift
1
990
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation /// A map from EntryKey to EntryValue and EntryMetadata that can be used to /// label anything that is associated with a specific operation. /// For example, Baggages can be used to label stats, log messages, or /// debugging information. public protocol Baggage: AnyObject { /// Builder for the Baggage class static func baggageBuilder() -> BaggageBuilder /// Returns an immutable collection of the entries in this Baggage. Order of /// entries is not guaranteed. func getEntries() -> [Entry] /// Returns the EntryValue associated with the given EntryKey. /// - Parameter key: entry key to return the value for. func getEntryValue(key: EntryKey) -> EntryValue? } public func == (lhs: Baggage, rhs: Baggage) -> Bool { guard type(of: lhs) == type(of: rhs) else { return false } return lhs.getEntries().sorted() == rhs.getEntries().sorted() }
apache-2.0
cae3b8068f14a9f36a01ea57151940d7
34.357143
80
0.70303
4.074074
false
false
false
false
manavgabhawala/swift
test/SILGen/foreach.swift
1
22928
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s ////////////////// // Declarations // ////////////////// class C {} @_silgen_name("loopBodyEnd") func loopBodyEnd() -> () @_silgen_name("condition") func condition() -> Bool @_silgen_name("loopContinueEnd") func loopContinueEnd() -> () @_silgen_name("loopBreakEnd") func loopBreakEnd() -> () @_silgen_name("funcEnd") func funcEnd() -> () struct TrivialStruct { var value: Int32 } struct NonTrivialStruct { var value: C } struct GenericStruct<T> { var value: T var value2: C } protocol P {} protocol ClassP : class {} protocol GenericCollection : Collection { } /////////// // Tests // /////////// //===----------------------------------------------------------------------===// // Trivial Struct //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden @_T07foreach13trivialStructySaySiGF : $@convention(thin) (@owned Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK]]: // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach13trivialStructySaySiGF' func trivialStruct(_ xx: [Int]) { for x in xx { loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructContinue(_ xx: [Int]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach26trivialStructContinueBreakySaySiGF : $@convention(thin) (@owned Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @_TFesRxs10Collectionwx8IteratorzGVs16IndexingIteratorx_rS_12makeIteratorfT_GS1_x_ : $@convention(method) <τ_0_0 where τ_0_0 : Collection, τ_0_0.Iterator == IndexingIterator<τ_0_0>> (@in_guaranteed τ_0_0) -> @out IndexingIterator<τ_0_0> // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<Int> // CHECK: store_borrow [[BORROWED_ARRAY]] to [[BORROWED_ARRAY_STACK]] // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[Int]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[FUNC_REF:%.*]] = function_ref @_TFVs16IndexingIterator4nextfT_GSqwx8_Element_ : $@convention(method) // CHECK: [[GET_ELT_STACK:%.*]] = alloc_stack $Optional<Int> // CHECK: apply [[FUNC_REF]]<[Int]>([[GET_ELT_STACK]], [[PROJECT_ITERATOR_BOX]]) // CHECK: [[IND_VAR:%.*]] = load [trivial] [[GET_ELT_STACK]] // CHECK: switch_enum [[IND_VAR]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<Int>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach26trivialStructContinueBreakySaySiGF' func trivialStructContinueBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Existential //===----------------------------------------------------------------------===// func existential(_ xx: [P]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialContinue(_ xx: [P]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach24existentialContinueBreakySayAA1P_pGF : $@convention(thin) (@owned Array<P>) -> () { // CHECK: bb0([[ARRAY:%.*]] : $Array<P>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<P>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @_TFesRxs10Collectionwx8IteratorzGVs16IndexingIteratorx_rS_12makeIteratorfT_GS1_x_ : $@convention(method) <τ_0_0 where τ_0_0 : Collection, τ_0_0.Iterator == IndexingIterator<τ_0_0>> (@in_guaranteed τ_0_0) -> @out IndexingIterator<τ_0_0> // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<P> // CHECK: store_borrow [[BORROWED_ARRAY]] to [[BORROWED_ARRAY_STACK]] // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[P]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<P> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[FUNC_REF:%.*]] = function_ref @_TFVs16IndexingIterator4nextfT_GSqwx8_Element_ : $@convention(method) // CHECK: apply [[FUNC_REF]]<[P]>([[ELT_STACK]], [[PROJECT_ITERATOR_BOX]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<P>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $P, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<P>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<P>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach24existentialContinueBreakySayAA1P_pGF' func existentialContinueBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Class Constrainted Existential //===----------------------------------------------------------------------===// func existentialClass(_ xx: [ClassP]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialClassContinue(_ xx: [ClassP]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialClassBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } func existentialClassContinueBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Generic Struct //===----------------------------------------------------------------------===// func genericStruct<T>(_ xx: [GenericStruct<T>]) { for x in xx { loopBodyEnd() } funcEnd() } func genericStructContinue<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericStructBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach26genericStructContinueBreakySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@owned Array<GenericStruct<T>>) -> () { // CHECK: bb0([[ARRAY:%.*]] : $Array<GenericStruct<T>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0> { var IndexingIterator<Array<GenericStruct<τ_0_0>>> } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @_TFesRxs10Collectionwx8IteratorzGVs16IndexingIteratorx_rS_12makeIteratorfT_GS1_x_ : $@convention(method) <τ_0_0 where τ_0_0 : Collection, τ_0_0.Iterator == IndexingIterator<τ_0_0>> (@in_guaranteed τ_0_0) -> @out IndexingIterator<τ_0_0> // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<GenericStruct<T>> // CHECK: store_borrow [[BORROWED_ARRAY]] to [[BORROWED_ARRAY_STACK]] // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[GenericStruct<T>]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<GenericStruct<T>> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[FUNC_REF:%.*]] = function_ref @_TFVs16IndexingIterator4nextfT_GSqwx8_Element_ : $@convention(method) // CHECK: apply [[FUNC_REF]]<[GenericStruct<T>]>([[ELT_STACK]], [[PROJECT_ITERATOR_BOX]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $GenericStruct<T>, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_value [[ARRAY]] // CHECK: } // end sil function '_T07foreach26genericStructContinueBreakySayAA07GenericC0VyxGGlF' func genericStructContinueBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Fully Generic Collection //===----------------------------------------------------------------------===// func genericCollection<T : Collection>(_ xx: T) { for x in xx { loopBodyEnd() } funcEnd() } func genericCollectionContinue<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericCollectionBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden @_T07foreach30genericCollectionContinueBreakyxs0C0RzlF : $@convention(thin) <T where T : Collection> (@in T) -> () { // CHECK: bb0([[COLLECTION:%.*]] : $*T): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Collection> { var τ_0_0.Iterator } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $T, #Sequence.makeIterator!1 : <Self where Self : Sequence> (Self) -> () -> Self.Iterator : $@convention(witness_method) <τ_0_0 where τ_0_0 : Sequence> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<T>([[PROJECT_ITERATOR_BOX]], [[COLLECTION]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<T.Iterator.Element> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[GET_NEXT_FUNC:%.*]] = witness_method $T.Iterator, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[GET_NEXT_FUNC]]<T.Iterator>([[ELT_STACK]], [[PROJECT_ITERATOR_BOX]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<T.Iterator.Element>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK_JUMP:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $T.Iterator.Element, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<T.Iterator.Element>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[CONT_BLOCK_JUMP]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: destroy_addr [[COLLECTION]] // CHECK: } // end sil function '_T07foreach30genericCollectionContinueBreakyxs0C0RzlF' func genericCollectionContinueBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Pattern Match Tests //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden @_T07foreach13tupleElementsySayAA1CC_ADtGF func tupleElements(_ xx: [(C, C)]) { // CHECK: bb3([[PAYLOAD:%.*]] : $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[COPY_A]] // CHECK: destroy_value [[PAYLOAD]] for (a, b) in xx {} // CHECK: bb7([[PAYLOAD:%.*]] : $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_B]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[COPY_A]] // CHECK: destroy_value [[PAYLOAD]] for (a, _) in xx {} // CHECK: bb11([[PAYLOAD:%.*]] : $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_A]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[PAYLOAD]] for (_, b) in xx {} // CHECK: bb15([[PAYLOAD:%.*]] : $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[COPY_A]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[PAYLOAD]] for (_, _) in xx {} // CHECK: bb19([[PAYLOAD:%.*]] : $(C, C)): // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]] // CHECK: [[A:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 0 // CHECK: [[COPY_A:%.*]] = copy_value [[A]] // CHECK: [[B:%.*]] = tuple_extract [[BORROWED_PAYLOAD]] : $(C, C), 1 // CHECK: [[COPY_B:%.*]] = copy_value [[B]] // CHECK: destroy_value [[COPY_B]] // CHECK: destroy_value [[COPY_A]] // CHECK: end_borrow [[BORROWED_PAYLOAD]] from [[PAYLOAD]] // CHECK: destroy_value [[PAYLOAD]] for _ in xx {} } // Make sure that when we have an unused value, we properly iterate over the // loop rather than run through the loop once. // // CHECK-LABEL: sil hidden @_T07foreach16unusedArgPatternySaySiGF : $@convention(thin) (@owned Array<Int>) -> () { // CHECK: bb0([[ARG:%.*]] : $Array<Int>): // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[OPT_VAL:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAL:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]] func unusedArgPattern(_ xx: [Int]) { for _ in xx { loopBodyEnd() } }
apache-2.0
f551102af071343e554179f2a6e9bdd4
34.499225
290
0.563524
3.27287
false
false
false
false
blackbear/OpenHumansUpload
OpenHumansUpload/OpenHumansUpload/ExportMenu.swift
1
9942
// // MainMenu.swift // OpenHumansUpload // // Created by James Turner on 6/18/16. // Copyright © 2016 Open Humans. All rights reserved. // import UIKit import HealthKitSampleGenerator import HealthKitUI class ExportMenu: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var uploadButton: UIButton! @IBOutlet weak var incrementalButton: UIButton! @IBOutlet weak var editUploadButton: UIButton! @IBOutlet weak var incrementalLabel: UILabel! @IBOutlet weak var progressView1: UIProgressView! var alert : UIAlertController! var fileList : JSONArray = JSONArray() var progressIncrement : Float! let healthStore = HKHealthStore() func updateUI() { self.progressView.hidden = true self.progressView1.hidden = true } override func viewDidLoad() { super.viewDidLoad() self.uploadButton.layer.cornerRadius=5 self.updateUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { } @IBAction func selectData(sender: UIButton) { } @IBAction func editUploaded(sender: AnyObject) { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "uploadToMainMenu" { let vc = segue.destinationViewController as! MainMenu vc.fileList = self.fileList } } @IBOutlet weak var progressView: UIProgressView! func generateMonthData(now : NSDate, currentDate : NSDate) -> Void { let cal = NSCalendar.currentCalendar() var nextMonth = cal.dateByAddingUnit(NSCalendarUnit.Month, value: 1, toDate: currentDate, options: NSCalendarOptions(rawValue: 0)) nextMonth = cal.dateBySettingUnit(NSCalendarUnit.Day, value: 1, ofDate: nextMonth!, options: NSCalendarOptions(rawValue: 0)) var endOfMonth = cal.dateByAddingUnit(NSCalendarUnit.Second, value: -1, toDate: nextMonth!, options: NSCalendarOptions(rawValue: 0)) if (now.compare(endOfMonth!) == .OrderedAscending) { endOfMonth = now } let configuration = HealthDataFullExportConfiguration(profileName: "Profilname", exportType: HealthDataToExportType.ALL, startDate: currentDate, endDate: endOfMonth!) let target = JsonSingleDocInMemExportTarget() // create your instance of HKHeakthStore // and pass it to the HealthKitDataExporter let exporter = HealthKitDataExporter(healthStore: healthStore) exporter.export( exportTargets: [target], exportConfiguration: configuration, onProgress: { (message: String, progressInPercent: NSNumber?) -> Void in dispatch_async(dispatch_get_main_queue(), { self.progressView.progress = (progressInPercent?.floatValue)! }) }, onCompletion: { (error: ErrorType?)-> Void in // output the result - if error is nil. everything went well if error != nil { var continuing = false self.alert = UIAlertController(title: "Export Failed", message: error.debugDescription, preferredStyle: UIAlertControllerStyle.Alert) if error.debugDescription.containsString("Protected health data") { self.alert = UIAlertController(title: "Export Paused", message: "The export will pause if the phone is locked during the operation.", preferredStyle: UIAlertControllerStyle.Alert) continuing = true } self.alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (act) -> Void in if continuing { self.view.userInteractionEnabled = false self.activityIndicator.startAnimating() } })) self.presentViewController(self.alert, animated: true, completion: nil) return } else { let dayTimePeriodFormatter = NSDateFormatter() dayTimePeriodFormatter.dateFormat = "yyyy-MM-dd" var fname = "healthkit-export_" + dayTimePeriodFormatter.stringFromDate(currentDate) fname = fname + "_" + dayTimePeriodFormatter.stringFromDate(endOfMonth!) + "_" fname = fname + String(now.timeIntervalSince1970) + ".json" if (target.hasSamples()) { OH_OAuth2.sharedInstance().uploadFile(fname, data: target.getJsonString(), memberId: OH_OAuth2.sharedInstance().memberId!, handler: { (success: Bool, filename: String?) -> Void in if success { dispatch_async(dispatch_get_main_queue(), { self.progressView1.progress += self.progressIncrement }); self.outputMonth(now, currentDate: nextMonth!) let defs = NSUserDefaults.standardUserDefaults() if endOfMonth?.compare(now) == .OrderedAscending { defs.setObject(endOfMonth, forKey: "lastSaveDate") } else { defs.setObject(now, forKey: "lastSaveDate") } } else { self.view.userInteractionEnabled = true self.activityIndicator.stopAnimating() self.alert = UIAlertController(title: "Upload Failed", message: "The upload failed, please try again later.", preferredStyle: UIAlertControllerStyle.Alert) self.alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(self.alert, animated: true, completion: nil) return } }) } else { dispatch_async(dispatch_get_main_queue(), { self.progressView1.progress += self.progressIncrement }); self.outputMonth(now, currentDate: nextMonth!) let defs = NSUserDefaults.standardUserDefaults() defs.setObject(endOfMonth, forKey: "lastSaveDate") } } }) } func outputMonth(now : NSDate, currentDate : NSDate) -> Void { if currentDate.compare(now) != NSComparisonResult.OrderedDescending { self.generateMonthData(now, currentDate: currentDate) } else { OH_OAuth2.sharedInstance().getMemberInfo({ (memberId, messagePermission, usernameShared, username, files) in self.fileList = files dispatch_async(dispatch_get_main_queue(),{ self.activityIndicator.stopAnimating() self.view.userInteractionEnabled = true self.alert = UIAlertController(title: "Upload Succeeded", message: "Your healthkit data has been uploaded to OpenHumans.", preferredStyle: UIAlertControllerStyle.Alert) self.alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(self.alert, animated: true, completion: nil) self.updateUI() }) }, onFailure: { self.activityIndicator.stopAnimating() self.view.userInteractionEnabled = true self.updateUI() }) } } @IBOutlet weak var datePickView: UIView! @IBOutlet weak var startButton: UIButton! @IBAction func uploadData(sender: AnyObject) { let defs = NSUserDefaults.standardUserDefaults() var lastDate = defs.objectForKey("lastSaveDate") if lastDate == nil { lastDate = NSDate(timeIntervalSince1970: 1104537600); } view.userInteractionEnabled = false self.progressView1.progress = 0.0 self.progressView.progress = 0.0 self.progressView.hidden = false self.progressView1.hidden = false activityIndicator.startAnimating() let now = NSDate() let cal = NSCalendar.currentCalendar() let nmonths = cal.components(.Month, fromDate: lastDate as! NSDate, toDate: now, options: NSCalendarOptions.MatchFirst).month if (nmonths == 0) { progressIncrement = 1.0 } else { progressIncrement = 1.0 / Float(nmonths) } outputMonth(now, currentDate: lastDate as! NSDate) } @IBOutlet weak var uploadData: UIButton! /* // 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. } */ }
mit
fe7ccfba29a1e77d9ef9273f0985ddfe
43.9819
203
0.568253
5.81345
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
Pod/Classes/Libs/SAVideoPlayer/AwesomeVideoPlayer.swift
1
6250
// // AwesomeVideoPlayer.swift // Pods // // Created by Gabriel Coman on 10/12/2018. // import AVFoundation import AVKit import Foundation import UIKit @objc(SAAwesomeVideoPlayer) public class AwesomeVideoPlayer: UIView, VideoPlayer { internal static let animationDuration = 0.3 private var playerLayer: AVPlayerLayer? private var didSetUpConstraints: Bool = false private weak var controller: VideoPlayerControls? private weak var controllerView: VideoPlayerControlsView? internal var isFullscreen: Bool = false public weak var delegate: VideoPlayerDelegate? private weak var previousParent: UIView? //////////////////////////////////////////////////////////////////////////// // Different setters and getters //////////////////////////////////////////////////////////////////////////// @objc(setControls:) public func setControls(controller: VideoPlayerControls) { self.controller = controller self.controller?.set(delegate: self) } @objc(setConstrolsView:insets:) public func setControlsView(controllerView: VideoPlayerControlsView, insets: UIEdgeInsets = .zero) { (self.controllerView as? UIView)?.removeFromSuperview() self.controllerView = controllerView self.controllerView?.set(delegate: self) guard let chrome = self.controllerView as? UIView else { return } addSubview(chrome) chrome.bind(toTheEdgesOf: self, insets: insets) } public func destroy() { controller?.reset() controller = nil (controllerView as? UIView)?.removeFromSuperview() controllerView = nil delegate = nil playerLayer?.removeFromSuperlayer() playerLayer = nil } override public func layoutSubviews() { super.layoutSubviews() playerLayer?.frame = CGRect(x: 0.0, y: 0.0, width: frame.width, height: frame.height) } @objc(player) func getPlayer() -> AVPlayer? { guard let control = controller as? AVPlayer else { return nil } return control } @objc(playerLayer) func getLayer() -> AVPlayerLayer? { return playerLayer } public func setMaximised() { guard !isFullscreen else { return } isFullscreen = true previousParent = superview let parentVC = self.parentViewController let isPlaying = controllerView?.isPlaying() ?? false let newVC = AwesomeVideoFullscreenPlayer(withVideoPlayer: self, andIsCurrentlyPlaying: isPlaying) newVC.modalPresentationStyle = .fullScreen newVC.modalTransitionStyle = .coverVertical parentVC?.present(newVC, animated: true) } public func setMinimised() { guard isFullscreen else { return } isFullscreen = false let parentVC = self.parentViewController parentVC?.dismiss(animated: true) guard let previousParent = previousParent else { return } previousParent.addSubview(self) let isPlaying = controllerView?.isPlaying() ?? false if isPlaying { getAVPlayer()?.play() } else { getAVPlayer()?.pause() } } public func setDelegate(delegate: VideoPlayerDelegate?) { self.delegate = delegate } public func getAVPlayer() -> AVPlayer? { guard let player = controller as? AVPlayer else { return nil } return player } public func getAVPlayerLayer() -> AVPlayerLayer? { return playerLayer } //////////////////////////////////////////////////////////////////////////// // MediaControlDelegate //////////////////////////////////////////////////////////////////////////// public func didPrepare(control: VideoPlayerControls) { if let avcontrol = control as? AVPlayer { playerLayer?.removeFromSuperlayer() playerLayer = AVPlayerLayer(player: avcontrol) if let playerLayer = playerLayer { layer.addSublayer(playerLayer) control.start() delegate?.didPrepare(videoPlayer: self, time: control.getCurrentPosition(), duration: control.getDuration()) controllerView?.setPlaying() subviews.forEach { bringSubviewToFront($0) } if let chrome = controllerView as? UIView { bringSubviewToFront(chrome) } } } } public func didUpdateTime(control: VideoPlayerControls, time: Int, duration: Int) { controllerView?.setTime(time: time, duration: duration) delegate?.didUpdateTime(videoPlayer: self, time: control.getCurrentPosition(), duration: control.getDuration()) } public func didCompleteMedia(control: VideoPlayerControls, time: Int, duration: Int) { controllerView?.setCompleted() delegate?.didComplete(videoPlayer: self, time: control.getCurrentPosition(), duration: control.getDuration()) } public func didCompleteSeek(control: VideoPlayerControls) { // N/A } public func didError(control: VideoPlayerControls, error: Error, time: Int, duration: Int) { delegate?.didError(videoPlayer: self, error: error, time: 0, duration: 0) } //////////////////////////////////////////////////////////////////////////// // ChromeControlDelegate //////////////////////////////////////////////////////////////////////////// public func didStartProgressBarSeek() { // N/A } public func didEndProgressBarSeek(value: Float) { let totalSeconds = controller?.getDuration() ?? 0 let value = CMTimeValue(value * Float(totalSeconds)) let seekTime = CMTime(value: value, timescale: 1) controller?.seekTo(position: seekTime) } public func didTapPlay() { controller?.start() } public func didTapPause() { controller?.pause() } public func didTapReplay() { controller?.seekTo(position: CMTime(seconds: 0.0, preferredTimescale: 1)) controller?.start() } public func didTapMaximise() { setMaximised() } public func didTapMinimise() { setMinimised() } }
lgpl-3.0
79c41743ee7b6644fa98577d374bd7cf
30.565657
124
0.59552
5.355613
false
false
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Dialogs/DialogsViewController.swift
1
9137
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class DialogsViewController: EngineListController, UISearchBarDelegate, UISearchDisplayDelegate { var tableView: UITableView! var searchView: UISearchBar? var searchDisplay: UISearchDisplayController? var searchSource: DialogsSearchSource? var binder = Binder() init() { super.init(contentSection: 0) tabBarItem = UITabBarItem( title: localized("TabMessages"), image: UIImage(named: "TabIconChats")?.styled("tab.icon"), selectedImage: UIImage(named: "TabIconChatsHighlighted")?.styled("tab.icon.selected")) binder.bind(Actor.getAppState().getGlobalCounter(), closure: { (value: JavaLangInteger?) -> () in if value != nil { if value!.integerValue > 0 { self.tabBarItem.badgeValue = "\(value!.integerValue)" } else { self.tabBarItem.badgeValue = nil } } else { self.tabBarItem.badgeValue = nil } }) if (!MainAppTheme.tab.showText) { tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0); } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() self.extendedLayoutIncludesOpaqueBars = true tableView = UITableView() tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.rowHeight = 76 tableView.backgroundColor = MainAppTheme.list.backyardColor view.addSubview(tableView) // view = tableView } override func buildDisplayList() -> ARBindedDisplayList { return Actor.getDialogsDisplayList() } func isTableEditing() -> Bool { return self.tableView.editing; } override func viewDidLoad() { bindTable(tableView, fade: true); searchView = UISearchBar() searchView!.delegate = self searchView!.frame = CGRectMake(0, 0, 320, 44) searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light MainAppTheme.search.styleSearchBar(searchView!) searchDisplay = UISearchDisplayController(searchBar: searchView!, contentsController: self) searchDisplay?.searchResultsDelegate = self searchDisplay?.searchResultsTableView.rowHeight = 76 searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None searchDisplay?.searchResultsTableView.backgroundColor = MainAppTheme.list.backyardColor searchDisplay?.searchResultsTableView.frame = tableView.frame let header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44)) header.addSubview(searchDisplay!.searchBar) tableView.tableHeaderView = header searchSource = DialogsSearchSource(searchDisplay: searchDisplay!) super.viewDidLoad(); navigationItem.title = NSLocalizedString("TabMessages", comment: "Messages Title") navigationItem.leftBarButtonItem = editButtonItem() navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title"); navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose") placeholder.setImage( UIImage(named: "chat_list_placeholder"), title: NSLocalizedString("Placeholder_Dialogs_Title", comment: "Placeholder Title"), subtitle: NSLocalizedString("Placeholder_Dialogs_Message", comment: "Placeholder Message")) binder.bind(Actor.getAppState().getIsDialogsEmpty(), closure: { (value: Any?) -> () in if let empty = value as? JavaLangBoolean { if Bool(empty.booleanValue()) == true { self.navigationItem.leftBarButtonItem = nil self.showPlaceholder() } else { self.hidePlaceholder() self.navigationItem.leftBarButtonItem = self.editButtonItem() } } }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Actor.onDialogsOpen(); } override func viewDidDisappear(animated: Bool) { Actor.onDialogsClosed(); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // SearchBar hack let searchBar = searchDisplay!.searchBar let superView = searchBar.superview if !(superView is UITableView) { searchBar.removeFromSuperview() superView?.addSubview(searchBar) } // Header hack tableView.tableHeaderView?.setNeedsLayout() tableView.tableFooterView?.setNeedsLayout() // tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height) if (searchDisplay != nil && searchDisplay!.active) { MainAppTheme.search.applyStatusBar() } else { MainAppTheme.navigation.applyStatusBar() } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) searchDisplay?.setActive(false, animated: animated) } // MARK: - // MARK: Setters override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) if (editing) { self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationDone", comment: "Done Title"); self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Done; navigationItem.rightBarButtonItem = nil } else { self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title"); self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Bordered; navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose") } if editing == true { navigationItem.rightBarButtonItem = nil } else { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose") } } // MARK: - // MARK: UITableView func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { let dialog = objectAtIndexPath(indexPath) as! ACDialog execute(Actor.deleteChatCommandWithPeer(dialog.getPeer())); } } override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell { let reuseKey = "cell_dialog"; var cell = tableView.dequeueReusableCellWithIdentifier(reuseKey) as! DialogCell?; if (cell == nil){ cell = DialogCell(reuseIdentifier: reuseKey); cell?.awakeFromNib(); } return cell!; } override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) { let dialog = item as! ACDialog; let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section) - 1; (cell as! DialogCell).bindDialog(dialog, isLast: isLast); } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (tableView == self.tableView) { let dialog = objectAtIndexPath(indexPath) as! ACDialog navigateToMessagesWithPeer(dialog.getPeer()) } else { let searchEntity = searchSource!.objectAtIndexPath(indexPath) as! ACSearchEntity navigateToMessagesWithPeer(searchEntity.getPeer()) } // tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - // MARK: Navigation func navigateToCompose() { navigateDetail(ComposeController()) } private func navigateToMessagesWithPeer(peer: ACPeer) { navigateDetail(ConversationViewController(peer: peer)) MainAppTheme.navigation.applyStatusBar() } }
mit
e0dc9ecd097db5c0dbbd33dd70b148ea
36.600823
158
0.634782
5.771952
false
false
false
false
N26-OpenSource/bob
Sources/Bob/Commands/Bump/Version.swift
1
2746
/* * Copyright (c) 2019 N26 GmbH. * * This file is part of Bob. * * Bob is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Bob is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Bob. If not, see <http://www.gnu.org/licenses/>. */ import Foundation struct Version { struct Build { public let value: String public init(_ value: String) { self.value = value } func bump() throws -> Build { let newBuildNumber: String if let numericBuildNumber = Int(value) { newBuildNumber = String(numericBuildNumber + 1) } else if let numericBuildString = RegexMatcher(text: value).matches(stringMatching: "[0-9]{1,}$").last, let numericBuildNumber = Int(numericBuildString) { let prefix = value.dropLast(numericBuildString.count) newBuildNumber = prefix + String(numericBuildNumber + 1) } else { throw "Could not bump up build number '\(value)' because it's not numeric." } return Build(newBuildNumber) } } let version: String let build: Build init(fromPlistContent content: String) throws { let (version, build) = try PListHelpers.version(fromPlistContent: content) self.version = version self.build = Build(build) } init(version: String, build: String) { self.init(version: version, build: Build(build)) } init(version: String, build: Build) { self.version = version self.build = build } /// Bumps the build version only func bump() throws -> Version { return Version(version: version, build: try build.bump()) } /// version + build number var fullVersion: String { return "\(version) (\(build.value))" } /// Commit message using the version and build number /// /// - Parameter template: Optional template where `<version>` will be replaced with the version string /// - Returns: e.g. `Version 3.2.0 123` func commitMessage(template: String? = nil) -> String { guard let template = template else { return fullVersion } return template.replacingOccurrences(of: "<version>", with: fullVersion) } }
gpl-3.0
43bf4e9c48cf6bc1166566589c47da72
32.901235
116
0.628551
4.429032
false
false
false
false
ianyh/Highball
Highball/Modules/Posts/Blog/BlogViewController.swift
1
1775
// // BlogViewController.swift // Highball // // Created by Ian Ynda-Hummel on 2/21/15. // Copyright (c) 2015 ianynda. All rights reserved. // import UIKit import FontAwesomeKit public class BlogViewController: PostsViewController { internal var blogPresenter: BlogPresenter? public override weak var presenter: PostsPresenter? { get { return blogPresenter as? PostsPresenter } set { guard let presenter = newValue as? BlogPresenter else { fatalError() } blogPresenter = presenter } } public init(blogName: String, postHeightCache: PostHeightCache) { super.init(postHeightCache: postHeightCache) let followIcon = FAKIonIcons.iosPersonaddOutlineIconWithSize(30) navigationItem.rightBarButtonItem = UIBarButtonItem( image: followIcon.imageWithSize(CGSize(width: 30, height: 30)), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(follow(_:)) ) navigationItem.title = blogName } public override init(postHeightCache: PostHeightCache) { fatalError("init() has not been implemented") } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func follow(sender: UIBarButtonItem) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) alertController.addAction(UIAlertAction(title: "Follow", style: .Default) { [weak self] action in self?.blogPresenter?.follow() }) alertController.addAction(UIAlertAction(title: "Unfollow", style: .Destructive) { [weak self] action in self?.blogPresenter?.unfollow() }) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alertController, animated: true, completion: nil) } }
mit
0ae0c8828c6ad45ee26d651eec2f2331
26.734375
105
0.743662
3.909692
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/Model/Operation.swift
1
2007
// // Operation.swift // WISData.JunZheng // // Created by Allen on 16/9/1. // Copyright © 2016 Wisdri. All rights reserved. // import Alamofire import SwiftyJSON import MJExtension /// 电极操作记录 class Operation: NSObject, PropertyNames { var FLYL: String? var JHL: String? var No: String? var PB: String? var SwitchTimes: SwitchTime? var YFCS: String? var YFL: String? } class SwitchTime: NSObject, PropertyNames { var HZGD: String? var Hour: String? var Minute: String? } extension Operation { class func get(date date: String, shiftNo: String, lNo: String, completionHandler: WISValueResponse<JSON> -> Void) -> Void { let getURL = BaseURL + "/GetDJOperation?date=\(date)&shiftNo=\(shiftNo)&lNo=\(lNo)" HTTPManager.sharedInstance.request(.POST, getURL).responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) guard json["Result"] == 1 else { let t = WISValueResponse<JSON>(value: JSON.null, success: false) t.message = "未检索到所需数据, \n请修改查询条件后重试。" completionHandler(t) return } let t = WISValueResponse<JSON>(value: json, success: true) completionHandler(t) } case .Failure(let error): debugPrint(error) debugPrint("\nError Description: " + error.localizedDescription) let t = WISValueResponse<JSON>(value: JSON.null, success: false) t.message = error.localizedDescription + "\n请检查设备的网络设置, 然后下拉页面刷新。" completionHandler(t) } } } }
mit
ac775cf0096c3e9f687ba68b26c6f5b3
29.444444
128
0.543796
4.439815
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSLock.swift
1
5704
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation public protocol Locking { func lock() func unlock() } public class Lock: NSObject, Locking { internal var mutex = UnsafeMutablePointer<pthread_mutex_t>(allocatingCapacity: 1) public override init() { pthread_mutex_init(mutex, nil) } deinit { pthread_mutex_destroy(mutex) mutex.deinitialize() mutex.deallocateCapacity(1) } public func lock() { pthread_mutex_lock(mutex) } public func unlock() { pthread_mutex_unlock(mutex) } public func tryLock() -> Bool { return pthread_mutex_trylock(mutex) == 0 } public var name: String? } extension Lock { internal func synchronized<T>(_ closure: @noescape () -> T) -> T { self.lock() defer { self.unlock() } return closure() } } public class NSConditionLock : NSObject, Locking { internal var _cond = Condition() internal var _value: Int internal var _thread: pthread_t? public convenience override init() { self.init(condition: 0) } public init(condition: Int) { _value = condition } public func lock() { let _ = lockBeforeDate(Date.distantFuture) } public func unlock() { _cond.lock() _thread = nil _cond.broadcast() _cond.unlock() } public var condition: Int { return _value } public func lockWhenCondition(_ condition: Int) { let _ = lockWhenCondition(condition, beforeDate: Date.distantFuture) } public func tryLock() -> Bool { return lockBeforeDate(Date.distantPast) } public func tryLockWhenCondition(_ condition: Int) -> Bool { return lockWhenCondition(condition, beforeDate: Date.distantPast) } public func unlockWithCondition(_ condition: Int) { _cond.lock() _thread = nil _value = condition _cond.broadcast() _cond.unlock() } public func lockBeforeDate(_ limit: Date) -> Bool { _cond.lock() while _thread == nil { if !_cond.waitUntilDate(limit) { _cond.unlock() return false } } _thread = pthread_self() _cond.unlock() return true } public func lockWhenCondition(_ condition: Int, beforeDate limit: Date) -> Bool { _cond.lock() while _thread != nil || _value != condition { if !_cond.waitUntilDate(limit) { _cond.unlock() return false } } _thread = pthread_self() _cond.unlock() return true } public var name: String? } public class RecursiveLock: NSObject, Locking { internal var mutex = UnsafeMutablePointer<pthread_mutex_t>(allocatingCapacity: 1) public override init() { super.init() var attrib = pthread_mutexattr_t() withUnsafeMutablePointer(&attrib) { attrs in pthread_mutexattr_settype(attrs, Int32(PTHREAD_MUTEX_RECURSIVE)) pthread_mutex_init(mutex, attrs) } } deinit { pthread_mutex_destroy(mutex) mutex.deinitialize() mutex.deallocateCapacity(1) } public func lock() { pthread_mutex_lock(mutex) } public func unlock() { pthread_mutex_unlock(mutex) } public func tryLock() -> Bool { return pthread_mutex_trylock(mutex) == 0 } public var name: String? } public class Condition: NSObject, Locking { internal var mutex = UnsafeMutablePointer<pthread_mutex_t>(allocatingCapacity: 1) internal var cond = UnsafeMutablePointer<pthread_cond_t>(allocatingCapacity: 1) public override init() { pthread_mutex_init(mutex, nil) pthread_cond_init(cond, nil) } deinit { pthread_mutex_destroy(mutex) pthread_cond_destroy(cond) mutex.deinitialize() cond.deinitialize() mutex.deallocateCapacity(1) cond.deallocateCapacity(1) } public func lock() { pthread_mutex_lock(mutex) } public func unlock() { pthread_mutex_unlock(mutex) } public func wait() { pthread_cond_wait(cond, mutex) } public func waitUntilDate(_ limit: Date) -> Bool { let lim = limit.timeIntervalSinceReferenceDate let ti = lim - CFAbsoluteTimeGetCurrent() if ti < 0.0 { return false } var ts = timespec() ts.tv_sec = Int(floor(ti)) ts.tv_nsec = Int((ti - Double(ts.tv_sec)) * 1000000000.0) var tv = timeval() withUnsafeMutablePointer(&tv) { t in gettimeofday(t, nil) ts.tv_sec += t.pointee.tv_sec ts.tv_nsec += Int((t.pointee.tv_usec * 1000000) / 1000000000) } let retVal: Int32 = withUnsafePointer(&ts) { t in return pthread_cond_timedwait(cond, mutex, t) } return retVal == 0 } public func signal() { pthread_cond_signal(cond) } public func broadcast() { pthread_cond_broadcast(cond) } public var name: String? }
apache-2.0
1686ce4392274343d268ce74d0d9bf53
23.586207
85
0.579593
4.331055
false
false
false
false