repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
XcqRomance/BookRoom-complete-
BookRoom/BookCell.swift
1
1707
// // BookCell.swift // BookRoom // // Created by romance on 2017/5/4. // Copyright © 2017年 romance. All rights reserved. // import UIKit import SDWebImage final class BookCell: UICollectionViewCell { @IBOutlet weak var bookCover: UIImageView! @IBOutlet weak var coverName: UILabel! @IBOutlet weak var isReadImageView: UIImageView! @IBOutlet weak var bookWidth: NSLayoutConstraint! @IBOutlet weak var bookHeight: NSLayoutConstraint! @IBOutlet weak var gradientView: UIView! var book: Book? { didSet { bookCover.sd_setImage(with: URL(string: (book?.pic.aliyunThumb())!), placeholderImage: UIImage(named: "bookDefault"), options: .retryFailed) { (_, _, _, _) in self.coverName.isHidden = true } coverName.text = book?.bookName // title.text = book?.bookName if (book?.isRead)! { // 是否阅读过该书籍 isReadImageView.isHidden = false } else { isReadImageView.isHidden = true } if book?.orientation == 1 { // 竖版书籍 bookWidth.constant = 67 bookHeight.constant = 88 } else { bookWidth.constant = 96 bookHeight.constant = 67 } layoutIfNeeded() } } override func awakeFromNib() { super.awakeFromNib() bookCover.layer.cornerRadius = 10 let gradLayer = CAGradientLayer() gradLayer.colors = [UIColor.hexColor(0x045b94).cgColor, UIColor.hexColor(0x176da6).cgColor] gradLayer.startPoint = CGPoint(x: 0, y: 0) gradLayer.endPoint = CGPoint(x: 0, y: 1) gradLayer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width / 3, height: 25) gradientView.layer.addSublayer(gradLayer) } }
mit
e78f8be8eb781fec57b0403b4d557af0
27.474576
164
0.65119
3.862069
false
false
false
false
AcelLuxembourg/LidderbuchApp
Lidderbuch/LBBacker.swift
1
4169
// // LBBacker.swift // Lidderbuch // // Created by Fränz Friederes on 12/11/16. // Copyright © 2016 ACEL. All rights reserved. // import UIKit class LBBacker: NSObject { // contains an array of backer image urls var backers: [URL]! fileprivate var localBackerDirectoryURL: URL { let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! return documentDirectoryURL.appendingPathComponent("backers") } override init() { super.init() // look for backer image files inside backer directory if let backerImageIds = try? FileManager.default.contentsOfDirectory(atPath: localBackerDirectoryURL.path) { backers = [] // each backer image is named after the backer image id for backerImageId in backerImageIds { backers.append(localBackerDirectoryURL.appendingPathComponent(backerImageId)) } } else { // no backer images could be located backers = [] } // schedule backers update at low QOS in 2 seconds DispatchQueue.global(qos: DispatchQoS.QoSClass.utility) .asyncAfter(deadline: .now() + 2.0) { self.update() } } func randomBackerImage() -> UIImage? { if let imageUrl = backers.random { // returns random backer image return UIImage(contentsOfFile: imageUrl.path) } return nil } func update() { // call backers endpoint let task = URLSession.shared.dataTask( with: URL(string: LBVariables.backerApiEndpoint)!, completionHandler: { (data, response, error) in if data != nil && error == nil { self.integrateBackersWithData(data!) } }) task.resume() } func integrateBackersWithData(_ data: Data) { let fileManager = FileManager.default // create backer directory if it does not exist yet if (!fileManager.fileExists(atPath: localBackerDirectoryURL.path)) { do { try fileManager.createDirectory(atPath: localBackerDirectoryURL.path, withIntermediateDirectories: false, attributes: nil) } catch _ as NSError { return } } var updatedBackers = [URL]() // try to read json data if let backersJson = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [AnyObject] { for backerJson in backersJson { // verify image id and url data if let backerImageId = backerJson["logo_id"] as? Int, let backerImageUrlString = backerJson["logo_display_url"] as? String, let backerImageUrl = URL(string: backerImageUrlString) { let backer = localBackerDirectoryURL.appendingPathComponent(String(backerImageId)) updatedBackers.append(backer) // download backer if !backers.contains(backer) { let task = URLSession.shared.dataTask( with: backerImageUrl, completionHandler: { (data, response, error) in // save backer try! data?.write(to: backer) } ) task.resume() } } } } // remove backers not included in latest backers list for backer in backers { // check if backer is still included if !updatedBackers.contains(backer) { // remove backer try! fileManager.removeItem(atPath: backer.path) } } backers = updatedBackers } }
mit
1bf6f9be7cd09ef1de44d8c8d3a323ab
32.604839
138
0.523398
5.376774
false
false
false
false
bizz84/MVMediaSlider
MVMediaSlider/MVMediaSlider.swift
1
10218
/* MVMediaSlider - Copyright (c) 2016 Andrea Bizzotto [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit private extension DateComponentsFormatter { // http://stackoverflow.com/questions/4933075/nstimeinterval-to-hhmmss class func string(timeInterval: TimeInterval, prefix: String = "", fallback: String = "0:00") -> String { let formatter = DateComponentsFormatter() formatter.zeroFormattingBehavior = .pad formatter.allowedUnits = timeInterval >= 3600 ? [.hour, .minute, .second] : [.minute, .second] let minusString = timeInterval >= 1.0 ? prefix : "" return minusString + (formatter.string(from: timeInterval) ?? fallback) } } private extension UIView { func anchorToSuperview() { if let superview = self.superview { self.translatesAutoresizingMaskIntoConstraints = false superview.addConstraints([ makeEqualityConstraint(attribute: .left, toView: superview), makeEqualityConstraint(attribute: .top, toView: superview), makeEqualityConstraint(attribute: .right, toView: superview), makeEqualityConstraint(attribute: .bottom, toView: superview) ]) } } func makeEqualityConstraint(attribute: NSLayoutConstraint.Attribute, toView view: UIView) -> NSLayoutConstraint { return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: view, attribute: attribute, multiplier: 1, constant: 0) } } @IBDesignable open class MVMediaSlider: UIControl { // MARK: IBOutlets @IBOutlet fileprivate var leftLabelHolder: UIView! @IBOutlet fileprivate var leftLabel: UILabel! @IBOutlet fileprivate var rightLabelHolder: UIView! @IBOutlet fileprivate var rightLabel: UILabel! @IBOutlet fileprivate var elapsedTimeView: UIView! @IBOutlet fileprivate var sliderView: UIView! @IBOutlet fileprivate var elapsedTimeViewWidthConstraint: NSLayoutConstraint! @IBOutlet fileprivate var sliderWidthConstraint: NSLayoutConstraint! @IBOutlet fileprivate var topSeparatorView: UIView! @IBOutlet fileprivate var bottomSeparatorView: UIView! // MARK: UIControl touch handling variables fileprivate let DragCaptureDeltaX: CGFloat = 22 open fileprivate(set) var draggingInProgress = false fileprivate var initialDragLocationX: CGFloat = 0 fileprivate var initialSliderConstraintValue: CGFloat = 0 // MARK: init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let bundle = Bundle(for: MVMediaSlider.self) if let view = bundle.loadNibNamed("MVMediaSlider", owner: self, options: nil)?.first as? UIView { self.addSubview(view) view.anchorToSuperview() } setDefaultValues() } override init(frame: CGRect) { super.init(frame: frame) setDefaultValues() } fileprivate func setDefaultValues() { elapsedViewColor = UIColor.gray sliderColor = UIColor.darkGray elapsedTextColor = UIColor.white remainingTextColor = UIColor.darkGray topSeparatorColor = UIColor.gray bottomSeparatorColor = UIColor.gray } // MARK: styling override open var backgroundColor: UIColor! { didSet { rightLabelHolder?.backgroundColor = self.backgroundColor } } @IBInspectable open var elapsedViewColor: UIColor? { get { return leftLabelHolder?.backgroundColor } set(newElapsedViewColor) { leftLabelHolder?.backgroundColor = newElapsedViewColor elapsedTimeView?.backgroundColor = newElapsedViewColor let _ = sliderView?.subviews.map { $0.backgroundColor = newElapsedViewColor } } } @IBInspectable open var sliderColor: UIColor? { get { return sliderView?.backgroundColor } set { sliderView?.backgroundColor = newValue } } @IBInspectable open var elapsedTextColor: UIColor? { get { return leftLabel?.textColor } set { leftLabel?.textColor = newValue ?? UIColor.gray } } @IBInspectable open var remainingTextColor: UIColor? { get { return rightLabel?.textColor } set { rightLabel?.textColor = newValue ?? UIColor.darkGray } } @IBInspectable open var topSeparatorColor: UIColor? { get { return topSeparatorView?.backgroundColor } set { topSeparatorView?.backgroundColor = newValue } } @IBInspectable open var bottomSeparatorColor: UIColor? { get { return bottomSeparatorView?.backgroundColor } set { bottomSeparatorView?.backgroundColor = newValue } } open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() } // IBInspectable should support UIFont: http://www.openradar.me/22835760 // @IBInspectable open var timersFont: UIFont! { didSet { leftLabel?.font = timersFont rightLabel?.font = timersFont } } // MARK: time management open var totalTime: TimeInterval? { didSet { updateView(currentTime: _currentTime, totalTime: _totalTime) } } open var currentTime: TimeInterval? { didSet { if !draggingInProgress { let currentTime = min(_currentTime, _totalTime) updateView(currentTime: currentTime, totalTime: _totalTime) } } } // MARK: internal methods fileprivate var _totalTime: TimeInterval { return totalTime ?? 0 } fileprivate var _currentTime: TimeInterval { return currentTime ?? 0 } fileprivate var availableSliderWidth: CGFloat { return self.frame.width - leftLabelHolder.frame.width - rightLabelHolder.frame.width - sliderView.frame.width } fileprivate func updateView(currentTime: TimeInterval, totalTime: TimeInterval) { let normalizedTime = totalTime > 0 ? currentTime / totalTime : 0 elapsedTimeViewWidthConstraint?.constant = CGFloat(normalizedTime) * availableSliderWidth leftLabel?.text = DateComponentsFormatter.string(timeInterval: currentTime) let remainingTime = totalTime - currentTime rightLabel?.text = DateComponentsFormatter.string(timeInterval: remainingTime, prefix: "-") } // MARK: trait collection override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if draggingInProgress { cancelTracking(with: nil) draggingInProgress = false } updateView(currentTime: _currentTime, totalTime: _totalTime) } } extension MVMediaSlider { // MARK: UIControl subclassing override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.sendActions(for: .touchDown) let sliderCenterX = leftLabelHolder.frame.width + elapsedTimeViewWidthConstraint.constant + sliderView.bounds.width / 2 let locationX = touch.location(in: self).x let beginTracking = locationX > sliderCenterX - DragCaptureDeltaX && locationX < sliderCenterX + DragCaptureDeltaX if beginTracking { initialDragLocationX = locationX initialSliderConstraintValue = elapsedTimeViewWidthConstraint.constant } return beginTracking } override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { if !draggingInProgress { draggingInProgress = true } let newValue = sliderValue(touch) let seekTime = TimeInterval(newValue / availableSliderWidth) * _totalTime updateView(currentTime: seekTime, totalTime: _totalTime) return true } override open func endTracking(_ touch: UITouch?, with event: UIEvent?) { self.sendActions(for: .touchUpInside) draggingInProgress = false guard let touch = touch else { updateView(currentTime: _currentTime, totalTime: _totalTime) return } let newValue = sliderValue(touch) currentTime = TimeInterval(newValue / availableSliderWidth) * _totalTime self.sendActions(for: .valueChanged) } fileprivate func sliderValue(_ touch: UITouch) -> CGFloat { let locationX = touch.location(in: self).x let deltaX = locationX - initialDragLocationX let adjustedSliderValue = initialSliderConstraintValue + deltaX return max(0, min(adjustedSliderValue, availableSliderWidth)) } }
mit
250e86a426cc218f64fb2a5e7290b8d9
34.234483
460
0.651106
5.529221
false
false
false
false
lionheart/QuickTableView
Pod/Extensions/QuickTableViewSection.swift
1
2394
// // Copyright 2016 Lionheart Software 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 UIKit public extension QuickTableViewSection where Self: RawRepresentable, Self.RawValue == Int { init(at indexPath: IndexPath) { self.init(at: indexPath.section) } init(at row: Int) { self.init(rawValue: row)! } static var count: Int { return lastSection.rawValue + 1 } static var lastSection: Self { var section = Self(rawValue: 0)! for i in 0..<Int.max { guard let _section = Self(rawValue: i) else { return section } section = _section } return section } } public extension QuickTableViewSectionWithConditions where Self: RawRepresentable, Self.RawValue == Int { init(at indexPath: IndexPath, container: Container) { self.init(at: indexPath.section, container: container) } init(at section: Int, container: Container) { var section = section let _conditionalRows = Self.conditionalSections(for: container) for (conditionalRow, test) in _conditionalRows { if section >= conditionalRow.rawValue && !test { section += 1 } } self.init(rawValue: section)! } static func index(section: Self, container: Container) -> Int? { for i in 0..<count(for: container) { if section == Self(at: i, container: container) { return i } } return nil } static func count(for container: Container) -> Int { var count = lastSection.rawValue + 1 let _conditionalRows = conditionalSections(for: container) for (_, test) in _conditionalRows { if !test { count -= 1 } } return count } }
apache-2.0
bb10d5378ba4e5af2c8b893aaf3d00be
28.555556
105
0.609858
4.458101
false
false
false
false
teamVCH/sway
sway/CenteredButton.swift
1
1872
// // CenteredButton.swift // sway // // Created by Christopher McMahon on 11/12/15. // Copyright © 2015 VCH. All rights reserved. // import UIKit class CenteredButton: UIButton { let padding: CGFloat = 5 override func titleRectForContentRect(contentRect: CGRect) -> CGRect { let rect = super.titleRectForContentRect(contentRect) let y = CGRectGetHeight(contentRect) - CGRectGetHeight(rect) + padding return CGRectMake(0, y, CGRectGetWidth(contentRect), CGRectGetHeight(rect)) } override func imageRectForContentRect(contentRect: CGRect) -> CGRect { let rect = super.imageRectForContentRect(contentRect) let titleRect = titleRectForContentRect(contentRect) return CGRectMake(CGRectGetWidth(contentRect)/2.0 - CGRectGetWidth(rect)/2.0, (CGRectGetHeight(contentRect) - CGRectGetHeight(titleRect))/2.0 - CGRectGetHeight(rect)/2.0, CGRectGetWidth(rect), CGRectGetHeight(rect)) } override func intrinsicContentSize() -> CGSize { let size = super.intrinsicContentSize() if let image = imageView?.image { var labelHeight: CGFloat = 0.0 if let size = titleLabel?.sizeThatFits(CGSizeMake(CGRectGetWidth(self.contentRectForBounds(self.bounds)), CGFloat.max)) { labelHeight = size.height } return CGSizeMake(size.width, image.size.height + labelHeight) } return size } override init(frame: CGRect) { super.init(frame: frame) centerTitleLabel() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) centerTitleLabel() } private func centerTitleLabel() { self.titleLabel?.textAlignment = .Center } }
mit
e5d4659032a0169c57d56c353e3fe52e
30.183333
133
0.62961
4.936675
false
false
false
false
huonw/swift
test/Interpreter/generic_class.swift
16
5223
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test protocol MyPrintable { func myPrint() } extension Int : MyPrintable { func myPrint() { print(self.description, terminator: "") } } extension Double : MyPrintable { func myPrint() { print(self.description, terminator: "") } } extension String : MyPrintable { func myPrint() { print(self.debugDescription, terminator: "") } } class BufferedPair<T, U> { var front: UInt8 var first: T var second: U var back: UInt8 init(_ front: UInt8, _ first: T, _ second: U, _ back: UInt8) { self.front = front self.first = first self.second = second self.back = back } } enum State : MyPrintable { case CA, OR, WA func myPrint() { switch self { case .CA: print("California", terminator: "") case .OR: print("Oregon", terminator: "") case .WA: print("Washington", terminator: "") } } } func printPair<A: MyPrintable, B: MyPrintable>(_ p: BufferedPair<A,B>) { print("\(p.front) ", terminator: "") p.first.myPrint() print(" ", terminator: "") p.second.myPrint() print(" \(p.back)") } var p = BufferedPair(99, State.OR, "Washington's Mexico", 84) // CHECK: 99 Oregon "Washington\'s Mexico" 84 printPair(p) class AwkwardTriple<V, W, X> : BufferedPair<V, W> { var third: X init(_ front: UInt8, _ first: V, _ second: W, _ back: UInt8, _ third: X) { self.third = third super.init(front, first, second, back) self.third = third } } func printTriple <D: MyPrintable, E: MyPrintable, F: MyPrintable> (_ p: AwkwardTriple<D, E, F>) { print("\(p.front) ", terminator: "") p.first.myPrint() print(" ", terminator: "") p.second.myPrint() print(" \(p.back) ", terminator: "") p.third.myPrint() print("") } var q = AwkwardTriple(123, State.CA, "Foo", 234, State.WA) // CHECK: 123 California "Foo" 234 printPair(q) // CHECK: 123 California "Foo" 234 Washington printTriple(q) class FourthWheel<P, Q, R, S> : AwkwardTriple<P, Q, R> { var fourth: S init(_ front: UInt8, _ first: P, _ second: Q, _ back: UInt8, _ third: R, _ fourth: S) { self.fourth = fourth super.init(front, first, second, back, third) self.fourth = fourth } } func printQuad <G: MyPrintable, H: MyPrintable, I: MyPrintable, J: MyPrintable> (_ p: FourthWheel<G, H, I, J>) { print("\(p.front) ", terminator: "") p.first.myPrint() print(" ", terminator: "") p.second.myPrint() print(" \(p.back) ", terminator: "") p.third.myPrint() print(" ", terminator: "") p.fourth.myPrint() print("") } var r = FourthWheel(21, State.WA, "Bar", 31, State.OR, 3.125) // CHECK: 21 Washington "Bar" 31 printPair(r) // CHECK: 21 Washington "Bar" 31 Oregon printTriple(r) var rAsPair: BufferedPair<State, String> = r // CHECK: 21 Washington "Bar" 31 Oregon printTriple(rAsPair as! AwkwardTriple<State, String, State>) // CHECK: 21 Washington "Bar" 31 Oregon 3.125 printQuad(r) // CHECK: 21 Washington "Bar" 31 Oregon 3.125 printQuad(rAsPair as! FourthWheel<State, String, State, Double>) class ConcretePair { var first, second: UInt8 init(_ first: UInt8, _ second: UInt8) { self.first = first self.second = second } } class SemiConcreteTriple<O> : ConcretePair { var third: O init(_ first: UInt8, _ second: UInt8, _ third: O) { self.third = third super.init(first, second) self.third = third } } func printConcretePair(_ p: ConcretePair) { print("\(p.first) \(p.second)") } func printSemiTriple<O : MyPrintable>(_ p: SemiConcreteTriple<O>) { print("\(p.first) \(p.second) ", terminator: "") p.third.myPrint() print("") } var s = SemiConcreteTriple(120, 230, State.CA) // CHECK: 120 230 printConcretePair(s) // CHECK: 120 230 California printSemiTriple(s) var t = SemiConcreteTriple(121, 231, "California's Canada") // CHECK: 121 231 printConcretePair(t) // CHECK: 121 231 "California\'s Canada" printSemiTriple(t) class MoreConcreteQuadruple : SemiConcreteTriple<State> { var fourth: String init(_ first: UInt8, _ second: UInt8, _ third: State, _ fourth: String) { self.fourth = fourth super.init(first, second, third) } } var u = MoreConcreteQuadruple(10, 17, State.CA, "Hella") // CHECK: 10 17 printConcretePair(u) class RootGenericFixedLayout<T> { let a: [T] let b: Int init(a: [T], b: Int) { self.a = a self.b = b } } func checkRootGenericFixedLayout<T>(_ r: RootGenericFixedLayout<T>) { print(r.a) print(r.b) } let rg = RootGenericFixedLayout<Int>(a: [1, 2, 3], b: 4) // CHECK: [1, 2, 3] // CHECK: 4 checkRootGenericFixedLayout(rg) class GenericInheritsGenericFixedLayout<T> : RootGenericFixedLayout<T> { let c: Int init(a: [T], b: Int, c: Int) { self.c = c super.init(a: a, b: b) } } let gg = GenericInheritsGenericFixedLayout<Int>(a: [1, 2, 3], b: 4, c: 5) func checkGenericInheritsGenericFixedLayout<T>(_ g: GenericInheritsGenericFixedLayout<T>) { print(g.a) print(g.b) print(g.c) } // CHECK: [1, 2, 3] // CHECK: 4 checkRootGenericFixedLayout(gg) // CHECK: [1, 2, 3] // CHECK: 4 // CHECK: 5 checkGenericInheritsGenericFixedLayout(gg)
apache-2.0
b26fb365dee516b75106c144ba9338c5
21.131356
91
0.640819
2.960884
false
false
false
false
asowers1/RevCheckIn
RevCheckIn/HTTPUpload.swift
1
1515
// // HTTPUpload.swift // RevCheckIn // // Created by Andrew Sowers on 7/29/14. // Copyright (c) 2014 Andrew Sowers. All rights reserved. // import Foundation import MobileCoreServices public class HTTPUpload: NSObject { var fileUrl: NSURL? { didSet { updateMimeType() } } var mimeType: String? var data: NSData? var fileName: String? //gets the mimeType from the fileUrl, if possible func updateMimeType() { if mimeType == nil && fileUrl != nil { var UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl?.pathExtension as NSString?, nil); var str = UTTypeCopyPreferredTagWithClass(UTI.takeUnretainedValue(), kUTTagClassMIMEType); if (str == nil) { mimeType = "application/octet-stream"; } else { mimeType = str.takeUnretainedValue() as NSString } } } //default init does nothing override init() { super.init() } ///upload a file with a fileUrl. The fileName and mimeType will be infered convenience init(fileUrl: NSURL) { self.init() self.fileUrl = fileUrl } ///upload a file from a a data blob. Must add a filename and mimeType as that can't be infered from the data convenience init(data: NSData, fileName: String, mimeType: String) { self.init() self.data = data self.fileName = fileName self.mimeType = mimeType } }
mit
a321aaa764568d9938eb5e0614cefd31
29.938776
132
0.620462
4.690402
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/KYCircularProgress/LTEPluseAnimation.swift
1
3621
// // LFTPulseAnimation.swift // // Created by Christoffer Tews on 18.12.14. // Copyright (c) 2014 Christoffer Tews. All rights reserved. // // Swift clone of: https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m import UIKit class LFTPulseAnimation: CALayer { var radius: CGFloat = 200.0 var fromValueForRadius: Float = 0.0 var fromValueForAlpha: Float = 0.45 var keyTimeForHalfOpacity: Float = 0.2 var animationDuration: TimeInterval = 3.0 var pulseInterval: TimeInterval = 0.0 var useTimingFunction: Bool = true var animationGroup: CAAnimationGroup = CAAnimationGroup() var repetitions: Float = Float.infinity // Need to implement that, because otherwise it can't find // the constructor init(layer:AnyObject!) // Doesn't seem to look in the super class override init(layer: Any) { super.init(layer: layer) } init(repeatCount: Float=Float.infinity, radius: CGFloat, position: CGPoint) { super.init() self.contentsScale = UIScreen.main.scale self.opacity = 0.0 self.backgroundColor = UIColor.blue.cgColor self.radius = radius; self.repetitions = repeatCount; self.position = position DispatchQueue.global(qos: .background).async { self.setupAnimationGroup() self.setPulseRadius(radius: self.radius) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func start() { if (self.pulseInterval != Double.infinity) { DispatchQueue.main.async { self.add(self.animationGroup, forKey: "pulse") } } } func reset() { self.removeAllAnimations() } func setPulseRadius(radius: CGFloat) { self.radius = radius let tempPos = self.position let diameter = self.radius * 2 self.bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter) self.cornerRadius = self.radius self.position = tempPos } func setupAnimationGroup() { self.animationGroup = CAAnimationGroup() self.animationGroup.duration = self.animationDuration + self.pulseInterval self.animationGroup.repeatCount = self.repetitions self.animationGroup.isRemovedOnCompletion = false if self.useTimingFunction { let defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) self.animationGroup.timingFunction = defaultCurve } self.animationGroup.animations = [createScaleAnimation(), createOpacityAnimation()] } func createScaleAnimation() -> CABasicAnimation { let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = NSNumber(value: self.fromValueForRadius) scaleAnimation.toValue = NSNumber(value: 1.0) scaleAnimation.duration = self.animationDuration return scaleAnimation } func createOpacityAnimation() -> CAKeyframeAnimation { let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = self.animationDuration opacityAnimation.values = [self.fromValueForAlpha, 0.8, 0] opacityAnimation.keyTimes = [0, self.keyTimeForHalfOpacity as NSNumber, 1] opacityAnimation.isRemovedOnCompletion = false return opacityAnimation } }
mit
22daf0c5e7596daaccb6289759c4b281
34.15534
100
0.642916
4.866935
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/SwiftApp/RxSwift/Demo1/Service/Demo_Service.swift
1
3303
// // Service.swift // SwiftApp // // Created by wuyp on 2017/7/3. // Copyright © 2017年 raymond. All rights reserved. // import Foundation import RxSwift class ValidationService { static let instance = ValidationService() var filePath: String { return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "users.plist" } private init() {} let minCharactersCount = 6 func validateUserName(_ username: String) -> Observable<Result> { if username.isEmpty { return Observable.just(.empty(message: "username")) } if username.characters.count < minCharactersCount { return Observable.just(.failed(message: "用户名最少输入\(minCharactersCount)位")) } if usernameValid(username) { return Observable.just(.failed(message: "账户已存在")) } return Observable.just(.ok(message: "用户名可用")) } fileprivate func usernameValid(_ username: String) -> Bool { let users = NSDictionary(contentsOfFile: filePath) let nameArray = users?.allKeys as NSArray? if let names: NSArray = nameArray, names.contains(username) { return true } return false } } extension ValidationService { func validatePassword(_ password: String) -> Result { if password.characters.count == 0 { return .empty(message: "password") } if password.characters.count < minCharactersCount { return .failed(message: "密码长度最少为\(minCharactersCount)位") } return .ok(message: "密码可用") } func validateRepeatPasswrod(_ password: String, repeatPassword: String) -> Result { if repeatPassword.characters.count == 0 { return .empty(message: "repeat") } if repeatPassword == password { return .ok(message: "密码可用") } return .failed(message: "两次密码不一致") } } extension ValidationService { func register(_ username: String, password: String) -> Observable<Result> { let userDic = [username: password] if (userDic as NSDictionary).write(toFile: filePath, atomically: true) { return .just(.ok(message: "注册成功")) } return .just(.failed(message: "注册失败")) } } extension ValidationService { func loginUserNameValidate(_ username: String) -> Observable<Result> { if username.characters.count == 0 { return .just(.empty(message: "username")) } if usernameValid(username) { return .just(.ok(message: "用户名可用")) } else { return .just(.failed(message: "用户名不存在")) } } func login(username: String, password: String) -> Observable<Result> { let users = NSDictionary(contentsOfFile: filePath) let pwd: String? = users?[username] as? String if pwd == password { return .just(.ok(message: "登录成功")) } return .just(.failed(message: "密码错误")) } }
apache-2.0
4cf7e821ed48483ef149ed4b76a876d2
27.504505
116
0.580278
4.625731
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/StudyNote/StudyNote/Texture/SNScrollViewController.swift
1
7726
// // SNScrollViewController.swift // StudyNote // // Created by 邬勇鹏 on 2019/1/11. // Copyright © 2019 Raymond. All rights reserved. // import UIKit import AsyncDisplayKit import MJRefresh private let kHeaderHeight: CGFloat = 150 fileprivate let offsetH: CGFloat = 0.5 class SNScrollViewController: UIViewController { @objc private lazy dynamic var mainScrollView: UIScrollView = { let scroll = UIScrollView(frame: CGRect(x: 0, y: 88, width: ScreenWidth, height: ScreenHeight - 88 - 34)) scroll.layer.borderWidth = 2 scroll.layer.borderColor = UIColor.green.cgColor scroll.isNeedMultipleScroll = true scroll.scrollState = .min scroll.delegate = self scroll.contentSize = CGSize(width: 0, height: scroll.height + kHeaderHeight) if #available(iOS 11, *) { scroll.contentInsetAdjustmentBehavior = .never } return scroll }() @objc private lazy dynamic var header: UIView = { let v = UIView(frame: CGRect(x: 0, y: 0, width: ScreenHeight, height: kHeaderHeight)) v.layer.borderWidth = 5 v.layer.borderColor = UIColor.yellow.cgColor return v }() private lazy var table: ASTableNode = { let temp = ASTableNode(style: .plain) temp.frame = CGRect(x: 0, y: kHeaderHeight, width: ScreenWidth, height: mainScrollView.height) temp.delegate = self temp.dataSource = self temp.view.estimatedRowHeight = 0 temp.view.estimatedSectionHeaderHeight = 0 temp.view.estimatedSectionFooterHeight = 0 temp.borderWidth = 5 temp.borderColor = UIColor.red.cgColor // temp.view.isNeedMultipleScroll = true temp.view.scrollState = .min temp.view.bounces = true if #available(iOS 11, *) { temp.view.contentInsetAdjustmentBehavior = .never } return temp }() @objc private dynamic var dataSource: [Int] = [8, 8, 8] private var childPages: [ASTableNode] = [] @objc override dynamic func viewDidLoad() { super.viewDidLoad() setupSubViews() } @objc private dynamic func setupSubViews() { self.view.addSubview(mainScrollView) mainScrollView.addSubview(header) mainScrollView.addSubnode(table) addMjRefresh() } } extension SNScrollViewController { @objc private dynamic func addMjRefresh() { table.view.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { let offset = self!.table.view.contentSize.height - self!.table.contentOffset.y print("刷新前:", self!.table.view.contentSize.height, offset) self?.dataSource.insert(3, at: 0) self?.table.view.mj_header?.endRefreshing() self?.table.reloadData(completion: { let offsetY = (self?.table.view.contentSize.height)! - offset print("刷新后:", self!.table.view.contentSize.height, offsetY) self?.table.setContentOffset(CGPoint(x: 0, y: 100), animated: false) }) }) }) // table.view.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {[weak self] in // DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { // self?.dataSource.append(2) // self?.refresh() // self?.table.view.mj_footer.endRefreshing() // }) // }) } } extension SNScrollViewController: ASTableDelegate, ASTableDataSource { func numberOfSections(in tableNode: ASTableNode) -> Int { return dataSource.count } func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { return dataSource[section] } func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode { let cell = SNCellNode() return cell } @objc dynamic func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } @objc dynamic func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.001 } @objc dynamic func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 30)) lbl.backgroundColor = UIColor.green lbl.text = "Section Header:\(section)" return lbl } func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) { } } extension SNScrollViewController { @objc dynamic func scrollViewDidScroll(_ scrollView: UIScrollView) { let direction = scrollView.panGestureRecognizer.translation(in: mainScrollView).y switch scrollView { case mainScrollView: setScrollOffsetState(scroll: scrollView, isSuper: true, condtion: { scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.height - offsetH }) if table.view.scrollState != .min { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: scrollView.contentSize.height - scrollView.height) } if direction > 0, scrollView.scrollState == .min, table.view.scrollState == .min { scrollView.contentOffset = .zero scrollView.isSupScrollView = true } // mainScrollView.isScrollEnabled = true // if direction < 0, mainScrollView.scrollState == .max, scrollView.scrollState == .max { //上滑 // mainScrollView.isScrollEnabled = false // print("------1") // } else if direction > 0, mainScrollView.scrollState == .min { //下滑 // mainScrollView.isScrollEnabled = false // print("------2") // } else { // print("------3") // } // print("main:", mainScrollView.scrollState, direction) break case table.view: setScrollOffsetState(scroll: scrollView, isSuper: false, condtion: nil) if direction < 0, mainScrollView.scrollState == .max, scrollView.scrollState == .max { print("sub: -------0") } else if direction > 0, mainScrollView.scrollState == .min, scrollView.scrollState == .min { print("sub: -------1") } else { if mainScrollView.scrollState != .max { scrollView.contentOffset = .zero } mainScrollView.isSupScrollView = false print("sub: -------2") } print("table:", scrollView.scrollState, mainScrollView.scrollState) break default: break } } private func setScrollOffsetState(scroll: UIScrollView, isSuper: Bool, condtion: (() -> Bool)?) { if isSuper && condtion == nil { return } scroll.scrollState = .center if scroll.contentOffset.y <= 0 { scroll.scrollState = .min return } if isSuper && condtion!() { scroll.scrollState = .max } } }
apache-2.0
6436ef481f9ff55b131add5068a9fe9b
33.662162
135
0.575309
4.964516
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat.ShareExtension/Compose/Cells/SEComposeFileCellModel.swift
1
2169
// // SEComposeFileCellModel.swift // Rocket.Chat.ShareExtension // // Created by Matheus Cardoso on 3/12/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit struct SEComposeFileCellModel: SEComposeCellModel { let contentIndex: Int var file: SEFile let image: UIImage var detailText: String = "" var fileSizeText: String = "" var originalNameText: String = "" var nameText: String { return file.name } var descriptionText: String { return file.description } init(contentIndex: Int, file: SEFile, isEnabled: Bool) { self.originalNameText = file.name self.contentIndex = contentIndex self.file = file let fileSize = Double(file.data.count)/1000000 self.fileSizeText = String(format: "%.2fMB", fileSize) if file.mimetype.contains("image/"), let image = UIImage(data: file.data) { self.image = image self.detailText = "\(Int(image.size.width))x\(Int(image.size.height))" } else if let url = file.fileUrl, let videoInfo = VideoInfo(videoURL: url) { self.image = videoInfo.thumbnail self.detailText = videoInfo.durationText } else { self.image = #imageLiteral(resourceName: "icon_file") } } var namePlaceholder: String { return localized("compose.file.name.placeholder") } var descriptionPlaceholder: String { return localized("compose.file.description.placeholder") } var nameHeight: CGFloat { return 44.0 } var descriptionHeight: CGFloat { return 88.0 } } // MARK: TableView Delegate extension SEComposeFileCellModel { func heightForRow(at indexPath: IndexPath) -> CGFloat { switch indexPath.row { case 0: return nameHeight case 1: return descriptionHeight default: return 0.0 } } } // MARK: Empty State extension SEComposeFileCellModel { static var emptyState: SEComposeFileCellModel { return SEComposeFileCellModel(contentIndex: 0, file: .empty, isEnabled: true) } }
mit
578059293293ee5a7b80546e6baa4c84
24.209302
85
0.630535
4.293069
false
false
false
false
DrewKiino/Tide
Tide/Source/Tide.swift
1
20883
// // Tide.swift // Tide // // Created by Andrew Aquino on 6/4/16. // Copyright © 2016 Andrew Aquino. All rights reserved. // import UIKit import CoreGraphics import SDWebImage open class Tide { public enum Mask { case rounded case squared case none } public enum fitMode { case clip case crop case scale case none } open var image: UIImage? public init(image: UIImage?) { self.image = image } open func fitClip(_ size: CGSize?) -> Tide { image = Tide.resizeImage(image, size: size) return self } open func rounded() -> Tide { image = Tide.Util.maskImageWithEllipse(image) return self } open static func resizeImage(_ image: UIImage?, size: CGSize?, fitMode: Tide.fitMode = .clip) -> UIImage? { guard let image = image, let size = size, size.height > 0 && size.width > 0 else { return nil } let imgRef = Util.CGImageWithCorrectOrientation(image) let originalWidth = CGFloat((imgRef?.width)!) let originalHeight = CGFloat((imgRef?.height)!) let widthRatio = size.width / originalWidth let heightRatio = size.height / originalHeight let scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio let resizedImageBounds = CGRect(x: 0, y: 0, width: round(originalWidth * scaleRatio), height: round(originalHeight * scaleRatio)) switch (fitMode) { case .clip: let scaleOffWidth: Bool = originalWidth > originalHeight let width: CGFloat = scaleOffWidth ? size.width : round(size.height * originalWidth / originalHeight) let height: CGFloat = !scaleOffWidth ? size.height : round(size.width * originalHeight / originalWidth) return Util.drawImageInBounds(image, bounds: CGRect(x: 0, y: 0, width: width, height: height)) case .crop: if let resizedImage = Util.drawImageInBounds(image, bounds: resizedImageBounds) { let croppedRect = CGRect(x: (resizedImage.size.width - size.width) / 2, y: (resizedImage.size.height - size.height) / 2, width: size.width, height: size.height) return Util.croppedImageWithRect(resizedImage, rect: croppedRect) } return nil case .scale: return Util.drawImageInBounds(image, bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height)) case .none: return image } } internal struct Util { static func maskImageWithEllipse( _ image: UIImage?, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white ) -> UIImage? { guard let image = image else { return nil } let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat((imgRef?.width)!) / image.scale, height: CGFloat((imgRef?.height)!) / image.scale) return Util.drawImageWithClosure(size) { (size: CGSize, context: CGContext) -> () in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.addEllipse(in: rect) context.clip() image.draw(in: rect) if (borderWidth > 0) { context.setStrokeColor(borderColor.cgColor); context.setLineWidth(borderWidth); context.addEllipse(in: CGRect(x: borderWidth / 2, y: borderWidth / 2, width: size.width - borderWidth, height: size.height - borderWidth)); context.strokePath(); } } } static func maskImageWithRoundedRect( _ image: UIImage?, cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white ) -> UIImage? { guard let image = image else { return nil } let imgRef = Util.CGImageWithCorrectOrientation(image) let size = CGSize(width: CGFloat((imgRef?.width)!) / image.scale, height: CGFloat((imgRef?.height)!) / image.scale) return Tide.Util.drawImageWithClosure(size) { (size: CGSize, context: CGContext) -> () in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIBezierPath(roundedRect:rect, cornerRadius: cornerRadius).addClip() image.draw(in: rect) if (borderWidth > 0) { context.setStrokeColor(borderColor.cgColor); context.setLineWidth(borderWidth); let borderRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius) borderPath.lineWidth = borderWidth * 2 borderPath.stroke() } } } static func CGImageWithCorrectOrientation(_ image : UIImage?) -> CGImage? { guard let image = image else { return nil } if (image.imageOrientation == UIImageOrientation.up) { return image.cgImage! } var transform : CGAffineTransform = CGAffineTransform.identity; switch (image.imageOrientation) { case UIImageOrientation.right, UIImageOrientation.rightMirrored: transform = transform.translatedBy(x: 0, y: image.size.height) transform = transform.rotated(by: CGFloat(-1.0 * M_PI_2)) break case UIImageOrientation.left, UIImageOrientation.leftMirrored: transform = transform.translatedBy(x: image.size.width, y: 0) transform = transform.rotated(by: CGFloat(M_PI_2)) break case UIImageOrientation.down, UIImageOrientation.downMirrored: transform = transform.translatedBy(x: image.size.width, y: image.size.height) transform = transform.rotated(by: CGFloat(M_PI)) break default: break } switch (image.imageOrientation) { case UIImageOrientation.rightMirrored, UIImageOrientation.leftMirrored: transform = transform.translatedBy(x: image.size.height, y: 0); transform = transform.scaledBy(x: -1, y: 1); break case UIImageOrientation.downMirrored, UIImageOrientation.upMirrored: transform = transform.translatedBy(x: image.size.width, y: 0); transform = transform.scaledBy(x: -1, y: 1); break default: break } let contextWidth : Int let contextHeight : Int switch (image.imageOrientation) { case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored: contextWidth = (image.cgImage?.height)! contextHeight = (image.cgImage?.width)! break default: contextWidth = (image.cgImage?.width)! contextHeight = (image.cgImage?.height)! break } let context : CGContext = CGContext(data: nil, width: contextWidth, height: contextHeight, bitsPerComponent: image.cgImage!.bitsPerComponent, bytesPerRow: image.cgImage!.bytesPerRow, space: image.cgImage!.colorSpace!, bitmapInfo: image.cgImage!.bitmapInfo.rawValue)!; context.concatenate(transform); context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: CGFloat(contextWidth), height: CGFloat(contextHeight))); let cgImage = context.makeImage(); return cgImage!; } static func drawImageInBounds(_ image: UIImage?, bounds : CGRect?) -> UIImage? { return drawImageWithClosure(bounds?.size) { [weak image] (size: CGSize, context: CGContext) -> () in var _bounds: CGRect? = bounds if let bounds = _bounds { image?.draw(in: bounds) } image = nil _bounds = nil }; } static func croppedImageWithRect(_ image: UIImage?, rect: CGRect?) -> UIImage? { return drawImageWithClosure(rect?.size) { [weak image] (size: CGSize, context: CGContext) -> () in guard let image = image else { return } var _rect: CGRect? = rect let drawRect = CGRect(x: -_rect!.origin.x, y: -_rect!.origin.y, width: image.size.width, height: image.size.height) context.clip(to: CGRect(x: 0, y: 0, width: _rect!.size.width, height: _rect!.size.height)) image.draw(in: drawRect) _rect = nil } } static func drawImageWithClosure(_ size: CGSize?, closure: @escaping (_ size: CGSize, _ context: CGContext) -> ()) -> UIImage? { var _closure: ((_ size: CGSize, _ context: CGContext) -> ())? = closure var _size: CGSize? = size var _image: UIImage? UIGraphicsBeginImageContextWithOptions(_size!, false, 0) if let context = UIGraphicsGetCurrentContext() { _closure?(_size!, context) _image = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() _size = nil _closure = nil return _image } } } extension UIImageView { @discardableResult public func fitClip(image: UIImage? = nil, fitMode: Tide.fitMode = .clip, completionHandler: ((_ image: UIImage?) -> Void)? = nil) -> Self { DispatchQueue.global(qos: .utility).async { [weak self] in var imageMod: UIImage? = Tide.resizeImage(image ?? self?.image, size: self?.frame.size, fitMode: fitMode) DispatchQueue.main.async { [weak self] in if let completionHandler = completionHandler { completionHandler(imageMod ?? image) } else { self?.image = imageMod ?? image } imageMod = nil } } return self } @discardableResult public func rounded( _ image: UIImage? = nil, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white, completionHandler: ((_ image: UIImage?) -> Void)? = nil ) -> Self { DispatchQueue.global(qos: .utility).async { [weak self] in var imageMod: UIImage? = Tide.Util.maskImageWithEllipse( image != nil ? image : self?.image, borderWidth: borderWidth, borderColor: borderColor ) DispatchQueue.main.async { [weak self] in if let completionHandler = completionHandler { completionHandler(imageMod ?? image) } else { self?.image = imageMod ?? image } imageMod = nil } } return self } @discardableResult public func squared( _ image: UIImage? = nil, cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white, completionHandler: ((_ image: UIImage?) -> Void)? = nil ) -> Self { DispatchQueue.global(qos: .utility).async { [weak self] in var imageMod: UIImage? = Tide.Util.maskImageWithRoundedRect( image != nil ? image : self?.image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor ) DispatchQueue.main.async { [weak self] in if let completionHandler = completionHandler { completionHandler(imageMod ?? image) } else { self?.image = imageMod ?? image } imageMod = nil } } return self } public func imageFromSource( _ url: String? = nil, placeholder: UIImage? = nil, fitMode: Tide.fitMode = .clip, mask: Tide.Mask = .none, cornerRadius: CGFloat = 0, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white, animated: Bool = false, showActivityAnimation: Bool = false, forced: Bool = true, progress: ((Float) -> Void)? = nil, skipImageSetAfterDownload: Bool = false, block: ((_ image: UIImage?) -> Void)? = nil) { func getImageKey() -> String? { let widthKey = frame.size.width.description let heightKey = frame.size.height.description let sourceKey = url?.hashValue.description ?? placeholder?.hashValue.description ?? "" let imageKey = sourceKey + widthKey + heightKey return imageKey.isEmpty ? nil : imageKey } func cacheImage(_ image: UIImage?) { SDImageCache.shared().store(image, forKey: getImageKey(), toDisk: false) } func setImage(_ image: UIImage?) { hideActivityIndicator() self.image = image ?? placeholder ?? self.image if animated { alpha = 0.0 UIView.animate(withDuration: 0.4, animations: { [weak self] in self?.alpha = 1.0 }) } block?(image ?? placeholder) } func fitClip(_ image: UIImage?, fitMode: Tide.fitMode) { // default the content mode so the image view does not // handle the resizing of the image itself contentMode = .center if let imageKey = getImageKey(), let image = SDImageCache.shared().imageFromMemoryCache(forKey: imageKey), image.size.equalTo(frame.size) { setImage(image) } else { self.fitClip(image: image, fitMode: fitMode) { [weak self] image in switch mask { case .rounded: self?.rounded(image, borderWidth: borderWidth, borderColor: borderColor) { image in cacheImage(image) setImage(image) } case .squared: self?.squared(image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor) { image in cacheImage(image) setImage(image) } case .none: cacheImage(image) setImage(image) } } } } if showActivityAnimation { showActivityIndicator() } if let imageKey = getImageKey(), let image = SDImageCache.shared().imageFromMemoryCache(forKey: imageKey) { setImage(image) } else if let url = url, let nsurl = URL(string: url) { // show activity let _ = SDWebImageManager.shared().imageDownloader?.downloadImage( with: nsurl, options: [ .useNSURLCache ], progress: { (received, actual, url) in if let _ = progress?(Float(received) / Float(actual)) {} } ) { (image, data, error, finished) -> Void in if skipImageSetAfterDownload { cacheImage(image) block?(image) } else { fitClip(image, fitMode: fitMode) } } } else if let placeholder = placeholder { fitClip(placeholder, fitMode: fitMode) } else if forced { self.image = nil } else { fitClip(image, fitMode: fitMode) } } } extension UIButton { @discardableResult public func fitClip( _ image: UIImage? = nil, fitMode: Tide.fitMode = .clip, forState: UIControlState, completionHandler: ((_ image: UIImage?) -> Void)? = nil ) -> Self { DispatchQueue.global(qos: .utility).async { [weak self] in var imageMod: UIImage? = Tide.resizeImage(image != nil ? image : self?.imageView?.image, size: self?.frame.size) DispatchQueue.main.async { [weak self] in if let completionHandler = completionHandler { completionHandler(imageMod ?? image) } else { self?.setImage(imageMod ?? image, for: forState) } imageMod = nil } } return self } @discardableResult public func rounded( _ image: UIImage? = nil, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white, forState: UIControlState, completionHandler: ((_ image: UIImage?) -> Void)? = nil ) -> Self { DispatchQueue.global(qos: .utility).async { [weak self] in var imageMod: UIImage? = Tide.Util.maskImageWithEllipse( image != nil ? image : self?.imageView?.image, borderWidth: borderWidth, borderColor: borderColor ) DispatchQueue.main.async { [weak self] in if let completionHandler = completionHandler { completionHandler(imageMod ?? image) } else { self?.setImage(imageMod ?? image, for: forState) } imageMod = nil } } return self } @discardableResult public func squared( _ image: UIImage? = nil, cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white, forState: UIControlState, completionHandler: ((_ image: UIImage?) -> Void)? = nil ) -> Self { DispatchQueue.global(qos: .utility).async { [weak self] in var imageMod: UIImage? = Tide.Util.maskImageWithRoundedRect( image != nil ? image : self?.imageView?.image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor ) DispatchQueue.main.async { [weak self] in if let completionHandler = completionHandler { completionHandler(imageMod ?? image) } else { self?.setImage(imageMod ?? image, for: forState) } imageMod = nil } } return self } public func imageFromSource( _ url: String? = nil, placeholder: UIImage? = nil, fitMode: Tide.fitMode = .clip, mask: Tide.Mask = .none, cornerRadius: CGFloat = 0, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.white, animated: Bool = false, showActivityAnimation: Bool = false, forced: Bool = true, forState: UIControlState, progress: ((Float) -> Void)? = nil, block: ((_ image: UIImage?) -> Void)? = nil) { func getImageKey() -> String? { let widthKey = frame.size.width.description let heightKey = frame.size.height.description let sourceKey = url?.hashValue.description ?? placeholder?.hashValue.description ?? "" let imageKey = sourceKey + widthKey + heightKey return imageKey.isEmpty ? nil : imageKey } func cacheImage(_ image: UIImage?) { SDImageCache.shared().store(image, forKey: getImageKey(), toDisk: false) } func setImage(_ image: UIImage?) { hideActivityIndicator() self.setImage(image, for: forState) if animated { alpha = 0.0 UIView.animate(withDuration: 0.4, animations: { [weak self] in self?.alpha = 1.0 }) } block?(image ?? placeholder) } func fitClip(_ image: UIImage?, fitMode: Tide.fitMode) { // default the content mode so the image view does not // handle the resizing of the image itself contentMode = .center if let imageKey = getImageKey(), let image = SDImageCache.shared().imageFromMemoryCache(forKey: imageKey), image.size.equalTo(frame.size) { setImage(image) } else { self.fitClip(image, fitMode: fitMode, forState: forState) { [weak self] image in switch mask { case .rounded: self?.rounded(image, borderWidth: borderWidth, borderColor: borderColor, forState: forState) { image in cacheImage(image) setImage(image) } case .squared: self?.squared(image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor, forState: forState) { image in cacheImage(image) setImage(image) } case .none: cacheImage(image) setImage(image) } } } } if showActivityAnimation { showActivityIndicator() } if let imageKey = getImageKey(), let image = SDImageCache.shared().imageFromMemoryCache(forKey: imageKey) { setImage(image) } else if let url = url, let nsurl = URL(string: url) { // show activity let _ = SDWebImageManager.shared().imageDownloader?.downloadImage( with: nsurl, options: [ .useNSURLCache ], progress: { (received, actual, url) in if let _ = progress?(Float(received) / Float(actual)) {} } ) { (image, data, error, finished) -> Void in fitClip(image ?? placeholder, fitMode: fitMode) } } else if let placeholder = placeholder { fitClip(placeholder, fitMode: fitMode) } else if forced { self.setImage(nil, for: forState) } else { fitClip(imageView?.image, fitMode: fitMode) } } } extension UIView { fileprivate func showActivityIndicator() { hideActivityIndicator() let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) activityIndicator.center = center addSubview(activityIndicator) activityIndicator.startAnimating() } fileprivate func hideActivityIndicator() { subviews.forEach { if let activityIndicator = $0 as? UIActivityIndicatorView { activityIndicator.stopAnimating() activityIndicator.removeFromSuperview() } } } }
mit
1b23a7682d904e45cf5e9ff15132bd4d
33.009772
145
0.607461
4.607679
false
false
false
false
GreenvilleCocoa/ChristmasDelivery
ChristmasDelivery/Santa.swift
1
972
// // Santa.swift // ChristmasDelivery // // Created by Marcus Smith on 12/8/14. // Copyright (c) 2014 GreenvilleCocoaheads. All rights reserved. // import SpriteKit class Santa: SKSpriteNode { init(size: CGSize) { let texture = SKTexture(imageNamed: "santa.png") super.init(texture: texture, color: UIColor.clearColor(), size: size) self.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: size.width * 0.95, height: size.height * 0.95)) self.physicsBody!.categoryBitMask = PhysicsCategory.Santa self.physicsBody!.contactTestBitMask = PhysicsCategory.Chimney|PhysicsCategory.Hazard|PhysicsCategory.EdgeLoop self.physicsBody!.collisionBitMask = PhysicsCategory.Chimney|PhysicsCategory.Hazard|PhysicsCategory.EdgeLoop self.physicsBody!.affectedByGravity = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented, stop calling it") } }
mit
89c4eab1b04c095a6b20acc8d75d0ef6
37.88
119
0.719136
4.244541
false
false
false
false
bag-umbala/music-umbala
Music-Umbala/Music-Umbala/Controller/DownloadVC.swift
1
6431
// // ThirdVC.swift // Music-Umbala // // Created by Nam Nguyen on 6/14/17. // Copyright © 2017 Nam Vo. All rights reserved. // import UIKit class DownloadVC: UIViewController, URLSessionDelegate, URLSessionDataDelegate { // MARK: *** Data model // MARK: *** Local variables var nameSong : String? var urlSong : String? var buffer:NSMutableData = NSMutableData() var session : URLSession? var dataTask:URLSessionDataTask? var expectedContentLength = 0 var destinationUrl : URL = URL(fileURLWithPath: "") // MARK: *** UI Elements @IBOutlet weak var nameSongLabel: UILabel! @IBOutlet weak var percentLabel: UILabel! @IBOutlet weak var progress: UIProgressView! // MARK: *** UI events @IBAction func backButton(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } // @IBAction func downloadButton(_ sender: UIButton) { func download() { // let url = URL(string: "http://j.ginggong.com/jDownload.ashx?id=ZWZFUFCB&h=mp3.zing.vn") // DispatchQueue.global().async { // do { // let data = try Data(contentsOf: url!) // DispatchQueue.global().sync { // // } // } catch { // error as? NSError // print("error") // } // } nameSong = "test" nameSong = nameSong ?? "noname" urlSong = "http://j.ginggong.com/jDownload.ashx?id=ZWZFUFCB&h=mp3.zing.vn" if let audioUrl = URL(string: urlSong!) { // then lets create your document folder url let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! // lets create your destination file url // let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(nameSong!).mp3") destinationUrl = documentsDirectoryURL.appendingPathComponent("\(nameSong!).mp3") print(destinationUrl) // to check if it exists before downloading it if FileManager.default.fileExists(atPath: destinationUrl.path) { print("The file already exists at path") // if the file doesn't exist } else { // you can use NSURLSession.sharedSession to download the data asynchronously // URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in // guard let location = location, error == nil else { return } // do { // // after downloading your file you need to move it to your destination url // try FileManager.default.moveItem(at: location, to: destinationUrl) // print("File moved to documents folder") // } catch let error as NSError { // print(error.localizedDescription) // } // }).resume() progress.progress = 0.0 let configuration = URLSessionConfiguration.default let manqueue = OperationQueue.main session = URLSession(configuration: configuration, delegate:self, delegateQueue: manqueue) dataTask = session?.dataTask(with: URLRequest.init(url: audioUrl)) dataTask?.resume() // session?.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in // guard let location = location, error == nil else { return } // do { // // after downloading your file you need to move it to your destination url // try FileManager.default.moveItem(at: location, to: destinationUrl) // print("File moved to documents folder") // } catch let error as NSError { // print(error.localizedDescription) // } // }).resume() } } } // MARK: *** UIViewController override func viewDidLoad() { super.viewDidLoad() download() progress.progress = 0.0 nameSongLabel.text = nameSong } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { //here you can get full lenth of your content expectedContentLength = Int(response.expectedContentLength) print(expectedContentLength) completionHandler(URLSession.ResponseDisposition.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { buffer.append(data as Data) let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength) progress.progress = percentageDownloaded print(percentageDownloaded) percentLabel.text = "\(floor(percentageDownloaded) * 100)%" } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { //use buffer here.Download is done progress.progress = 1.0 // download 100% complete print("100%") percentLabel.text = "100%" do { // after downloading your file you need to move it to your destination url // try FileManager.default.moveItem(at: dataTask, to: destinationUrl) buffer.write(to: destinationUrl, atomically: true) print("File moved to documents folder") } catch let error as NSError { print(error.localizedDescription) } } /* // 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
5b0a790460f3bbab0058db1490f749d8
40.217949
179
0.588958
5.131684
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/Sort/Library/BottomDrawer.swift
1
18135
// // BottomDrawer.swift // BottomDrawer // // Created by Seva Billevich on 18/03/15. // Copyright (c) 2015 Go Travel Un Limited. All rights reserved. // import UIKit private let kHandleButtonHeight: CGFloat = 55 private let kActionButtonHeight: CGFloat = 50 private let kSeparatorHeight: CGFloat = 1 / UIScreen.main.scale private let kShaddowPadding: CGFloat = 10 private let kDrawerNibName = "BottomDrawer" class BottomDrawerView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) applyShadow() } func applyShadow() { let shadowPath = UIBezierPath(rect: CGRect( origin: CGPoint(x: -kShaddowPadding, y: 0), size: CGSize(width: bounds.size.width + kShaddowPadding * 2, height: bounds.size.height)) ) layer.shadowOffset = CGSize(width: 0, height: -1) layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.29 layer.shadowRadius = 3 layer.shadowPath = shadowPath.cgPath } } public class BottomDrawer: UIViewController, UINavigationControllerDelegate { static var defaultTitleStyleAttributes: [NSAttributedString.Key: Any] = createDefaultStyleAttributes() static var defaultActionButtonStyle: ActionButtonStyle = ActionButtonStyle( height: kActionButtonHeight, backgroundColor: UIColor.white, selectedBackgroundColor: UIColor(white: 0.9, alpha: 1), titleAttributes: createActionButtonTitleAttributes() ) static var defaultEnableHapticFeedback = false public var drawerHeight:CGFloat { get { var drawerHeight = contentHeight if attributedHandleTitle != nil { drawerHeight += kHandleButtonHeight + kSeparatorHeight } if attributedActionButtonTitle != nil { drawerHeight += actionButtonStyle.height + kSeparatorHeight } return drawerHeight } } public var contentHeight: CGFloat = 195 { didSet { updateDrawerHeight() } } public var drawerContainerOffset: CGFloat = 44 public var maxOverlayAlpha: CGFloat = 0.35 public var drawerAnimationDuration: TimeInterval = 0.3 public var hidesNavigationBarPermanently = false public var titleAttributes = BottomDrawer.defaultTitleStyleAttributes { didSet { self.updateAttributedHandleTitle() } } public var handleTitle: String? { didSet { self.updateAttributedHandleTitle() } } public var attributedHandleTitle: NSAttributedString? { didSet { updateHandleButton() } } public var actionButtonTitle: String? { didSet { if let title = actionButtonTitle { let attributes = actionButtonStyle.titleAttributes attributedActionButtonTitle = NSAttributedString(string: title.uppercased(), attributes: attributes) } else { attributedActionButtonTitle = nil } } } public var attributedActionButtonTitle: NSAttributedString? { didSet { updateActionButton() } } public struct ActionButtonStyle { var height: CGFloat var backgroundColor: UIColor var selectedBackgroundColor: UIColor var titleAttributes: [NSAttributedString.Key: Any] } public var actionButtonStyle = BottomDrawer.defaultActionButtonStyle { didSet { updateActionButton() setupActionButtonBackground() } } public var enableHapticFeedback = BottomDrawer.defaultEnableHapticFeedback { didSet { updateHapticFeedback() } } public var actionClick: ((BottomDrawer) -> Void)? public var willDismissBlock: ((BottomDrawer, _ programmatically: Bool) -> Void)? public var dismissBlock: ((BottomDrawer, _ programmatically: Bool) -> Void)? private var contentController: UIViewController! private var navigationControllerClass: UINavigationController.Type! private var drawerNavigationController: UINavigationController? private var drawerWindow:UIWindow? private var _navDelegateProxy = _NavDelegateProxy() private var visible: Bool = false private var triggerHapticFeedback: (() -> Void)? @IBOutlet weak var drawerView: UIView! @IBOutlet weak var overlay: UIView! @IBOutlet weak var drawerBottomConstraint: NSLayoutConstraint! @IBOutlet weak var drawerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var drawerContainerConstraint: NSLayoutConstraint! @IBOutlet weak var container: UIView! @IBOutlet weak var handleButton: UIButton! @IBOutlet weak var handleButtonHeightConstraint: NSLayoutConstraint! @IBOutlet weak var topSeparatorHeightConstraint: NSLayoutConstraint! @IBOutlet weak var bottomSeparatorHeightConstraint: NSLayoutConstraint! @IBOutlet weak var topSeparator: UIView! @IBOutlet weak var bottomSeparator: UIView! @IBOutlet weak var actionButtonHeightConstraint: NSLayoutConstraint! @IBOutlet weak var actionButton: UIButton! public convenience init(viewController: UIViewController) { self.init(nibName: kDrawerNibName, viewController: viewController, navigationControllerClass: UINavigationController.self) } public convenience init(viewController: UIViewController, navigationControllerClass: UINavigationController.Type) { self.init(nibName: kDrawerNibName, viewController: viewController, navigationControllerClass: navigationControllerClass) } public init(nibName: String, viewController: UIViewController, navigationControllerClass: UINavigationController.Type) { super.init(nibName: nibName, bundle: nil) self.contentController = viewController self.navigationControllerClass = navigationControllerClass.self updateHapticFeedback() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** * Show drawer in window */ public func show() { let prevKeyWindow = UIApplication.shared.keyWindow ?? UIApplication.shared.windows.first! drawerWindow = UIWindow(frame: prevKeyWindow.frame) drawerNavigationController = navigationControllerClass.init(rootViewController: self) drawerNavigationController?.isNavigationBarHidden = true drawerWindow?.backgroundColor = UIColor.clear drawerWindow?.rootViewController = drawerNavigationController drawerWindow?.windowLevel = UIWindow.Level.statusBar + 1 drawerWindow?.isHidden = false drawerWindow?.makeKeyAndVisible() } /** * Show drawer in view */ public func showInViewController(_ parentViewController: UIViewController) { drawerNavigationController = navigationControllerClass.init(rootViewController: self) drawerNavigationController?.isNavigationBarHidden = true parentViewController.addChildViewController(childController: drawerNavigationController, toFillView: parentViewController.view) visible = true } override public func viewDidLoad() { super.viewDidLoad() navigationController?.view.backgroundColor = UIColor.clear addChildViewController(childController: contentController, toFillView: container) updateHandleButton() updateActionButton() setupViews() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { self.showDrawerAnimated() } _navDelegateProxy._originalDelegate = navigationController?.delegate _navDelegateProxy._newDelegate = self navigationController?.delegate = nil navigationController?.delegate = _navDelegateProxy } func setupViews() { if drawerContainerConstraint != nil { drawerContainerConstraint.constant = drawerContainerOffset } drawerHeightConstraint.constant = drawerHeight + drawerContainerOffset drawerBottomConstraint.constant = drawerHeight + drawerContainerOffset overlay.alpha = 0 if let topSeparatorConstraint = topSeparatorHeightConstraint { topSeparatorConstraint.constant = kSeparatorHeight } let separatorColor = UIColor(hue: 0, saturation: 0, brightness: 0.79, alpha: 1) if topSeparator != nil { topSeparator.backgroundColor = separatorColor } if bottomSeparator != nil { bottomSeparator.backgroundColor = separatorColor } setupActionButtonBackground() } func setupActionButtonBackground() { guard let actionButton = actionButton else { return } actionButton.setBackgroundImage(UIImage(color: actionButtonStyle.backgroundColor), for: .normal) actionButton.setBackgroundImage(UIImage(color: actionButtonStyle.selectedBackgroundColor), for: .highlighted) } func showDrawerAnimated() { triggerHapticFeedback?() UIView.animate(withDuration: drawerAnimationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .curveEaseIn, animations: { self.drawerBottomConstraint.constant = self.drawerContainerOffset self.view.layoutIfNeeded() self.overlay.alpha = self.maxOverlayAlpha }, completion: nil) visible = true } func hideDrawerAnimated(completionBlock: @escaping () -> Void) { UIView.animate(withDuration: drawerAnimationDuration, delay: 0, options: .curveEaseIn, animations: { self.drawerBottomConstraint.constant = self.drawerHeight + self.drawerContainerOffset self.view.layoutIfNeeded() self.overlay.alpha = 0 }, completion: { [weak self] Bool in self?.visible = false completionBlock() }) } public func dismissDrawer() { dismissDrawer(programmatically: true) } public func isVisible() -> Bool { return visible } @IBAction internal func handleButtonClick() { dismissDrawer(programmatically: false) } @objc(dismissDrawerProgrammatically:) public func dismissDrawer(programmatically: Bool) { navigationController?.delegate = _navDelegateProxy._originalDelegate willDismissBlock?(self, programmatically) hideDrawerAnimated { self.deleteChildViewController(self.contentController) self.drawerWindow?.isHidden = true self.drawerWindow = nil self.drawerNavigationController?.parent?.deleteChildViewController(self.drawerNavigationController) self.drawerNavigationController?.view.isHidden = true self.drawerNavigationController = nil self.dismissBlock?(self, programmatically) } } // MARK: - gesture recognizer handling @IBAction func handlePan(recognizer: UIPanGestureRecognizer) { let location = recognizer.location(in: self.view).y let velocity = recognizer.velocity(in: self.view).y var newBottomOffset = -1 * (self.view.bounds.height - location - self.drawerHeight - self.drawerContainerOffset) if newBottomOffset < drawerContainerOffset { //slow down pan tracking newBottomOffset = newBottomOffset / 2 + drawerContainerOffset / 2 } if newBottomOffset < 0 { newBottomOffset = 0 } switch recognizer.state { case .began: UIView.animate(withDuration: drawerAnimationDuration, delay: 0, options: .curveEaseOut, animations: { self.updateBottomOffset(newBottomOffset: newBottomOffset) self.view.layoutIfNeeded() }, completion: { Bool in }) case .changed: updateBottomOffset(newBottomOffset: newBottomOffset) case .ended: if velocity > 100 || (velocity >= 0 && newBottomOffset > self.drawerContainerOffset) { self.dismissDrawer(programmatically: false) } else { self.showDrawerAnimated() } default: break } } @IBAction func didClickActionButton(sender: AnyObject) { actionClick?(self) } private func updateHandleButton() { guard handleButton != nil else { return } //not loaded yet if let title = attributedHandleTitle { handleButton.setAttributedTitle(title, for: .normal) handleButtonHeightConstraint.constant = kHandleButtonHeight handleButton.contentEdgeInsets = UIEdgeInsets.init(top: 2, left: 1, bottom: 0, right: 0) handleButton.alpha = 1 } else { handleButton.setAttributedTitle(nil, for: .normal) handleButtonHeightConstraint.constant = 0 handleButton.alpha = 0 } updateDrawerHeight() } private func updateActionButton() { guard actionButton != nil else { return } //not loaded yet if let title = attributedActionButtonTitle { actionButton.setAttributedTitle(title, for: .normal) actionButtonHeightConstraint.constant = actionButtonStyle.height bottomSeparatorHeightConstraint.constant = kSeparatorHeight actionButton.alpha = 1 } else { actionButton.setAttributedTitle(nil, for: .normal) actionButtonHeightConstraint.constant = 0 if bottomSeparatorHeightConstraint != nil { bottomSeparatorHeightConstraint.constant = 0 } actionButton.alpha = 0 } updateDrawerHeight() } func updateBottomOffset(newBottomOffset: CGFloat) { self.drawerBottomConstraint.constant = newBottomOffset self.overlay.alpha = self.maxOverlayAlpha * ( (self.drawerContainerOffset - newBottomOffset) / self.drawerHeight + 1 ) } private func updateDrawerHeight() { drawerHeightConstraint?.constant = drawerHeight + drawerContainerOffset } private func updateAttributedHandleTitle() { if let title = handleTitle { attributedHandleTitle = NSAttributedString(string: title.uppercased(), attributes: self.titleAttributes) } else { attributedHandleTitle = nil } } private func updateHapticFeedback() { if enableHapticFeedback { if #available(iOS 10.0, *) { let impactGenerator = UIImpactFeedbackGenerator.init(style: .light) impactGenerator.prepare() triggerHapticFeedback = { impactGenerator.impactOccurred() } } } else { triggerHapticFeedback = nil } } // MARK: navigation controller delegate class _NavDelegateProxy: NSObject, UINavigationControllerDelegate { weak var _originalDelegate: UINavigationControllerDelegate? weak var _newDelegate: UINavigationControllerDelegate? override func responds(to aSelector: Selector!) -> Bool { return super.responds(to: aSelector) || _originalDelegate?.responds(to: aSelector) == true } override func forwardingTarget(for aSelector: Selector!) -> Any? { if _originalDelegate?.responds(to: aSelector) == true { return _originalDelegate } else { return super.forwardingTarget(for: aSelector) as AnyObject? } } func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { _originalDelegate?.navigationController?(navigationController, willShow: viewController, animated: animated) _newDelegate?.navigationController?(navigationController, willShow: viewController, animated: animated) } } public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if viewController.isEqual(self) { navigationController.setNavigationBarHidden(true, animated: true) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) { self.drawerWindow?.windowLevel = UIWindow.Level.statusBar + 1 } } else { navigationController.setNavigationBarHidden(hidesNavigationBarPermanently, animated: true) drawerWindow?.windowLevel = UIWindow.Level.normal } } } /// MARK: child view controller handling private extension UIViewController { func addChildViewController(childController: UIViewController?, toFillView containerView: UIView) { guard let childController = childController else { return } self.addChild(childController) containerView.addSubview(childController.view) childController.view.frame = CGRect(origin: .zero, size: containerView.bounds.size) childController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] childController.didMove(toParent: self) } func deleteChildViewController(childController: UIViewController?) { childController?.willMove(toParent: nil) childController?.view.removeFromSuperview() childController?.removeFromParent() } } private func createDefaultStyleAttributes() -> [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor : UIColor(hue: 0, saturation: 0, brightness: 0.36, alpha: 1), NSAttributedString.Key.kern : 1.0 as AnyObject ] } private func createActionButtonTitleAttributes() -> [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor(hue: 0, saturation: 0, brightness: 0.5, alpha: 1), NSAttributedString.Key.kern: 1.0 as AnyObject ] }
mit
a68ff146e8685b56d241b0a3fa484a12
38
163
0.67571
5.576568
false
false
false
false
dasdom/InteractivePlayground
InteractivePlayground.playground/Pages/Spring Animation.xcplaygroundpage/Contents.swift
1
3844
//: [Previous](@previous) import UIKit import PlaygroundSupport class View: UIView { let redBox: UIView let durationSlider: UISlider let durationLabel: UILabel let dampingSlider: UISlider let dampingLabel: UILabel let initialVelocitySlider: UISlider let initialVelocityLabel: UILabel override init(frame: CGRect) { let makeStackView = { (labelText: String, sliderMin: Float, sliderMax: Float) -> (UILabel, UISlider, UIStackView) in let slider = UISlider() slider.minimumValue = sliderMin slider.maximumValue = sliderMax let label = UILabel() label.text = labelText + ": \(sliderMin)" label.textAlignment = .center let stackView = UIStackView(arrangedSubviews: [label, slider]) stackView.axis = .vertical stackView.alignment = .fill return (label, slider, stackView) } var durationStackView: UIStackView = UIStackView() (durationLabel, durationSlider, durationStackView) = makeStackView("Duration", 0.1, 10) var dampingStackView: UIStackView = UIStackView() (dampingLabel, dampingSlider, dampingStackView) = makeStackView("Damping", 0.1, 1) var velocityStackView: UIStackView = UIStackView() (initialVelocityLabel, initialVelocitySlider, velocityStackView) = makeStackView("Initial Velocity", 0, 5) let button = UIButton() button.setTitle("Animate", for: .normal) button.backgroundColor = UIColor.blue let stackView = UIStackView(arrangedSubviews: [durationStackView, dampingStackView, velocityStackView, button]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 30 redBox = UIView(frame: CGRect(x: 50, y: 20, width: 30, height: 30)) redBox.backgroundColor = UIColor.red super.init(frame: frame) backgroundColor = UIColor.white addSubview(redBox) addSubview(stackView) durationSlider.addTarget(self, action: #selector(changeDuration(sender:)), for: .valueChanged) dampingSlider.addTarget(self, action: #selector(changeDamping(sender:)), for: .valueChanged) initialVelocitySlider.addTarget(self, action: #selector(changeVelocity(sender:)), for: .valueChanged) button.addTarget(self, action: #selector(View.animate as (View) -> () -> ()), for: .touchUpInside) let views = ["stackView": stackView] var layoutConstraints = [NSLayoutConstraint]() layoutConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|-[stackView]-|", options: [], metrics: nil, views: views) layoutConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-80-[stackView]", options: [], metrics: nil, views: views) NSLayoutConstraint.activate(layoutConstraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animate() { UIView.animate(withDuration: Double(durationSlider.value), delay: 0.0, usingSpringWithDamping:CGFloat(dampingSlider.value), initialSpringVelocity: CGFloat(initialVelocitySlider.value), options: [], animations: { if self.redBox.frame.origin.x > 100 { self.redBox.frame.origin.x = 50 } else { self.redBox.frame.origin.x = self.frame.width-self.redBox.frame.size.width-50 } }) { (_) in } } func changeDuration(sender: UISlider) { durationLabel.text = "Duration: \(durationSlider.value)" } func changeDamping(sender: UISlider) { dampingLabel.text = "Damping: \(dampingSlider.value)" } func changeVelocity(sender: UISlider) { initialVelocityLabel.text = "Initial Velocity: \(initialVelocitySlider.value)" } } let view = View(frame: CGRect(x: 0, y: 0, width: 300, height: 400)) PlaygroundPage.current.liveView = view //: [Next](@next)
mit
d89b601a008e27cabb8e36fc4a1949cc
35.264151
215
0.697971
4.549112
false
false
false
false
box/box-ios-sdk
Tests/Responses/WebhookItemSpecs.swift
1
9598
// // WebhookItemSpecs.swift // BoxSDKTests-iOS // // Created by Artur Jankowski on 21/09/2021. // Copyright © 2021 box. All rights reserved. // @testable import BoxSDK import Nimble import Quick class WebhookItemSpecs: QuickSpec { override func spec() { describe("Webhook Item") { describe("init()") { it("should correctly deserialize a file type from full JSON representation") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFile", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let jsonDict = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) as! [String: Any] let webhookItem = try WebhookItem(json: jsonDict) guard case let .file(file) = webhookItem else { fail("This should be a file") return } expect(file.type).to(equal("file")) expect(file.id).to(equal("11111")) expect(file.etag).to(equal("2")) expect(file.sequenceId).to(equal("2")) expect(file.sha1).to(equal("14acc506f2021b2f1a9d81097ca82e14887b34fe")) expect(file.name).to(equal("script.js")) expect(file.extension).to(equal("js")) expect(file.description).to(equal("My test script")) expect(file.size).to(equal(33510)) } catch { fail("Failed with Error: \(error)") } } it("should correctly deserialize a folder type from full JSON representation") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFolder", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let jsonDict = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) as! [String: Any] let webhookItem = try WebhookItem(json: jsonDict) guard case let .folder(folder) = webhookItem else { fail("This should be a folder") return } expect(folder.type).to(equal("folder")) expect(folder.id).to(equal("11111")) expect(folder.sequenceId).to(equal("0")) expect(folder.sequenceId).to(equal("0")) expect(folder.etag).to(equal("0")) expect(folder.name).to(equal("Test Folder")) expect(folder.createdAt?.iso8601).to(equal("2013-06-01T22:52:00Z")) expect(folder.modifiedAt?.iso8601).to(equal("2019-05-28T19:12:46Z")) expect(folder.description).to(equal("A folder for testing")) expect(folder.isCollaborationRestrictedToEnterprise).to(beTrue()) expect(folder.size).to(equal(814_688_861)) } catch { fail("Failed with Error: \(error)") } } it("should throw BoxCodingError.valueMismatch exception when deserialize an object with an unknown value in type filed") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFile_ValueFormatMismatch", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let webhookItemDictionary = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) let expectedError = BoxCodingError(message: .valueMismatch(key: "type", value: "invalid_type_value", acceptedValues: ["file", "folder"])) expect(try WebhookItem(json: webhookItemDictionary as! [String: Any])).to(throwError(expectedError)) } catch { fail("Failed with Error: \(error)") } } it("should throw BoxCodingError.typeMismatch exception when deserialize object with no type field") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFile_MissingRequiredField", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let webhookItemDictionary = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) let expectedError = BoxCodingError(message: .typeMismatch(key: "type")) expect(try WebhookItem(json: webhookItemDictionary as! [String: Any])).to(throwError(expectedError)) } catch { fail("Failed with Error: \(error)") } } } describe("rawData") { it("should be equal to json data used to create the WebhookItem file type object") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFile", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let jsonDict = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) as! [String: Any] let webhookItem = try WebhookItem(json: jsonDict) expect(JSONComparer.match(json1: webhookItem.rawData, json2: jsonDict)).to(equal(true)) expect(webhookItem.json()).to(equal(webhookItem.toJSONString())) } catch { fail("Failed with Error: \(error)") } } it("should be equal to json data used to create the WebhookItem folder type object") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFolder", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let jsonDict = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) as! [String: Any] let webhookItem = try WebhookItem(json: jsonDict) expect(JSONComparer.match(json1: webhookItem.rawData, json2: jsonDict)).to(equal(true)) expect(webhookItem.json()).to(equal(webhookItem.toJSONString())) } catch { fail("Failed with Error: \(error)") } } } describe("debugDescription") { it("should return correct description for a file type") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFile", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let jsonDict = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) as! [String: Any] let webhookItem = try WebhookItem(json: jsonDict) expect(webhookItem.debugDescription).to(equal("file Optional(\"script.js\")")) } catch { fail("Failed with Error: \(error)") } } it("should return correct description for folder type") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullFolder", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) let jsonDict = try JSONSerialization.jsonObject(with: contents.data(using: .utf8)!) as! [String: Any] let webhookItem = try WebhookItem(json: jsonDict) expect(webhookItem.debugDescription).to(equal("folder Optional(\"Test Folder\")")) } catch { fail("Failed with Error: \(error)") } } } } } }
apache-2.0
34ffc9ff84776f0d826056d4ab91b7c5
47.964286
161
0.482755
5.403716
false
false
false
false
JaySonGD/SwiftDayToDay
Alipay/Alipay/AppDelegate.swift
1
1721
// // AppDelegate.swift // Alipay // // Created by czljcb on 16/3/16. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { if url.host == "safepay"{ AlipaySDK.defaultService().processOrderWithPaymentResult(url, standbyCallback: { (resultDic: [NSObject : AnyObject]!) -> Void in print(resultDic) }) } return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if url.host == "safepay"{ AlipaySDK.defaultService().processOrderWithPaymentResult(url, standbyCallback: { (resultDic: [NSObject : AnyObject]!) -> Void in print(resultDic) }) } return true } func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { if url.host == "safepay"{ AlipaySDK.defaultService().processOrderWithPaymentResult(url, standbyCallback: { (resultDic: [NSObject : AnyObject]!) -> Void in print(resultDic) }) } return true } }
mit
db4ad486070e52834e4d949d8ee631be
25.430769
140
0.58149
5.269939
false
false
false
false
yikaraman/iOS8-day-by-day
08-today-extension/GitHubToday/GitHubToday/TableViewController.swift
3
2478
// // Copyright 2014 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import GitHubTodayCommon class TableViewController: UITableViewController { let dataProvider = GitHubDataProvider() let mostRecentEventCache = GitHubEventCache(userDefaults: NSUserDefaults(suiteName: "group.GitHubToday")) var events: [GitHubEvent] = [GitHubEvent]() { didSet { // Must call reload on the main thread dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } } override func awakeFromNib() { title = "GitHub Events" dataProvider.getEvents("sammyd", callback: { githubEvents in self.events = githubEvents self.mostRecentEventCache.mostRecentEvent = githubEvents[0] }) } func scrollToAndHighlightEvent(eventId: Int) { var eventIndex: Int? = nil for (index, event) in enumerate(events) { if event.id == eventId { eventIndex = index break } } if let eventIndex = eventIndex { let indexPath = NSIndexPath(forRow: eventIndex, inSection: 0) tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Top) } } // DataSource override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { let count = events.count return count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { return tableView.dequeueReusableCellWithIdentifier("EventCell", forIndexPath: indexPath) as UITableViewCell } override func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) { if let eventCell = cell as? EventTableViewCell { let event = events[indexPath.row] eventCell.event = event } } }
apache-2.0
fed849572784eea7388e431a91dc022c
30.367089
135
0.711461
4.68431
false
false
false
false
AlexYang1949/FFLabel
FFLabel/FFLabel Swift Demo/FFLabel Swift Demo/TableViewController.swift
10
1346
// // TableViewController.swift // FFLabel Swift Demo // // Created by 刘凡 on 15/7/20. // Copyright © 2015年 joyios. All rights reserved. // import UIKit import FFLabel class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 80 tableView.rowHeight = UITableViewAutomaticDimension } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DemoCell // Configure the cell... cell.contentLabel.text = demoContent return cell } } class DemoCell: UITableViewCell, FFLabelDelegate { @IBOutlet weak var contentLabel: FFLabel! override func awakeFromNib() { contentLabel.labelDelegate = self } override func layoutSubviews() { super.layoutSubviews() contentLabel.preferredMaxLayoutWidth = bounds.width - 16 } func labelDidSelectedLinkText(label: FFLabel, text: String) { print(text) } }
mit
0cd365e2c6ab472039b6e23ed3611e71
24.769231
118
0.676624
5.271654
false
false
false
false
Kyoooooo/DouYuZhiBo
DYZB/DYZB/Classes/Home/View/RecommendCycleView.swift
1
4556
// // RecommendCycleView.swift // DYZB // // Created by 张起哲 on 2017/9/6. // Copyright © 2017年 张起哲. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { //定义属性 var cycleTimer : Timer? var cycleModels : [CycleModel]? { didSet { //1.刷新 collectionView.reloadData() //2.设置pageControl pageControl.numberOfPages = cycleModels?.count ?? 0 //3.默认滚动到中间某一个位置(是为了让一开始滚动时就可以向左滚动) let indexPath = NSIndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0)//大概是60的位置 collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false) //4.添加定时器(添加之前先移除,防止出现问题) removeCycleTimer() addCycleTimer() } } //控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! //系统回掉 override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件拉伸而拉伸 autoresizingMask = UIViewAutoresizing() //注册cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) } override func layoutSubviews() { super.layoutSubviews() // 设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } //提供一个快速创建View的类方法 extension RecommendCycleView { class func recomendCycleView() ->RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } //遵守UICollectionView数据源协议 extension RecommendCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //*10000时实现无限轮播,其实你一直滚也是可以滚完的(深井冰你就去滚一天吧) return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView .dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell //这里加上取模操作,是因为上面*10000,不然数组会越界 cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count] return cell } } //遵守UICollectionView代理协议 extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { //1.获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 //+ scrollView.bounds.width * 0.5是让滚动到一半时让pageControl变化 //2.计算pageControl的currentIndex //这里取模也是因为上面实现无限轮播*10000 pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } ///用户滚动时候,取消定时器的滚动 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } //对定时器的操作 extension RecommendCycleView { fileprivate func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: .commonModes) } fileprivate func removeCycleTimer() { //从runloop中移除定时器 cycleTimer?.invalidate() cycleTimer = nil } @objc private func scrollToNext() { //1.获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offSetX = currentOffsetX + collectionView.bounds.width //2.滚动到该位置 collectionView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
mit
f138faba0d6b795744a4c8b464e18294
29.816794
129
0.654942
4.834731
false
false
false
false
jemmons/Medea
Tests/MedeaTests/JSONObjectTests.swift
1
3578
import XCTest import Medea class JSONObjectTests: XCTestCase { func testRawObject() { let subject = try! JSONHelper.jsonObject(from: "{\"foo\": \"bar\"}") XCTAssertEqual(subject["foo"] as! String, "bar") } func testRawJSONArray() { let shouldThrow = expectation(description: "throws notJSONObject error") do { let _ = try JSONHelper.jsonObject(from: "[1,2,3]") } catch JSONError.unexpectedType { shouldThrow.fulfill() } catch {} waitForExpectations(timeout: 0.1, handler: nil) } func testInvalidRawJSON() { let shouldThrow = expectation(description: "should not parse") do { let _ = try JSONHelper.jsonObject(from: "foobarbaz") } catch JSONError.malformed { shouldThrow.fulfill() } catch {} waitForExpectations(timeout: 0.1, handler: nil) } func testInvalidByOmission() { let shouldThrow = expectation(description: "should not parse") do { let _ = try JSONHelper.jsonObject(from: "") } catch JSONError.malformed { shouldThrow.fulfill() } catch {} waitForExpectations(timeout: 0.1, handler: nil) } func testEmptyRawJSON() { let subject = try! JSONHelper.jsonObject(from: "{}") XCTAssert(subject.isEmpty) } func testJSONObject() { let subject = try! JSONHelper.string(from: ["foo": "bar"]) XCTAssertEqual(subject, "{\"foo\":\"bar\"}") } func testValidJSONObject() { let subject = try! ValidJSONObject(["baz": "thud"]) let object = JSONHelper.string(from: subject) XCTAssertEqual(object, "{\"baz\":\"thud\"}") } func testInvaidJSONObject() { let shouldRejectValue = expectation(description: "invalid JSON value") do { let _ = try JSONHelper.string(from: ["date": Date()]) } catch JSONError.invalidType { shouldRejectValue.fulfill() } catch {} waitForExpectations(timeout: 0.1, handler: nil) } func testEmptyJSONObject() { let subject = try! JSONHelper.string(from: [:]) XCTAssertEqual(subject, "{}") } func testIsValid() { XCTAssert(JSONHelper.isValid("{\"foo\":42}")) XCTAssert(JSONHelper.isValid("{\"one\": \"two\"}")) XCTAssert(JSONHelper.isValid(["foo": 42, "bar": false, "baz": NSNull()])) XCTAssertFalse(JSONHelper.isValid("{1:2}")) XCTAssertFalse(JSONHelper.isValid("")) XCTAssertFalse(JSONHelper.isValid("foobar")) XCTAssertFalse(JSONHelper.isValid(["non-representable": Date()])) } func testValidate() { _ = try! JSONHelper.validate("{\"foo\":42}") _ = try! JSONHelper.validate("{\"one\": \"two\"}") _ = try! JSONHelper.validate(["foo": 42, "bar": false, "baz": NSNull()]) let shouldRejectStringKey = expectation(description: "string with bad key") let shouldRejectEmptyString = expectation(description: "empty string") let shouldRejectString = expectation(description: "string") let shouldRejectValue = expectation(description: "bad value") do { try JSONHelper.validate("{1:2}") } catch JSONError.malformed { shouldRejectStringKey.fulfill() } catch { } do { try JSONHelper.validate("") } catch JSONError.malformed { shouldRejectEmptyString.fulfill() } catch { } do { try JSONHelper.validate("foobar") } catch JSONError.malformed { shouldRejectString.fulfill() } catch { } do { try JSONHelper.validate(["non-representable": Date()]) } catch JSONError.invalidType { shouldRejectValue.fulfill() } catch { } waitForExpectations(timeout: 1.0, handler: nil) } }
mit
6f1c256199dd1d846933f9a69e2cf65b
28.570248
95
0.643097
4.279904
false
true
false
false
Ben21hao/edx-app-ios-new
Source/PostsViewController.swift
1
27725
// // PostsViewController.swift // edX // // Created by Tang, Jeff on 5/19/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class PostsViewController: TDSwiftBaseViewController, UITableViewDataSource, UITableViewDelegate, PullRefreshControllerDelegate, InterfaceOrientationOverriding, DiscussionNewPostViewControllerDelegate { typealias Environment = protocol<NetworkManagerProvider, OEXRouterProvider, OEXAnalyticsProvider, OEXStylesProvider> enum Context { case Topic(DiscussionTopic) case Following case Search(String) case AllPosts var allowsPosting : Bool { switch self { case Topic: return true case Following: return true case Search: return false case AllPosts: return true } } var topic : DiscussionTopic? { switch self { case let Topic(topic): return topic case Search(_): return nil case Following(_): return nil case AllPosts(_): return nil } } var navigationItemTitle : String? { switch self { case let Topic(topic): return topic.name case Search(_): return Strings.searchResults case Following(_): return Strings.postsImFollowing case AllPosts(_): return Strings.allPosts } } //Strictly to be used to pass on to DiscussionNewPostViewController. var selectedTopic : DiscussionTopic? { switch self { case let Topic(topic): return topic.isSelectable ? topic : topic.firstSelectableChild() case Search(_): return nil case Following(_): return nil case AllPosts(_): return nil } } var noResultsMessage : String { switch self { case Topic(_): return Strings.noResultsFound case AllPosts: return Strings.noCourseResults case Following: return Strings.noFollowingResults case let .Search(string) : return Strings.emptyResultset(queryString: string) } } private var queryString: String? { switch self { case Topic(_): return nil case AllPosts: return nil case Following: return nil case let .Search(string) : return string } } } var environment: Environment! private var paginationController : PaginationController<DiscussionThread>? private lazy var tableView = UITableView(frame: CGRectZero, style: .Plain) private let viewSeparator = UIView() private let loadController = LoadStateViewController() private let refreshController = PullRefreshController() private let insetsController = ContentInsetsController() private let refineLabel = UILabel() private let headerButtonHolderView = UIView() private let headerView = UIView() private var searchBar : UISearchBar? private let filterButton = PressableCustomButton() private let sortButton = PressableCustomButton() private let newPostButton = UIButton(type: .System) private let courseID: String private var isDiscussionBlackedOut: Bool = true { didSet { updateNewPostButtonStyle() } } private var stream: Stream<(DiscussionInfo)>? private let contentView = UIView() private var context : Context? private let topicID: String? private var posts: [DiscussionThread] = [] private var selectedFilter: DiscussionPostsFilter = .AllPosts private var selectedOrderBy: DiscussionPostsSort = .RecentActivity var searchBarDelegate : DiscussionSearchBarDelegate? private var queryString : String? private var refineTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) } private var filterTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().primaryBaseColor()) } private var hasResults:Bool = false required init(environment: Environment, courseID: String, topicID: String?, context: Context?) { self.courseID = courseID self.environment = environment self.topicID = topicID self.context = context super.init(nibName: nil, bundle: nil) configureSearchBar() } convenience init(environment: Environment, courseID: String, topicID: String?) { self.init(environment: environment, courseID : courseID, topicID: topicID, context: nil) } convenience init(environment: Environment, courseID: String, topic: DiscussionTopic) { self.init(environment: environment, courseID : courseID, topicID: nil, context: .Topic(topic)) } convenience init(environment: Environment,courseID: String, queryString : String) { self.init(environment: environment, courseID : courseID, topicID: nil, context : .Search(queryString)) } ///Convenience initializer for All Posts and Followed posts convenience init(environment: Environment, courseID: String, following : Bool) { self.init(environment: environment, courseID : courseID, topicID: nil, context : following ? .Following : .AllPosts) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() addSubviews() setConstraints() setStyles() tableView.registerClass(PostTableViewCell.classForCoder(), forCellReuseIdentifier: PostTableViewCell.identifier) tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView.init() tableView.estimatedRowHeight = 150 tableView.rowHeight = UITableViewAutomaticDimension tableView.applyStandardSeparatorInsets() if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } filterButton.oex_addAction( {[weak self] _ in self?.showFilterPicker() }, forEvents: .TouchUpInside) sortButton.oex_addAction( {[weak self] _ in self?.showSortPicker() }, forEvents: .TouchUpInside) newPostButton.oex_addAction( {[weak self] _ in if let owner = self { owner.environment.router?.showDiscussionNewPostFromController(owner, courseID: owner.courseID, selectedTopic : owner.context?.selectedTopic) } }, forEvents: .TouchUpInside) loadController.setupInController(self, contentView: contentView) insetsController.setupInController(self, scrollView: tableView) refreshController.setupInScrollView(tableView) insetsController.addSource(refreshController) refreshController.delegate = self //set visibility of header view updateHeaderViewVisibility() loadContent() setAccessibility() } private func setAccessibility() { if let searchBar = searchBar { view.accessibilityElements = [searchBar, tableView] } else { view.accessibilityElements = [refineLabel, filterButton, sortButton, tableView, newPostButton] } updateAccessibility() } private func updateAccessibility() { filterButton.accessibilityLabel = Strings.Accessibility.discussionFilterBy(filterBy: titleForFilter(selectedFilter)) filterButton.accessibilityHint = Strings.accessibilityShowsDropdownHint sortButton.accessibilityLabel = Strings.Accessibility.discussionSortBy(sortBy: titleForSort(selectedOrderBy)) sortButton.accessibilityHint = Strings.accessibilityShowsDropdownHint } private func configureSearchBar() { guard let context = context where !context.allowsPosting else { return } searchBar = UISearchBar() searchBar?.applyStandardStyles(withPlaceholder: Strings.searchAllPosts) searchBar?.text = context.queryString searchBarDelegate = DiscussionSearchBarDelegate() { [weak self] text in self?.context = Context.Search(text) self?.loadController.state = .Initial self?.searchThreads(text) self?.searchBar?.delegate = self?.searchBarDelegate } } private func addSubviews() { view.addSubview(contentView) view.addSubview(headerView) if let searchBar = searchBar { view.addSubview(searchBar) } contentView.addSubview(tableView) headerView.addSubview(refineLabel) headerView.addSubview(headerButtonHolderView) headerButtonHolderView.addSubview(filterButton) headerButtonHolderView.addSubview(sortButton) view.addSubview(newPostButton) contentView.addSubview(viewSeparator) } private func setConstraints() { contentView.snp_remakeConstraints { (make) -> Void in if context?.allowsPosting ?? false { make.top.equalTo(view) } //Else the top is equal to searchBar.snp_bottom make.leading.equalTo(view) make.trailing.equalTo(view) //The bottom is equal to newPostButton.snp_top } headerView.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.top.equalTo(contentView) make.height.equalTo(context?.allowsPosting ?? false ? 40 : 0) } searchBar?.snp_remakeConstraints(closure: { (make) -> Void in make.top.equalTo(view) make.trailing.equalTo(contentView) make.leading.equalTo(contentView) make.bottom.equalTo(contentView.snp_top) }) refineLabel.snp_remakeConstraints { (make) -> Void in make.leadingMargin.equalTo(headerView).offset(StandardHorizontalMargin) make.centerY.equalTo(headerView) } refineLabel.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) headerButtonHolderView.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(refineLabel.snp_trailing) make.trailing.equalTo(headerView) make.bottom.equalTo(headerView) make.top.equalTo(headerView) } filterButton.snp_remakeConstraints{ (make) -> Void in make.leading.equalTo(headerButtonHolderView) make.trailing.equalTo(sortButton.snp_leading) make.centerY.equalTo(headerButtonHolderView) } sortButton.snp_remakeConstraints{ (make) -> Void in make.trailingMargin.equalTo(headerButtonHolderView) make.centerY.equalTo(headerButtonHolderView) make.width.equalTo(filterButton.snp_width) } newPostButton.snp_remakeConstraints{ (make) -> Void in make.leading.equalTo(view) make.trailing.equalTo(view) make.height.equalTo(context?.allowsPosting ?? false ? OEXStyles.sharedStyles().standardFooterHeight : 0) make.top.equalTo(contentView.snp_bottom) make.bottom.equalTo(view) } tableView.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(contentView) make.top.equalTo(viewSeparator.snp_bottom) make.trailing.equalTo(contentView) make.bottom.equalTo(newPostButton.snp_top) } viewSeparator.snp_remakeConstraints{ (make) -> Void in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.height.equalTo(OEXStyles.dividerSize()) make.top.equalTo(headerView.snp_bottom) } } private func setStyles() { view.backgroundColor = environment.styles.baseColor5() self.refineLabel.attributedText = self.refineTextStyle.attributedStringWithText(Strings.refine) var buttonTitle = NSAttributedString.joinInNaturalLayout( [Icon.Filter.attributedTextWithStyle(filterTextStyle.withSize(.XSmall)), filterTextStyle.attributedStringWithText(self.titleForFilter(self.selectedFilter))]) filterButton.setAttributedTitle(buttonTitle, forState: .Normal, animated : false) buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Sort.attributedTextWithStyle(filterTextStyle.withSize(.XSmall)), filterTextStyle.attributedStringWithText(Strings.recentActivity)]) sortButton.setAttributedTitle(buttonTitle, forState: .Normal, animated : false) updateNewPostButtonStyle() let style = OEXTextStyle(weight : .Normal, size: .Base, color: environment.styles.neutralWhite()) buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Create.attributedTextWithStyle(style.withSize(.XSmall)), style.attributedStringWithText(Strings.createANewPost)]) newPostButton.setAttributedTitle(buttonTitle, forState: .Normal) newPostButton.contentVerticalAlignment = .Center self.titleViewLabel.text = context?.navigationItemTitle viewSeparator.backgroundColor = environment.styles.neutralXLight() } private func updateNewPostButtonStyle() { newPostButton.backgroundColor = isDiscussionBlackedOut ? environment.styles.neutralBase() : environment.styles.primaryXDarkColor() newPostButton.enabled = !isDiscussionBlackedOut } func setIsDiscussionBlackedOut(value : Bool){ isDiscussionBlackedOut = value } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let selectedIndex = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(selectedIndex, animated: false) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .AllButUpsideDown } private func logScreenEvent() { guard let context = context else { return } switch context { case let .Topic(topic): self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenViewTopicThreads, courseId: self.courseID, value: topic.name, threadId: nil, topicId: topic.id, responseID: nil) case let .Search(query): self.environment.analytics.trackScreenWithName(OEXAnalyticsScreenSearchThreads, courseID: self.courseID, value: query, additionalInfo:["search_string":query]) case .Following: self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenViewTopicThreads, courseId: self.courseID, value: "posts_following", threadId: nil, topicId: "posts_following", responseID: nil) case .AllPosts: self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenViewTopicThreads, courseId: self.courseID, value: "all_posts", threadId: nil, topicId: "all_posts", responseID: nil) } } private func loadContent() { let apiRequest = DiscussionAPI.getDiscussionInfo(courseID) stream = environment.networkManager.streamForRequest(apiRequest) stream?.listen(self, success: { [weak self] (discussionInfo) in self?.isDiscussionBlackedOut = discussionInfo.isBlackedOut self?.loadPostContent() } ,failure: { [weak self] (error) in self?.loadController.state = LoadState.failed(error) }) } private func loadPostContent() { guard let context = context else { // context is only nil in case if topic is selected loadTopic() return } logScreenEvent() switch context { case let .Topic(topic): loadPostsForTopic(topic, filter: selectedFilter, orderBy: selectedOrderBy) case let .Search(query): searchThreads(query) case .Following: loadFollowedPostsForFilter(selectedFilter, orderBy: selectedOrderBy) case .AllPosts: loadPostsForTopic(nil, filter: selectedFilter, orderBy: selectedOrderBy) } } private func loadTopic() { guard let topicID = topicID else { loadController.state = LoadState.failed(NSError.oex_unknownError()) return } let apiRequest = DiscussionAPI.getTopicByID(courseID, topicID: topicID) self.environment.networkManager.taskForRequest(apiRequest) {[weak self] response in if let topics = response.data { //Sending signle topic id so always get a single topic self?.context = .Topic(topics[0]) self?.titleViewLabel.text = self?.context?.navigationItemTitle self?.setConstraints() self?.loadContent() } else { self?.loadController.state = LoadState.failed(response.error) } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() insetsController.updateInsets() } private func updateHeaderViewVisibility() { tableView.scrollEnabled = posts.count * 53 > TDScreenHeight - 180 ? true : false // if post has results then set hasResults yes hasResults = context?.allowsPosting ?? false && self.posts.count > 0 headerView.hidden = !hasResults } private func loadFollowedPostsForFilter(filter : DiscussionPostsFilter, orderBy: DiscussionPostsSort) { let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in return DiscussionAPI.getFollowedThreads(courseID: self.courseID, filter: filter, orderBy: orderBy, pageNumber: page) } paginationController = PaginationController (paginator: paginator, tableView: self.tableView) loadThreads() } private func searchThreads(query : String) { let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in return DiscussionAPI.searchThreads(courseID: self.courseID, searchText: query, pageNumber: page) } paginationController = PaginationController (paginator: paginator, tableView: self.tableView) loadThreads() } private func loadPostsForTopic(topic : DiscussionTopic?, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort) { var topicIDApiRepresentation : [String]? if let identifier = topic?.id { topicIDApiRepresentation = [identifier] } //Children's topic IDs if the topic is root node else if let discussionTopic = topic { topicIDApiRepresentation = discussionTopic.children.mapSkippingNils { $0.id } } let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in return DiscussionAPI.getThreads(courseID: self.courseID, topicIDs: topicIDApiRepresentation, filter: filter, orderBy: orderBy, pageNumber: page) } paginationController = PaginationController (paginator: paginator, tableView: self.tableView) loadThreads() } private func loadThreads() { paginationController?.stream.listen(self, success: { [weak self] threads in self?.posts.removeAll() self?.updatePostsFromThreads(threads) self?.refreshController.endRefreshing() }, failure: { [weak self] (error) -> Void in self?.loadController.state = LoadState.failed(error) }) paginationController?.loadMore() } private func updatePostsFromThreads(threads : [DiscussionThread]) { for thread in threads { self.posts.append(thread) } self.tableView.reloadData() let emptyState = LoadState.empty(icon : nil , message: errorMessage()) self.loadController.state = self.posts.isEmpty ? emptyState : .Loaded // set visibility of header view updateHeaderViewVisibility() UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } func titleForFilter(filter : DiscussionPostsFilter) -> String { switch filter { case .AllPosts: return Strings.allPosts case .Unread: return Strings.unread case .Unanswered: return Strings.unanswered } } func titleForSort(filter : DiscussionPostsSort) -> String { switch filter { case .RecentActivity: return Strings.recentActivity case .MostActivity: return Strings.mostActivity case .VoteCount: return Strings.mostVotes } } func isFilterApplied() -> Bool { switch self.selectedFilter { case .AllPosts: return false case .Unread: return true case .Unanswered: return true } } func errorMessage() -> String { guard let context = context else { return "" } if isFilterApplied() { return context.noResultsMessage + " " + Strings.removeFilter } else { return context.noResultsMessage } } func showFilterPicker() { let options = [.AllPosts, .Unread, .Unanswered].map { return (title : self.titleForFilter($0), value : $0) } let controller = UIAlertController.actionSheetWithItems(options, currentSelection : self.selectedFilter) {filter in self.selectedFilter = filter self.loadController.state = .Initial self.loadContent() let buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Filter.attributedTextWithStyle(self.filterTextStyle.withSize(.XSmall)), self.filterTextStyle.attributedStringWithText(self.titleForFilter(filter))]) self.filterButton.setAttributedTitle(buttonTitle, forState: .Normal, animated : false) self.updateAccessibility() } controller.addCancelAction() self.presentViewController(controller, animated: true, completion:nil) } func showSortPicker() { let options = [.RecentActivity, .MostActivity, .VoteCount].map { return (title : self.titleForSort($0), value : $0) } let controller = UIAlertController.actionSheetWithItems(options, currentSelection : self.selectedOrderBy) {sort in self.selectedOrderBy = sort self.loadController.state = .Initial self.loadContent() let buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Sort.attributedTextWithStyle(self.filterTextStyle.withSize(.XSmall)), self.filterTextStyle.attributedStringWithText(self.titleForSort(sort))]) self.sortButton.setAttributedTitle(buttonTitle, forState: .Normal, animated: false) self.updateAccessibility() } controller.addCancelAction() self.presentViewController(controller, animated: true, completion:nil) } private func updateSelectedPostAttributes(indexPath: NSIndexPath) { posts[indexPath.row].read = true posts[indexPath.row].unreadCommentCount = 0 tableView.reloadData() } //MARK :- DiscussionNewPostViewControllerDelegate method func newPostController(controller: DiscussionNewPostViewController, addedPost post: DiscussionThread) { loadContent() } // MARK - Pull Refresh func refreshControllerActivated(controller: PullRefreshController) { loadContent() } // MARK - Table View Delegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } var cellTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().primaryBaseColor()) } var unreadIconTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .Large, color: OEXStyles.sharedStyles().primaryBaseColor()) } var readIconTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralBase()) } func styledCellTextWithIcon(icon : Icon, text : String?) -> NSAttributedString? { let style = cellTextStyle.withSize(.Small) return text.map {text in return NSAttributedString.joinInNaturalLayout([icon.attributedTextWithStyle(style), style.attributedStringWithText(text)]) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { tableView.tableFooterView = UIView.init() let cell = tableView.dequeueReusableCellWithIdentifier(PostTableViewCell.identifier, forIndexPath: indexPath) as! PostTableViewCell cell.useThread(posts[indexPath.row], selectedOrderBy : selectedOrderBy) cell.applyStandardSeparatorInsets() return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { updateSelectedPostAttributes(indexPath) environment.router?.showDiscussionResponsesFromViewController(self, courseID : courseID, threadID: posts[indexPath.row].threadID, isDiscussionBlackedOut: isDiscussionBlackedOut) } } //We want to make sure that only non-root node topics are selectable public extension DiscussionTopic { var isSelectable : Bool { return self.depth != 0 || self.id != nil } func firstSelectableChild(forTopic topic : DiscussionTopic? = nil) -> DiscussionTopic? { let discussionTopic = topic ?? self if let matchedIndex = discussionTopic.children.firstIndexMatching({$0.isSelectable }) { return discussionTopic.children[matchedIndex] } if discussionTopic.children.count > 0 { return firstSelectableChild(forTopic : discussionTopic.children[0]) } return nil } } extension UITableView { //Might be worth adding a section argument in the future func isLastRow(indexPath indexPath : NSIndexPath) -> Bool { return indexPath.row == self.numberOfRowsInSection(indexPath.section) - 1 && indexPath.section == self.numberOfSections - 1 } } // Testing only extension PostsViewController { var t_loaded : Stream<()> { return self.stream!.map {_ in () } } var t_loaded_pagination : Stream<()> { return self.paginationController!.stream.map {_ in return } } }
apache-2.0
b14b624d71f7abfc2f09829856cfe21e
37.994374
215
0.646456
5.477084
false
false
false
false
5397chop/FriendlyChat-App
ios-starter/swift-starter/FriendlyChatSwift/AppDelegate.swift
1
2209
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Firebase import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var window: UIWindow? @available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { return self.application(application, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: "") } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) { if let error = error { print("Error \(error)") return } guard let authentication = user.authentication else { return } let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) Auth.auth().signIn(with: credential) { (user, error) in if let error = error { print("Error \(error)") return } } } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID GIDSignIn.sharedInstance().delegate = self return true } }
apache-2.0
5ebf0c48e03413e67d6b110b81d61008
35.213115
158
0.715256
4.802174
false
false
false
false
alblue/swift
stdlib/public/core/AnyHashable.swift
1
10481
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A value that has a custom representation in `AnyHashable`. /// /// `Self` should also conform to `Hashable`. public protocol _HasCustomAnyHashableRepresentation { /// Returns a custom representation of `self` as `AnyHashable`. /// If returns nil, the default representation is used. /// /// If your custom representation is a class instance, it /// needs to be boxed into `AnyHashable` using the static /// type that introduces the `Hashable` conformance. /// /// class Base : Hashable {} /// class Derived1 : Base {} /// class Derived2 : Base, _HasCustomAnyHashableRepresentation { /// func _toCustomAnyHashable() -> AnyHashable? { /// // `Derived2` is canonicalized to `Derived1`. /// let customRepresentation = Derived1() /// /// // Wrong: /// // return AnyHashable(customRepresentation) /// /// // Correct: /// return AnyHashable(customRepresentation as Base) /// } __consuming func _toCustomAnyHashable() -> AnyHashable? } @usableFromInline internal protocol _AnyHashableBox { var _canonicalBox: _AnyHashableBox { get } /// Determine whether values in the boxes are equivalent. /// /// - Precondition: `self` and `box` are in canonical form. /// - Returns: `nil` to indicate that the boxes store different types, so /// no comparison is possible. Otherwise, contains the result of `==`. func _isEqual(to box: _AnyHashableBox) -> Bool? var _hashValue: Int { get } func _hash(into hasher: inout Hasher) func _rawHashValue(_seed: Int) -> Int var _base: Any { get } func _unbox<T: Hashable>() -> T? func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool } extension _AnyHashableBox { var _canonicalBox: _AnyHashableBox { return self } } internal struct _ConcreteHashableBox<Base : Hashable> : _AnyHashableBox { internal var _baseHashable: Base internal init(_ base: Base) { self._baseHashable = base } internal func _unbox<T : Hashable>() -> T? { return (self as _AnyHashableBox as? _ConcreteHashableBox<T>)?._baseHashable } internal func _isEqual(to rhs: _AnyHashableBox) -> Bool? { if let rhs: Base = rhs._unbox() { return _baseHashable == rhs } return nil } internal var _hashValue: Int { return _baseHashable.hashValue } func _hash(into hasher: inout Hasher) { _baseHashable.hash(into: &hasher) } func _rawHashValue(_seed: Int) -> Int { return _baseHashable._rawHashValue(seed: _seed) } internal var _base: Any { return _baseHashable } internal func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { guard let value = _baseHashable as? T else { return false } result.initialize(to: value) return true } } /// A type-erased hashable value. /// /// The `AnyHashable` type forwards equality comparisons and hashing operations /// to an underlying hashable value, hiding its specific underlying type. /// /// You can store mixed-type keys in dictionaries and other collections that /// require `Hashable` conformance by wrapping mixed-type keys in /// `AnyHashable` instances: /// /// let descriptions: [AnyHashable: Any] = [ /// AnyHashable("😄"): "emoji", /// AnyHashable(42): "an Int", /// AnyHashable(Int8(43)): "an Int8", /// AnyHashable(Set(["a", "b"])): "a set of strings" /// ] /// print(descriptions[AnyHashable(42)]!) // prints "an Int" /// print(descriptions[AnyHashable(43)]) // prints "nil" /// print(descriptions[AnyHashable(Int8(43))]!) // prints "an Int8" /// print(descriptions[AnyHashable(Set(["a", "b"]))]!) // prints "a set of strings" @_fixed_layout // FIXME(sil-serialize-all) public struct AnyHashable { internal var _box: _AnyHashableBox internal init(_box box: _AnyHashableBox) { self._box = box } /// Creates a type-erased hashable value that wraps the given instance. /// /// The following example creates two type-erased hashable values: `x` wraps /// an `Int` with the value 42, while `y` wraps a `UInt8` with the same /// numeric value. Because the underlying types of `x` and `y` are /// different, the two variables do not compare as equal despite having /// equal underlying values. /// /// let x = AnyHashable(Int(42)) /// let y = AnyHashable(UInt8(42)) /// /// print(x == y) /// // Prints "false" because `Int` and `UInt8` are different types /// /// print(x == AnyHashable(Int(42))) /// // Prints "true" /// /// - Parameter base: A hashable value to wrap. public init<H : Hashable>(_ base: H) { if let custom = (base as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() { self = custom return } self.init(_box: _ConcreteHashableBox(false)) // Dummy value _makeAnyHashableUpcastingToHashableBaseType( base, storingResultInto: &self) } internal init<H : Hashable>(_usingDefaultRepresentationOf base: H) { self._box = _ConcreteHashableBox(base) } /// The value wrapped by this instance. /// /// The `base` property can be cast back to its original type using one of /// the casting operators (`as?`, `as!`, or `as`). /// /// let anyMessage = AnyHashable("Hello world!") /// if let unwrappedMessage = anyMessage.base as? String { /// print(unwrappedMessage) /// } /// // Prints "Hello world!" public var base: Any { return _box._base } /// Perform a downcast directly on the internal boxed representation. /// /// This avoids the intermediate re-boxing we would get if we just did /// a downcast on `base`. internal func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { // Attempt the downcast. if _box._downCastConditional(into: result) { return true } #if _runtime(_ObjC) // Bridge to Objective-C and then attempt the cast from there. // FIXME: This should also work without the Objective-C runtime. if let value = _bridgeAnythingToObjectiveC(_box._base) as? T { result.initialize(to: value) return true } #endif return false } } extension AnyHashable : Equatable { /// Returns a Boolean value indicating whether two type-erased hashable /// instances wrap the same type and value. /// /// Two instances of `AnyHashable` compare as equal if and only if the /// underlying types have the same conformance to the `Equatable` protocol /// and the underlying values compare as equal. /// /// The following example creates two type-erased hashable values: `x` wraps /// an `Int` with the value 42, while `y` wraps a `UInt8` with the same /// numeric value. Because the underlying types of `x` and `y` are /// different, the two variables do not compare as equal despite having /// equal underlying values. /// /// let x = AnyHashable(Int(42)) /// let y = AnyHashable(UInt8(42)) /// /// print(x == y) /// // Prints "false" because `Int` and `UInt8` are different types /// /// print(x == AnyHashable(Int(42))) /// // Prints "true" /// /// - Parameters: /// - lhs: A type-erased hashable value. /// - rhs: Another type-erased hashable value. public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool { return lhs._box._canonicalBox._isEqual(to: rhs._box._canonicalBox) ?? false } } extension AnyHashable : Hashable { /// The hash value. public var hashValue: Int { return _box._canonicalBox._hashValue } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. public func hash(into hasher: inout Hasher) { _box._canonicalBox._hash(into: &hasher) } public func _rawHashValue(seed: Int) -> Int { return _box._canonicalBox._rawHashValue(_seed: seed) } } extension AnyHashable : CustomStringConvertible { public var description: String { return String(describing: base) } } extension AnyHashable : CustomDebugStringConvertible { public var debugDescription: String { return "AnyHashable(" + String(reflecting: base) + ")" } } extension AnyHashable : CustomReflectable { public var customMirror: Mirror { return Mirror( self, children: ["value": base]) } } /// Returns a default (non-custom) representation of `self` /// as `AnyHashable`. /// /// Completely ignores the `_HasCustomAnyHashableRepresentation` /// conformance, if it exists. /// Called by AnyHashableSupport.cpp. @_silgen_name("_swift_makeAnyHashableUsingDefaultRepresentation") internal func _makeAnyHashableUsingDefaultRepresentation<H : Hashable>( of value: H, storingResultInto result: UnsafeMutablePointer<AnyHashable> ) { result.pointee = AnyHashable(_usingDefaultRepresentationOf: value) } /// Provided by AnyHashable.cpp. @usableFromInline // FIXME(sil-serialize-all) @_silgen_name("_swift_makeAnyHashableUpcastingToHashableBaseType") internal func _makeAnyHashableUpcastingToHashableBaseType<H : Hashable>( _ value: H, storingResultInto result: UnsafeMutablePointer<AnyHashable> ) @inlinable public // COMPILER_INTRINSIC func _convertToAnyHashable<H : Hashable>(_ value: H) -> AnyHashable { return AnyHashable(value) } /// Called by the casting machinery. @_silgen_name("_swift_convertToAnyHashableIndirect") internal func _convertToAnyHashableIndirect<H : Hashable>( _ value: H, _ target: UnsafeMutablePointer<AnyHashable> ) { target.initialize(to: AnyHashable(value)) } /// Called by the casting machinery. @_silgen_name("_swift_anyHashableDownCastConditionalIndirect") internal func _anyHashableDownCastConditionalIndirect<T>( _ value: UnsafePointer<AnyHashable>, _ target: UnsafeMutablePointer<T> ) -> Bool { return value.pointee._downCastConditional(into: target) }
apache-2.0
96307cfb7e695cfc9af2520d8bcb2f73
31.74375
87
0.66005
4.257619
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level70.swift
1
877
// // Level70.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level70: Level { let levelNumber = 70 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
0ecfb45871e1634557e84b358c8edd1b
24.794118
89
0.573546
2.649547
false
false
false
false
raginmari/RAGTextField
Example/RAGTextField/TextAlignmentViewController.swift
1
3265
import UIKit import RAGTextField final class TextAlignmentViewController: UIViewController, UITextFieldDelegate { @IBOutlet private weak var naturalAlignmentTextField: RAGTextField! { didSet { setUp(naturalAlignmentTextField) naturalAlignmentTextField.hintColor = .darkGray naturalAlignmentTextField.hintFont = UIFont.systemFont(ofSize: 11.0) naturalAlignmentTextField.hint = "Based on user interface direction" } } @IBOutlet private weak var differentAlignmentsTextField: RAGTextField! { didSet { setUp(differentAlignmentsTextField) differentAlignmentsTextField.hintColor = ColorPalette.meadow differentAlignmentsTextField.hintFont = UIFont.systemFont(ofSize: 11.0) } } @IBOutlet private weak var textAlignmentControl: UISegmentedControl! { didSet { textAlignmentControl.tintColor = ColorPalette.meadow } } private func setUp(_ textField: RAGTextField) { textField.delegate = self textField.clearButtonMode = .whileEditing textField.textColor = ColorPalette.midnight textField.tintColor = ColorPalette.midnight textField.textBackgroundView = makeTextBackgroundView() textField.textPadding = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0) textField.textPaddingMode = .textAndPlaceholderAndHint textField.scaledPlaceholderOffset = 2.0 textField.placeholderMode = .scalesWhenEditing textField.placeholderScaleWhenEditing = 0.8 textField.placeholderColor = ColorPalette.stone } private func makeTextBackgroundView() -> UIView { let view = UIView() view.layer.cornerRadius = 4.0 view.backgroundColor = ColorPalette.chalk return view } override func viewDidLoad() { title = "Text alignment" super.viewDidLoad() setTextAlignement(at: textAlignmentControl.selectedSegmentIndex) } @IBAction func onTextAlignmentChanged(_ control: UISegmentedControl) { setTextAlignement(at: control.selectedSegmentIndex) } private func setTextAlignement(at index: Int) { _ = differentAlignmentsTextField.resignFirstResponder() let alignment: NSTextAlignment = [.left, .center, .right][index] differentAlignmentsTextField.textAlignment = alignment differentAlignmentsTextField.hint = hint(for: alignment) } private func hint(for textAlignment: NSTextAlignment) -> String { switch textAlignment { case .left: return "Left alignment" case .center: return "Center alignment" case .right: return "Right alignment" case .natural: return "Natural alignment" case .justified: return "Justified alignment" @unknown default: return "Unknown alignment" } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
mit
bbd240aa51b068a57bb1b1f7c85d9c48
31.65
90
0.640429
5.678261
false
false
false
false
prettyxfan/iOSQueenExamples
NavigationBar/NavigationDemo/ViewController.swift
1
2703
// // ViewController.swift // NavigationDemo // // Created by Xie Fan on 16/1/31. // Copyright © 2016年 PrettyX.org. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidAppear(animated: Bool) { let nav = self.navigationController?.navigationBar //默认设置 nav?.barStyle = UIBarStyle.Black //自定义导航栏背景色 //nav?.barTintColor = UIColor.navigationBarColor() //透明度 // nav?.translucent = false //透明导航栏 // nav?.translucent = true // nav?.setBackgroundImage(UIImage(), // forBarMetrics: UIBarMetrics.Default) // nav?.shadowImage = UIImage() //导航栏按钮-文字 // let homeButton : UIBarButtonItem = UIBarButtonItem(title: "Left", style: UIBarButtonItemStyle.Plain, target: self, action: "") // // let logButton : UIBarButtonItem = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: "") // // self.navigationItem.leftBarButtonItem = homeButton // self.navigationItem.rightBarButtonItem = logButton //导航栏按钮-图标 let leftItem = UIButton(frame: CGRectMake(0, 0, 12, 20)) leftItem.setImage(UIImage(named: "icon-arrow"), forState: .Normal) leftItem .addTarget(self, action: "", forControlEvents: .TouchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftItem) let rightItem = UIButton(frame: CGRectMake(0, 0, 22, 16)) rightItem.setImage(UIImage(named: "icon-list"), forState: .Normal) rightItem .addTarget(self, action: "", forControlEvents: .TouchUpInside) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem) //导航栏标题 self.title = "iOSQueen" self.navigationItem.title = "iOSQueen" //导航栏标题字体和颜色 // nav?.titleTextAttributes = [ // NSForegroundColorAttributeName : UIColor.yellowColor(), // NSFontAttributeName: UIFont.systemFontOfSize(20) // ] //导航栏Logo // let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 28, height: 28)) // imageView.contentMode = .ScaleAspectFit // let image = UIImage(named: "swift") // imageView.image = image // navigationItem.titleView = imageView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
bb04dc6b5f609d5d74cd406b94e9a90f
32.205128
136
0.621236
4.769797
false
false
false
false
dukemedicine/Duke-Medicine-Mobile-Companion
Classes/Main/MCAppDelegate.swift
1
6536
// // MCAppDelegate.swift // Duke Medicine Mobile Companion // // Created by Ricky Bloomfield on 6/13/14. // Copyright (c) 2014 Duke Medicine // // 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UIAlertViewDelegate { var window: UIWindow? var keyWindow: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { // Override point for customization after application launch. // Set user agent to iPad so the links always work let userAgentDict = [ "UserAgent": "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25" ] NSUserDefaults.standardUserDefaults().registerDefaults(userAgentDict) // Change global tint color window!.tintColor = DUKE_BLUE() // Initialize default settings registerDefaultsFromSettingsBundle() return true } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // Handle the URL scheme (dukemedmc://) func application(application: UIApplication!, openURL url: NSURL!, sourceApplication: String!, annotation: AnyObject!) -> Bool { // Check to see if a modal view controller is already being shown (and which one). If it is, close it first, then open up the new one. var modalClassName = NSStringFromClass(window!.rootViewController?.presentedViewController?.classForCoder) if (modalClassName != nil) { // This will be 'nil' if there is not a showing modal view println("Modal view '\(modalClassName)' is now showing, so will close it.") window!.rootViewController?.presentedViewController?.dismissViewControllerAnimated(false, completion: {self.handleURL(url)}) } else { // Loading the URL for the first time handleURL(url) } return true } func handleURL(url: NSURL) { if url.host == "uptodate" { let urlString = "http:/\(url.path!)?\(url.query!)" let webViewController = MCModalWebViewController(address: urlString, tintColor: UPTODATE_GREEN()) webViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve window!.rootViewController?.presentViewController(webViewController, animated: true, completion: nil) } else if url.host == "bilitool" { let urlString = "http:/\(url.path!)?\(url.query!)" let webViewController = MCModalWebViewController(address: urlString, tintColor: BILITOOL_YELLOW()) webViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve window!.rootViewController?.presentViewController(webViewController, animated: true, completion: nil) } else if url.host == "maps" { let mapsBaseURL = USER_DEFAULTS().objectForKey("mapsBaseURL") as String let urlString = "\(mapsBaseURL)?\(url.query!)" // If default Safari Google Maps is selected, will open the website in this app (because this allows the user to conveniently get back to Haiku), otherwise will push the user to the other native app if mapsBaseURL == "https://maps.google.com/maps" { let webViewController = MCModalWebViewController(address: urlString, tintColor: DUKE_BLUE()) webViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve window!.rootViewController?.presentViewController(webViewController, animated: true, completion: nil) } else { if UIApplication.sharedApplication().canOpenURL(NSURL(string: urlString)!) { // Detaching thread for this because UIApplication was having fits being called at the same time as the app was starting NSThread.detachNewThreadSelector(Selector("openURLInBackground:"), toTarget: self, withObject: urlString) } else { // Display an alert if the users attempts to use an app that is not installed let title = titleForValueInPlistNamed("Root", "mapsBaseURL", mapsBaseURL) let alert = UIAlertView(title: "App Not Installed", message: "\(title) is not installed. Please change your default maps app selection and try again.", delegate: nil, cancelButtonTitle: "OK") alert.show() } } } else { let alert = UIAlertView(title: "Whoops!", message: "The app did not understand that URL.", delegate: nil, cancelButtonTitle: "OK") alert.show() } } // Detach thread for Maps URLs func openURLInBackground(urlString: String) { UIApplication.sharedApplication().openURL(NSURL(string: urlString)!) } }
mit
48fa0aa48b6d6a4d7b16f1aed6ee069c
50.880952
212
0.671512
5.199682
false
false
false
false
LampshadeSoftware/TheWordGame
TheWordGame/TheWordGame/WordGame.swift
1
11190
// // WordGame.swift // The Word Game // // Created by Daniel McCrystal on 11/28/16. // Copyright © 2016 Lampshade Software. All rights reserved. // import Foundation class WordGame: NSObject, NSCoding { private var players: [PlayerData] var turn: Int var lastWord, currentWord: String var usedWords: [String] var errorLog: String static var dictionary = WordGame.generateDictionary() static var common = WordGame.generateCommons() override init() { players = [PlayerData]() turn = 0 lastWord = "" currentWord = WordGame.generateStartWord() usedWords = [String]() errorLog = "" } init(lastWord: String, currentWord: String, usedWords: [String], players: [PlayerData], turn: Int) { self.players = players self.turn = turn self.lastWord = lastWord self.currentWord = currentWord self.usedWords = usedWords errorLog = "" } // Decode required convenience init?(coder aDecoder: NSCoder) { guard let _lastWord = aDecoder.decodeObject(forKey: "lastWord") as? String else { print("Unable to decode [lastWord]") return nil } guard let _currentWord = aDecoder.decodeObject(forKey: "currentWord") as? String else { print("Unable to decode [currentWord]") return nil } guard let _usedWords = aDecoder.decodeObject(forKey: "usedWords") as? [String] else { print("Unable to decode [usedWords]") return nil } guard let _playerData = aDecoder.decodeObject(forKey: "playerData") as? [PlayerData] else { print("Unable to decode [playerData]") return nil } let _turn = aDecoder.decodeInteger(forKey: "turn") self.init(lastWord: _lastWord, currentWord: _currentWord, usedWords: _usedWords, players: _playerData, turn: _turn) } // Encode func encode(with aCoder: NSCoder) { aCoder.encode(lastWord, forKey: "lastWord") aCoder.encode(currentWord, forKey: "currentWord") aCoder.encode(usedWords, forKey: "usedWords") aCoder.encode(players, forKey: "playerData") aCoder.encode(turn, forKey: "turn") } func addPlayer(_ name: String) { players.append(PlayerData(name: name)) } func playerForfeited() { players[turn].active = false if numActivePlayers() > 0 { cyclePlayers() } else { // TODO: Endgame calculations } } func getCurrentPlayer() -> PlayerData { return players[turn] } func cyclePlayers() { turn = (turn + 1) % players.count while !players[turn].active { turn = (turn + 1) % players.count } } func numActivePlayers() -> Int { var count = 0 for player in players { if player.active { count += 1 } } return count } static func generateStartWord() -> String { var potential = WordGame.common[Int(arc4random_uniform(UInt32(WordGame.common.count)))] while numPlays(on: potential, lessThan: 5) { potential = WordGame.common[Int(arc4random_uniform(UInt32(WordGame.common.count)))] } return potential } static func numPlays(on word: String, lessThan goal: Int) -> Bool { var count = 0 for test in WordGame.dictionary { if isValidPlayLite(test, on: word) { // print(test + " is a valid play on " + word) count += 1 if count == goal { return false } } } return true } static func numPlays(on word: String) -> Int { var count = 0 for test in WordGame.dictionary { if isValidPlayLite(test, on: word) { // print(test + " is a valid play on " + word) count += 1 } } return count } func numGamePlays(on word: String) -> Int { var count = 0 for test in WordGame.dictionary { if isValidPlay(test, on: word, last: lastWord) >= 0 { count+=1 } } return count } static func isValidPlayLite(_ play: String, on word: String) -> Bool { if play == word || !play.isAlpha { return false } return WordGame.isValidAdd(play, on: word) >= 0 || WordGame.isValidSub(play, on: word) >= 0 || WordGame.isValidReplace(play, on: word) >= 0 || WordGame.isValidRearrange(play, on: word) } /* Returns an error code based on the reason for invalidity -1: Word is invalid play on current word -2: Word is technically valid, but meaning did not change -3: Word is valid play, but not English -4: Word is valid play and English, but already used -5: Word is valid play and English and new, but it is a double play -6: Word is 'fjord', player can fuck off 0+: Word is valid, return play type and index 00-99: Addition 100-199: Subtraction 200-299: Replacement 300: Rearrange */ func isValidPlay(_ play: String, on word: String, last: String) -> Int { if !play.isAlpha { return -1 } var potential = -1 let validAdd = WordGame.isValidAdd(play, on: word) let validSub = WordGame.isValidSub(play, on: word) let validRep = WordGame.isValidReplace(play, on: word) if validAdd >= 0 { if WordGame.addedS(play, on: word) || WordGame.addedD(play, on: word) { return -2 } else { potential = validAdd } } else if validSub >= 0 { potential = 100 + validSub } else if validRep >= 0 { potential = 200 + validRep } else if WordGame.isValidRearrange(play, on: word) { potential = 300 } else { return -1 } if !WordGame.isEnglishWord(play) { return -3 } if play == word || alreadyUsed(play) { return -4 } if doublePlay(play, last: last) { return -5 } if play == "fjord" || play == "fiord" { return -6 } return potential } static func isValidAdd(_ play: String, on word: String) -> Int { if play.characters.count != word.characters.count + 1 { return -1 } var i = 0 while i < word.characters.count { if play[i] != word[i] { break } i += 1 } let changeAt = i while i+1 < play.characters.count { if play[i+1] != word[i] { return -1 } i += 1 } return changeAt } static func addedS(_ play: String, on word: String) -> Bool { return play.getLastChar() == "s" && word.getLastChar() != "s" } static func addedD(_ play: String, on word: String) -> Bool { return play.getLastChar() == "d" && word.getLastChar() == "e" } static func isValidSub(_ play: String, on word: String) -> Int { return isValidAdd(word, on: play) } static func isValidReplace(_ play: String, on word: String) -> Int { if play.characters.count != word.characters.count { return -1 } var i = 0 while i < play.characters.count { if play[i] != word[i] { i += 1 break } i += 1 } let changeAt = i - 1 while i < word.characters.count { if play[i] != word[i] { return -1 } i += 1 } return changeAt } static func isValidRearrange(_ play: String, on word: String) -> Bool { if play.characters.count != word.characters.count { return false } var letterCount = [Int](repeating: 0, count: 26) let playVals = play.unicodeScalars.filter{$0.isASCII}.map{$0.value} let wordVals = word.unicodeScalars.filter{$0.isASCII}.map{$0.value} for val in playVals { letterCount[Int(val) - 97] += 1 } for val in wordVals { letterCount[Int(val) - 97] -= 1 } for count in letterCount { if count != 0 { return false } } return true } static func isEnglishWord(_ play: String) -> Bool { let dict = WordGame.dictionary var hi = dict.count - 1 var lo = 0 var mid: Int while true { mid = (hi + lo) / 2 let guess = dict[mid] if guess == play { return true } else if lo > hi { return false } else { if guess < play { lo = mid + 1 } else { // guess > play hi = mid - 1 } } mid = (hi + lo) / 2 } } func alreadyUsed(_ play: String) -> Bool { return usedWords.contains(play) } func doublePlay(_ play: String, last word: String) -> Bool { return WordGame.isValidPlayLite(play, on: word) } func submitWord(_ word: String) -> Int { let wordLower = word.lowercased() let code = isValidPlay(wordLower, on: currentWord, last: lastWord) switch code { case -1: errorLog = "Invalid play! Try again" break case -2: errorLog = "You must change the meaning of the word!" break case -3: errorLog = "Not an English word! Try again" break case -4: errorLog = "\(word) has already been played! Try again" break case -5: errorLog = "Double play! Try again" break case -6: errorLog = "You think you're pretty smart, huh?" break default: usedWords.append(currentWord) lastWord = currentWord players[turn].addPlayedWord(word: currentWord) cyclePlayers() currentWord = wordLower errorLog = "" } return code } static func generateDictionary() -> [String] { guard let url = Bundle.main.path(forResource: "dictionary", ofType: "txt") else { print("Dictionary not found") return ["failed"] } do { let stringFromPath = try String(contentsOfFile: url, encoding: String.Encoding.utf8) return stringFromPath.components(separatedBy: "\r\n") } catch let error as NSError { print(error) return ["failed"] } } static func generateCommons() -> [String] { guard let url = Bundle.main.path(forResource: "common", ofType: "txt") else { print("Commons not found") return ["failed"] } do { let stringFromPath = try String(contentsOfFile: url, encoding: String.Encoding.utf8) return stringFromPath.components(separatedBy: "\n") } catch let error as NSError { print(error) return ["failed"] } } }
mit
718f58925f0d2d1647815e7ca85d2da7
28.917112
123
0.538297
4.083577
false
false
false
false
DJBCompany/DHNote
NoteBook/NoteBook/HZMeTableViewCell.swift
1
1321
// // HZMeTableViewCell.swift // NoteBook // // Created by DH on 16/4/29. // Copyright © 2016年 chris. All rights reserved. // import UIKit import SnapKit class HZMeTableViewCell: UITableViewCell { // 内容 lazy var contentLabel: UILabel = { let contentLabel = UILabel() contentLabel.textAlignment = .Center return contentLabel }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(contentLabel) contentLabel.snp_makeConstraints { (make) -> Void in make.center.equalTo(contentView) } } var contentString: String? { didSet{ contentLabel.text = contentString } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 快速创建一个cell class func meTableViewCell(tableView: UITableView) ->HZMeTableViewCell { let ID: String = "me" var cell: HZMeTableViewCell? = (tableView.dequeueReusableCellWithIdentifier(ID) as? HZMeTableViewCell) if cell == nil { cell = HZMeTableViewCell(style: .Default, reuseIdentifier: ID) } return cell! } }
mit
c07612078aea4f927a6e2a6b2247437d
26.125
110
0.630568
4.666667
false
false
false
false
PekanMmd/Pokemon-XD-Code
extensions/NSViewExtensions.swift
1
2707
// // NSViewExtensions.swift // GoD Tool // // Created by StarsMmd on 29/06/2016. // Copyright © 2016 StarsMmd. All rights reserved. // import Cocoa extension NSView { func setBackgroundColour(_ colour: XGColour) { setBackgroundColour(colour.NSColour) } func setBackgroundColour(_ colour: NSColor) { self.wantsLayer = true self.layer?.backgroundColor = colour.cgColor } func addBorder(colour: XGColour, width: CGFloat) { addBorder(colour: colour.NSColour, width: width) } func addBorder(colour: NSColor, width: CGFloat) { self.wantsLayer = true self.layer?.borderWidth = width self.layer?.borderColor = colour.cgColor } func removeBorder() { self.wantsLayer = true self.layer?.borderWidth = 0 } } // MARK: - Constraints - extension NSView { func pin(to view: NSView, padding: CGFloat = 0) { pinTop(to: view, padding: padding) pinBottom(to: view, padding: padding) pinLeading(to: view, padding: padding) pinTrailing(to: view, padding: padding) } func pinTop(to view: NSView, padding: CGFloat = 0) { topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true } func pinBottom(to view: NSView, padding: CGFloat = 0) { bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true } func pinLeading(to view: NSView, padding: CGFloat = 0) { leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true } func pinTrailing(to view: NSView, padding: CGFloat = 0) { trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true } func pinTopToBottom(of view: NSView, padding: CGFloat = 0) { topAnchor.constraint(equalTo: view.bottomAnchor, constant: padding).isActive = true } func pinLeadingToTrailing(of view: NSView, padding: CGFloat = 0) { leadingAnchor.constraint(equalTo: view.trailingAnchor, constant: padding).isActive = true } func pinCenterX(to view: NSView, padding: CGFloat = 0) { centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: padding).isActive = true } func pinCenterY(to view: NSView, padding: CGFloat = 0) { centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: padding).isActive = true } func pinHeight(as height: CGFloat) { heightAnchor.constraint(equalToConstant: height).isActive = true } func pinWidth(as width: CGFloat) { widthAnchor.constraint(equalToConstant: width).isActive = true } func constrainWidthEqual(to view: NSView) { widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1).isActive = true } func constrainHeightEqual(to view: NSView) { heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1).isActive = true } }
gpl-2.0
a5178310709b246aa025f53862675656
27.484211
93
0.736142
3.651822
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CloudHSMV2/CloudHSMV2_Error.swift
1
3178
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for CloudHSMV2 public struct CloudHSMV2ErrorType: AWSErrorType { enum Code: String { case cloudHsmAccessDeniedException = "CloudHsmAccessDeniedException" case cloudHsmInternalFailureException = "CloudHsmInternalFailureException" case cloudHsmInvalidRequestException = "CloudHsmInvalidRequestException" case cloudHsmResourceNotFoundException = "CloudHsmResourceNotFoundException" case cloudHsmServiceException = "CloudHsmServiceException" case cloudHsmTagException = "CloudHsmTagException" } private let error: Code public let context: AWSErrorContext? /// initialize CloudHSMV2 public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The request was rejected because the requester does not have permission to perform the requested operation. public static var cloudHsmAccessDeniedException: Self { .init(.cloudHsmAccessDeniedException) } /// The request was rejected because of an AWS CloudHSM internal failure. The request can be retried. public static var cloudHsmInternalFailureException: Self { .init(.cloudHsmInternalFailureException) } /// The request was rejected because it is not a valid request. public static var cloudHsmInvalidRequestException: Self { .init(.cloudHsmInvalidRequestException) } /// The request was rejected because it refers to a resource that cannot be found. public static var cloudHsmResourceNotFoundException: Self { .init(.cloudHsmResourceNotFoundException) } /// The request was rejected because an error occurred. public static var cloudHsmServiceException: Self { .init(.cloudHsmServiceException) } /// The request was rejected because of a tagging failure. Verify the tag conditions in all applicable policies, and then retry the request. public static var cloudHsmTagException: Self { .init(.cloudHsmTagException) } } extension CloudHSMV2ErrorType: Equatable { public static func == (lhs: CloudHSMV2ErrorType, rhs: CloudHSMV2ErrorType) -> Bool { lhs.error == rhs.error } } extension CloudHSMV2ErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
bfdc2d40637524a3a5b61fac645b9af7
43.138889
144
0.70107
4.874233
false
false
false
false
grpc/grpc-swift
Sources/GRPC/ClientCalls/ClientCall.swift
1
6849
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import NIOCore import NIOHPACK import NIOHTTP1 import NIOHTTP2 import SwiftProtobuf /// Base protocol for a client call to a gRPC service. public protocol ClientCall { /// The type of the request message for the call. associatedtype RequestPayload /// The type of the response message for the call. associatedtype ResponsePayload /// The event loop this call is running on. var eventLoop: EventLoop { get } /// The options used to make the RPC. var options: CallOptions { get } /// HTTP/2 stream that requests and responses are sent and received on. var subchannel: EventLoopFuture<Channel> { get } /// Initial response metadata. var initialMetadata: EventLoopFuture<HPACKHeaders> { get } /// Status of this call which may be populated by the server or client. /// /// The client may populate the status if, for example, it was not possible to connect to the service. /// /// Note: despite ``GRPCStatus`` conforming to `Error`, the value will be __always__ delivered as a __success__ /// result even if the status represents a __negative__ outcome. This future will __never__ be fulfilled /// with an error. var status: EventLoopFuture<GRPCStatus> { get } /// Trailing response metadata. var trailingMetadata: EventLoopFuture<HPACKHeaders> { get } /// Cancel the current call. /// /// Closes the HTTP/2 stream once it becomes available. Additional writes to the channel will be ignored. /// Any unfulfilled promises will be failed with a cancelled status (excepting ``status`` which will be /// succeeded, if not already succeeded). func cancel(promise: EventLoopPromise<Void>?) } extension ClientCall { func cancel() -> EventLoopFuture<Void> { let promise = self.eventLoop.makePromise(of: Void.self) self.cancel(promise: promise) return promise.futureResult } } /// A ``ClientCall`` with request streaming; i.e. client-streaming and bidirectional-streaming. public protocol StreamingRequestClientCall: ClientCall { /// Sends a message to the service. /// /// - Important: Callers must terminate the stream of messages by calling <doc:/documentation/GRPC/StreamingRequestClientCall/sendEnd()-7zuxl> /// or ``sendEnd(promise:)``. /// /// - Parameters: /// - message: The message to send. /// - compression: Whether compression should be used for this message. Ignored if compression /// was not enabled for the RPC. /// - Returns: A future which will be fullfilled when the message has been sent. func sendMessage(_ message: RequestPayload, compression: Compression) -> EventLoopFuture<Void> /// Sends a message to the service. /// /// - Important: Callers must terminate the stream of messages by calling ``sendEnd()-7bhdp`` or ``sendEnd(promise:)``. /// /// - Parameters: /// - message: The message to send. /// - compression: Whether compression should be used for this message. Ignored if compression /// was not enabled for the RPC. /// - promise: A promise to be fulfilled when the message has been sent. func sendMessage( _ message: RequestPayload, compression: Compression, promise: EventLoopPromise<Void>? ) /// Sends a sequence of messages to the service. /// /// - Important: Callers must terminate the stream of messages by calling <doc:/documentation/GRPC/StreamingRequestClientCall/sendEnd()-7bhdp> /// or ``sendEnd(promise:)``. /// /// - Parameters: /// - messages: The sequence of messages to send. /// - compression: Whether compression should be used for this message. Ignored if compression /// was not enabled for the RPC. func sendMessages<S: Sequence>(_ messages: S, compression: Compression) -> EventLoopFuture<Void> where S.Element == RequestPayload /// Sends a sequence of messages to the service. /// /// - Important: Callers must terminate the stream of messages by calling ``sendEnd()-7bhdp`` or ``sendEnd(promise:)``. /// /// - Parameters: /// - messages: The sequence of messages to send. /// - compression: Whether compression should be used for this message. Ignored if compression /// was not enabled for the RPC. /// - promise: A promise to be fulfilled when all messages have been sent successfully. func sendMessages<S: Sequence>( _ messages: S, compression: Compression, promise: EventLoopPromise<Void>? ) where S.Element == RequestPayload /// Terminates a stream of messages sent to the service. /// /// - Important: This should only ever be called once. /// - Returns: A future which will be fulfilled when the end has been sent. func sendEnd() -> EventLoopFuture<Void> /// Terminates a stream of messages sent to the service. /// /// - Important: This should only ever be called once. /// - Parameter promise: A promise to be fulfilled when the end has been sent. func sendEnd(promise: EventLoopPromise<Void>?) } extension StreamingRequestClientCall { public func sendMessage( _ message: RequestPayload, compression: Compression = .deferToCallDefault ) -> EventLoopFuture<Void> { let promise = self.eventLoop.makePromise(of: Void.self) self.sendMessage(message, compression: compression, promise: promise) return promise.futureResult } public func sendMessages<S: Sequence>( _ messages: S, compression: Compression = .deferToCallDefault ) -> EventLoopFuture<Void> where S.Element == RequestPayload { let promise = self.eventLoop.makePromise(of: Void.self) self.sendMessages(messages, compression: compression, promise: promise) return promise.futureResult } public func sendEnd() -> EventLoopFuture<Void> { let promise = self.eventLoop.makePromise(of: Void.self) self.sendEnd(promise: promise) return promise.futureResult } } /// A ``ClientCall`` with a unary response; i.e. unary and client-streaming. public protocol UnaryResponseClientCall: ClientCall { /// The response message returned from the service if the call is successful. This may be failed /// if the call encounters an error. /// /// Callers should rely on the `status` of the call for the canonical outcome. var response: EventLoopFuture<ResponsePayload> { get } }
apache-2.0
f39f6c8a5280ad472448a284822dfde5
38.589595
144
0.712805
4.413015
false
false
false
false
danger/danger-swift
Sources/DangerFixtures/DangerDSLResources/DangerDSLGitLab.swift
1
6002
public let DSLGitLabJSON = """ { "danger": { "git": { "modified_files": [ "static/source/swift/guides/getting_started.html.slim" ], "created_files": [], "deleted_files": [], "commits": [ { "sha": "621bc3348549e51c5bd6ea9f094913e9e4667c7b", "author": { "name": "Franco Meloni", "email": "[email protected]", "date": "2019-04-10T21:56:43.000Z" }, "committer": { "name": "Franco Meloni", "email": "[email protected]", "date": "2019-04-10T21:56:43.000Z" }, "message": "Update getting_started.html.slim", "parents": [], "url": "https://gitlab.com/danger-systems/danger.systems/commit/621bc3348549e51c5bd6ea9f094913e9e4667c7b", "tree": null } ] }, "gitlab": { "metadata": { "pullRequestID": "182", "repoSlug": "danger-systems/danger.systems" }, "mr": { "id": 27469633, "iid": 182, "project_id": 1620437, "title": "Update getting_started.html.slim", "description": "Updating it to avoid problems like https://github.com/danger/swift/issues/221", "state": "merged", "created_at": "2019-04-10T21:57:45.346Z", "updated_at": "2019-04-11T00:37:22.460Z", "merged_by": { "id": 377669, "name": "Orta", "username": "orta", "state": "active", "avatar_url": "https://secure.gravatar.com/avatar/f116cb3be23153ec08b94e8bd4dbcfeb?s=80&d=identicon", "web_url": "https://gitlab.com/orta" }, "merged_at": "2019-04-11T00:37:22.492Z", "closed_by": null, "closed_at": null, "target_branch": "master", "source_branch": "patch-2", "user_notes_count": 0, "upvotes": 0, "downvotes": 0, "assignee": { "id": 377669, "name": "Orta", "username": "orta", "state": "active", "avatar_url": "https://secure.gravatar.com/avatar/f116cb3be23153ec08b94e8bd4dbcfeb?s=80&d=identicon", "web_url": "https://gitlab.com/orta" }, "author": { "id": 3331525, "name": "Franco Meloni", "username": "f-meloni", "state": "active", "avatar_url": "https://secure.gravatar.com/avatar/3d90e967de2beab6d44cfadbb4976b87?s=80&d=identicon", "web_url": "https://gitlab.com/f-meloni" }, "assignees": [ { "id": 377669, "name": "Orta", "username": "orta", "state": "active", "avatar_url": "https://secure.gravatar.com/avatar/f116cb3be23153ec08b94e8bd4dbcfeb?s=80&d=identicon", "web_url": "https://gitlab.com/orta" } ], "source_project_id": 10132593, "target_project_id": 1620437, "labels": [], "work_in_progress": false, "milestone": { "id": 1, "iid": 2, "project_id": 1000, "title": "Test Milestone", "description": "Test Description", "state": "closed", "start_date": "2019-04-10", "created_at": "2019-04-10T21:57:45.346Z", "updated_at": "2019-04-10T21:57:45.346Z", "due_date": "2019-06-10", "web_url": "https://gitlab.com/milestone" }, "merge_when_pipeline_succeeds": false, "merge_status": "can_be_merged", "sha": "621bc3348549e51c5bd6ea9f094913e9e4667c7b", "merge_commit_sha": "377a24fb7a0f30364f089f7bca67752a8b61f477", "discussion_locked": null, "should_remove_source_branch": null, "force_remove_source_branch": true, "allow_collaboration": false, "allow_maintainer_to_push": false, "reference": "!182", "web_url": "https://gitlab.com/danger-systems/danger.systems/merge_requests/182", "time_stats": { "time_estimate": 0, "total_time_spent": 0, "human_time_estimate": null, "human_total_time_spent": null }, "squash": false, "subscribed": false, "changes_count": "1", "latest_build_started_at": "2019-04-11T00:20:22.492Z", "latest_build_finished_at": "2019-04-11T00:33:22.492Z", "first_deployed_to_production_at": "2019-04-11T00:30:22.492Z", "pipeline": { "id": 50, "sha": "621bc3348549e51c5bd6ea9f094913e9e4667c7b", "ref": "ef28580bb2a00d985bffe4a4ce3fe09fdb12283f", "status": "success", "web_url": "https://gitlab.com/danger-systems/danger.systems/pipeline/621bc3348549e51c5bd6ea9f094913e9e4667c7b" }, "head_pipeline": null, "diff_refs": { "base_sha": "ef28580bb2a00d985bffe4a4ce3fe09fdb12283f", "head_sha": "621bc3348549e51c5bd6ea9f094913e9e4667c7b", "start_sha": "ef28580bb2a00d985bffe4a4ce3fe09fdb12283f" }, "merge_error": null, "user": { "can_merge": false }, "approvals_before_merge": 1 }, "commits": [ { "id": "621bc3348549e51c5bd6ea9f094913e9e4667c7b", "short_id": "621bc334", "created_at": "2019-04-10T21:56:43.000Z", "parent_ids": [], "title": "Update getting_started.html.slim", "message": "Update getting_started.html.slim", "author_name": "Franco Meloni", "author_email": "[email protected]", "authored_date": "2019-04-10T21:56:43.000Z", "committer_name": "Franco Meloni", "committer_email": "[email protected]", "committed_date": "2019-04-10T21:56:43.000Z" } ] }, "settings": { "github": { "accessToken": "NO_T...", "additionalHeaders": {} }, "cliArgs": {} } } } """
mit
e09ca14e630459944aecd8dc2b6943c9
34.099415
121
0.525325
3.062245
false
false
false
false
lucaslimapoa/NewsAPISwift
Source/Decoders/NewsAPIDecoder.swift
1
2057
// // NewsSourceDecoder.swift // NewsAPISwift // // Created by Lucas Lima on 22/06/18. // Copyright © 2018 Lucas Lima. All rights reserved. // import Foundation class NewsAPIDecoder { lazy private var iso8601: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return dateFormatter }() lazy private var iso8601mm: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ" return dateFormatter }() func decode<T: Decodable>(data: Data) throws -> [T] { let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = makeDateDecodingStategy() let response = try? jsonDecoder.decode(NewsResponse.self, from: data) if let code = response?.code, let message = response?.message { throw NewsAPIError.serviceError(code: code, message: message) } if let sources = response?.sources as? [T] { return sources } if let articles = response?.articles as? [T] { return articles } throw NewsAPIError.unableToParse } } private extension NewsAPIDecoder { func makeDateDecodingStategy() -> JSONDecoder.DateDecodingStrategy { return .custom ({ [weak self] decoder in let container = try decoder.singleValueContainer() let dateStr = try container.decode(String.self) if let date = self?.iso8601.date(from: dateStr) { return date } if let date = self?.iso8601mm.date(from: dateStr) { return date } throw NewsAPIError.unableToParse }) } } private struct NewsResponse: Decodable { let status: String let code: String? let message: String? let sources: [NewsSource]? let articles: [NewsArticle]? }
mit
c79ee446bd0b7d198f579cc74c1abfb9
27.164384
77
0.588035
4.715596
false
false
false
false
mozilla-mobile/firefox-ios
Account/FxAPushMessageHandler.swift
2
9544
// 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 Shared import SyncTelemetry import Account import os.log import MozillaAppServices let PendingAccountDisconnectedKey = "PendingAccountDisconnect" /// This class provides handles push messages from FxA. /// For reference, the [message schema][0] and [Android implementation][1] are both useful resources. /// [0]: https://github.com/mozilla/fxa-auth-server/blob/master/docs/pushpayloads.schema.json#L26 /// [1]: https://dxr.mozilla.org/mozilla-central/source/mobile/android/services/src/main/java/org/mozilla/gecko/fxa/FxAccountPushHandler.java /// The main entry points are `handle` methods, to accept the raw APNS `userInfo` and then to process the resulting JSON. class FxAPushMessageHandler { let profile: Profile init(with profile: Profile) { self.profile = profile } } extension FxAPushMessageHandler { /// Accepts the raw Push message from Autopush. /// This method then decrypts it according to the content-encoding (aes128gcm or aesgcm) /// and then effects changes on the logged in account. @discardableResult func handle(userInfo: [AnyHashable: Any]) -> PushMessageResult { let keychain = MZKeychainWrapper.sharedClientAppContainerKeychain guard let pushReg = keychain.object(forKey: KeychainKey.fxaPushRegistration) as? PushRegistration else { return deferMaybe(PushMessageError.accountError) } let subscription = pushReg.defaultSubscription guard let encoding = userInfo["con"] as? String, // content-encoding let payload = userInfo["body"] as? String else { return deferMaybe(PushMessageError.messageIncomplete("missing con or body")) } // ver == endpointURL path, chid == channel id, aps == alert text and content_available. let plaintext: String? if let cryptoKeyHeader = userInfo["cryptokey"] as? String, // crypto-key let encryptionHeader = userInfo["enc"] as? String, // encryption encoding == "aesgcm" { plaintext = subscription.aesgcm(payload: payload, encryptionHeader: encryptionHeader, cryptoHeader: cryptoKeyHeader) } else if encoding == "aes128gcm" { plaintext = subscription.aes128gcm(payload: payload) } else { plaintext = nil } guard let string = plaintext else { // The app will detect this missing, and re-register. see AppDelegate+PushNotifications.swift. keychain.removeObject(forKey: KeychainKey.apnsToken, withAccessibility: MZKeychainItemAccessibility.afterFirstUnlock) return deferMaybe(PushMessageError.notDecrypted) } // return handle(plaintext: string) let deferred = PushMessageResult() RustFirefoxAccounts.reconfig(prefs: profile.prefs).uponQueue(.main) { accountManager in accountManager.deviceConstellation()?.processRawIncomingAccountEvent(pushPayload: string) { result in guard case .success(let events) = result, let firstEvent = events.first else { let err: PushMessageError if case .failure(let error) = result { err = PushMessageError.messageIncomplete(error.localizedDescription) } else { err = PushMessageError.messageIncomplete("empty message") } deferred.fill(Maybe(failure: err)) return } if events.count > 1 { // Log to the console for debugging release builds os_log( "%{public}@", log: OSLog(subsystem: "org.mozilla.firefox", category: "firefoxnotificationservice"), type: OSLogType.debug, "Multiple events arrived, only handling the first event.") } switch firstEvent { case .commandReceived(let deviceCommand): switch deviceCommand { case .tabReceived(_, let tabData): let title = tabData.entries.last?.title ?? "" let url = tabData.entries.last?.url ?? "" let message = PushMessage.commandReceived(tab: ["title": title, "url": url]) if let json = try? accountManager.gatherTelemetry() { let events = FxATelemetry.parseTelemetry(fromJSONString: json) events.forEach { $0.record(intoPrefs: self.profile.prefs) } } deferred.fill(Maybe(success: message)) } case .deviceConnected(let deviceName): let message = PushMessage.deviceConnected(deviceName) deferred.fill(Maybe(success: message)) case let .deviceDisconnected(deviceId, isLocalDevice): if isLocalDevice { // We can't disconnect the device from the account until we have access to the application, so we'll handle this properly in the AppDelegate (as this code in an extension), // by calling the FxALoginHelper.applicationDidDisonnect(application). self.profile.prefs.setBool(true, forKey: PendingAccountDisconnectedKey) let message = PushMessage.thisDeviceDisconnected deferred.fill(Maybe(success: message)) return } guard let profile = self.profile as? BrowserProfile else { // We can't look up a name in testing, so this is the same as not knowing about it. let message = PushMessage.deviceDisconnected(nil) deferred.fill(Maybe(success: message)) return } profile.remoteClientsAndTabs.getClient(fxaDeviceId: deviceId).uponQueue(.main) { result in guard let device = result.successValue else { return } let message = PushMessage.deviceDisconnected(device?.name) if let id = device?.guid { profile.remoteClientsAndTabs.deleteClient(guid: id).uponQueue(.main) { _ in print("deleted client") } } deferred.fill(Maybe(success: message)) } default: // There are other events, but we ignore them at this level. do {} } } } return deferred } } enum PushMessageType: String { case commandReceived = "fxaccounts:command_received" case deviceConnected = "fxaccounts:device_connected" case deviceDisconnected = "fxaccounts:device_disconnected" case profileUpdated = "fxaccounts:profile_updated" case passwordChanged = "fxaccounts:password_changed" case passwordReset = "fxaccounts:password_reset" } enum PushMessage: Equatable { case commandReceived(tab: [String: String]) case deviceConnected(String) case deviceDisconnected(String?) case profileUpdated case passwordChanged case passwordReset // This is returned when we detect that it is us that has been disconnected. case thisDeviceDisconnected var messageType: PushMessageType { switch self { case .commandReceived: return .commandReceived case .deviceConnected: return .deviceConnected case .deviceDisconnected: return .deviceDisconnected case .thisDeviceDisconnected: return .deviceDisconnected case .profileUpdated: return .profileUpdated case .passwordChanged: return .passwordChanged case .passwordReset: return .passwordReset } } public static func == (lhs: PushMessage, rhs: PushMessage) -> Bool { guard lhs.messageType == rhs.messageType else { return false } switch (lhs, rhs) { case (.commandReceived(let lIndex), .commandReceived(let rIndex)): return lIndex == rIndex case (.deviceConnected(let lName), .deviceConnected(let rName)): return lName == rName default: return true } } } typealias PushMessageResult = Deferred<Maybe<PushMessage>> enum PushMessageError: MaybeErrorType { case notDecrypted case messageIncomplete(String) case unimplemented(PushMessageType) case timeout case accountError case noProfile case subscriptionOutOfDate public var description: String { switch self { case .notDecrypted: return "notDecrypted" case .messageIncomplete(let message): return "messageIncomplete=\(message)" case .unimplemented(let what): return "unimplemented=\(what)" case .timeout: return "timeout" case .accountError: return "accountError" case .noProfile: return "noProfile" case .subscriptionOutOfDate: return "subscriptionOutOfDate" } } }
mpl-2.0
4a78c5fe0823c141f67df7d50756f01a
43.390698
196
0.606035
5.389046
false
false
false
false
mozilla-mobile/firefox-ios
Shared/AsyncReducer.swift
2
4345
// 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 public let DefaultDispatchQueue = DispatchQueue.global(qos: DispatchQoS.default.qosClass) public func asyncReducer<T, U>(_ initialValue: T, combine: @escaping (T, U) -> Deferred<Maybe<T>>) -> AsyncReducer<T, U> { return AsyncReducer(initialValue: initialValue, combine: combine) } /** * A appendable, async `reduce`. * * The reducer starts empty. New items need to be `append`ed. * * The constructor takes an `initialValue`, a `dispatch_queue_t`, and a `combine` function. * * The reduced value can be accessed via the `reducer.terminal` `Deferred<Maybe<T>>`, which is * run once all items have been combined. * * The terminal will never be filled if no items have been appended. * * Once the terminal has been filled, no more items can be appended, and `append` methods will error. */ open class AsyncReducer<T, U> { // T is the accumulator. U is the input value. The returned T is the new accumulated value. public typealias Combine = (T, U) -> Deferred<Maybe<T>> fileprivate let lock = NSRecursiveLock() private let dispatchQueue: DispatchQueue private let combine: Combine private let initialValueDeferred: Deferred<Maybe<T>> public let terminal: Deferred<Maybe<T>> = Deferred() private var queuedItems: [U] = [] private var isStarted: Bool = false /** * Has this task queue finished? * Once the task queue has finished, it cannot have more tasks appended. */ open var isFilled: Bool { lock.lock() defer { lock.unlock() } return terminal.isFilled } public convenience init(initialValue: T, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) { self.init(initialValue: deferMaybe(initialValue), queue: queue, combine: combine) } public init(initialValue: Deferred<Maybe<T>>, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) { self.dispatchQueue = queue self.combine = combine self.initialValueDeferred = initialValue } // This is always protected by a lock, so we don't need to // take another one. fileprivate func ensureStarted() { if self.isStarted { return } func queueNext(_ deferredValue: Deferred<Maybe<T>>) { deferredValue.uponQueue(dispatchQueue, block: continueMaybe) } func nextItem() -> U? { // Because popFirst is only available on array slices. // removeFirst is fine for range-replaceable collections. return queuedItems.isEmpty ? nil : queuedItems.removeFirst() } func continueMaybe(_ res: Maybe<T>) { lock.lock() defer { lock.unlock() } if res.isFailure { self.queuedItems.removeAll() self.terminal.fill(Maybe(failure: res.failureValue!)) return } let accumulator = res.successValue! guard let item = nextItem() else { self.terminal.fill(Maybe(success: accumulator)) return } let combineItem = deferDispatchAsync(dispatchQueue) { return self.combine(accumulator, item) } queueNext(combineItem) } queueNext(self.initialValueDeferred) self.isStarted = true } /** * Append one or more tasks onto the end of the queue. * * @throws AlreadyFilled if the queue has finished already. */ open func append(_ items: U...) throws -> Deferred<Maybe<T>> { return try append(items) } /** * Append a list of tasks onto the end of the queue. * * @throws AlreadyFilled if the queue has already finished. */ open func append(_ items: [U]) throws -> Deferred<Maybe<T>> { lock.lock() defer { lock.unlock() } if terminal.isFilled { throw ReducerError.alreadyFilled } queuedItems.append(contentsOf: items) ensureStarted() return terminal } } enum ReducerError: Error { case alreadyFilled }
mpl-2.0
943144e31a850772ede24fae29cbfa57
30.485507
124
0.63153
4.564076
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/CommonSource/InfoScreen/Views/InfoScreenRateCell/InfoScreenRateCell.swift
1
985
// // InfoScreenRateCell.swift // AviasalesSDKTemplate // // Created by Dim on 18.07.17. // Copyright © 2017 Go Travel Un Limited. All rights reserved. // import UIKit protocol InfoScreenRateCellProtocol { var name: String? { get } } class InfoScreenRateCell: UITableViewCell { @IBOutlet weak var actionButton: UIButton! var action: ((UIButton) -> Void)? override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none setupUI() } private func setupUI() { actionButton.layer.cornerRadius = 4 actionButton.layer.borderWidth = JRPixel() actionButton.layer.borderColor = JRColorScheme.mainColor().cgColor } func setup(cellModel: InfoScreenRateCellProtocol, action: @escaping (UIButton) -> Void) { actionButton.setTitle(cellModel.name, for: .normal) self.action = action } @IBAction func actionButtonTapped(_ sender: UIButton) { action?(sender) } }
mit
d8ea3ae39f67c5be11d84cec9b1184c2
23.6
93
0.66565
4.315789
false
false
false
false
zacharyclaysmith/SwiftBindingUI
SwiftBindingUI/BindableTextView.swift
1
1587
// // BindableTextView.swift // ARWorld // // Created by Zachary Smith on 12/22/14. // Copyright (c) 2014 Scal.io. All rights reserved. // import Foundation import UIKit import SwiftBinding public class BindableTextView:SwiftTextView, PTextBindable, PHiddenBindable{ private var _textBinding:BindableValue<String>? public var textBinding:BindableValue<String>?{ get{ return _textBinding } set(newValue){ _textBinding?.removeListener(self) _textBinding = newValue _textBinding?.addListener(self, alertNow:true, listener:valueChanged) } } deinit{ _textBinding?.removeListener(self) _hiddenBinding?.removeListener(self) } internal override func textChanged(){ if(_textBinding?.value != self.text){ _textBinding?.value = self.text } super.textChanged() } private func valueChanged(newValue:String){ self.text = newValue } private var _hiddenBinding:BindableValue<Bool>? public var hiddenBinding:BindableValue<Bool>?{ get{ return _hiddenBinding } set(newValue){ _hiddenBinding?.removeListener(self) _hiddenBinding = newValue _hiddenBinding?.addListener(self, alertNow: true, listener:hiddenBinding_valueChanged) } } private func hiddenBinding_valueChanged(newValue:Bool){ self.hidden = newValue } }
mit
84377cc76e15d0dcadc5980a90453072
23.060606
98
0.593573
4.853211
false
false
false
false
jeroendesloovere/examples-swift
Swift-Playgrounds/Protocols.playground/section-1.swift
1
10125
// Protocols import Foundation /* protocol SomeProtocol { // protocol definition goes here } struct SomeStructure: FirstProtocol, AnotherProtocol { // structure definition goes here } // If a class has a superclass, list the superclass name before any protocols it adopts, followed by a comma: class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { // class definition goes here } */ // Property Requirements // Property requirements are always declared as variable properties, prefixed with the var keyword. protocol SomeProtocol { var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get } } // Always prefix type property requirements with the class keyword when you define them in a protocol. This is true even though type property requirements are prefixed with the static keyword when implemented by a structure or enumeration: protocol AnotherProtocol { class var someTypeProperty: Int { get set } } protocol FullyNamed { var fullName: String { get } } struct Person: FullyNamed { var fullName: String } let john = Person(fullName: "John AppleSeed") class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } var fullName: String { return ((prefix != nil ? prefix! + " " : "") + name) } } var ncc1701 = Starship(name: "Enterprise", prefix: "USS") // Method Requirements /* protocol SomeProtocol { class func someTypeMethod() } */ protocol RandomNumberGenerator { func random() -> Double } // linear congruential generator: class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) % m) return lastRandom / m } } let generator = LinearCongruentialGenerator() println("Here's a random number: \(generator.random())") println("And another one: \(generator.random())") // Mutating Method Requirements protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case Off, On mutating func toggle() { switch self { case Off: self = On case On: self = Off } } } var lightSwitch = OnOffSwitch.Off lightSwitch.toggle() lightSwitch // Protocols as Types // Protocols do not actually implement any functionality themselves. Nonetheless, any protocol you create will become a fully-fledged type for use class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...5 { println("Random dice roll is \(d6.roll())") } // Delegation protocol DiceGame { var dice: Dice { get } func play() } protocol DiceGameDelegate { func gameDidStart(game: DiceGame) func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) func gameDidEnd(game: DiceGame) } class SnakesAndLadders: DiceGame { let finalSquare = 25 let dice = Dice(sides: 6, generator:LinearCongruentialGenerator()) var square = 0 var board: [Int] init() { board = [Int](count: finalSquare + 1, repeatedValue: 0) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02; board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 } var delegate: DiceGameDelegate? func play() { square = 0 delegate?.gameDidStart(self) gameLoop: while square != finalSquare { let diceRoll = dice.roll() delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) switch square + diceRoll { case finalSquare: break gameLoop case let newSquare where newSquare > finalSquare: continue gameLoop default: square += diceRoll square += board[square] } } delegate?.gameDidEnd(self) } } class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(game: DiceGame) { numberOfTurns = 0 if game is SnakesAndLadders { println("Started a new game of Snakes and Ladders") } println("The game is using a \(game.dice.sides)-sided dice") } func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { ++numberOfTurns println("Rolled a \(diceRoll)") } func gameDidEnd(game: DiceGame) { println("The game lasted for \(numberOfTurns) turns") } } let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play() // Adding Protocol Conformance with an Extension protocol TextRepresentable { func asText() -> String } extension Dice: TextRepresentable { func asText() -> String { return "A \(sides)-sided dice" } } let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator()) println(d12.asText()) d6.asText() extension SnakesAndLadders: TextRepresentable { func asText() -> String { return "A game of Snakes and Ladders with \(finalSquare) squares" } } println(game.asText()) // Declaring Protocol Adoption with an Extension // If a type already conforms to all of the requirements of a protocol, but has not yet stated that it adopts that protocol, you can make it adopt the protocol with an empty extension: struct Hamster { var name: String func asText() -> String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster println(somethingTextRepresentable.asText()) // Collections of Protocol Types let things: [TextRepresentable] = [game, d12, simonTheHamster] for thing in things { println(thing.asText()) } // Note that the thing constant is of type TextRepresentable. It is not of type Dice, or DiceGame, or Hamster, even if the actual instance behind the scenes is of one of those types. // Protocol Inheritance /* protocol InheritingProtocol: SomeProtocol, Another Protocol { // protocol definition goes here } */ protocol PrettyTextRepresentable: TextRepresentable { func asPrettyText() -> String } // PrettyTextRepresentable must satisfy all of the requirements enforced by TextRepresentable, plus the additional requirements enforced by PrettyTextRepresentable. extension SnakesAndLadders: PrettyTextRepresentable { func asPrettyText() -> String { var output = asText() + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } println(game.asPrettyText()) // Protocol Composition protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person2: Named, Aged { var name: String var age: Int } func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person2(name:"Malcom", age: 21) wishHappyBirthday(birthdayPerson) // Checking for Protocol Conformance @objc protocol HasArea { var area: Double { get } } // You can check for protocol conformance only if your protocol is marked with the @objc attribute class Circle: HasArea { let pi = 3.1415927 var radius: Double var area: Double { return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } let objects: [AnyObject] = [ Circle(radius: 2.0), Country(area: 243_610), Animal(legs: 4) ] for object in objects { if let objectWithArea = object as? HasArea { println("Area is \(objectWithArea.area)") } else { println("Something that doesn't have an area") } } // Note that the underlying objects are not changed by the casting process. They continue to be a Circle, a Country and an Animal. However, at the point that they are stored in the objectWithArea constant, they are only known to be of type HasArea, and so only their area property can be accessed. // Optional Protocol Requirements // Optional property requirements, and optional method requirements that return a value, will always return an optional value of the appropriate type when they are accessed or called, to reflect the fact that the optional requirement may not have been implemented. @objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } @objc class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement? { count += amount } } } class ThreeSource: CounterDataSource { let fixedIncrement = 3 } var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() println(counter.count) } class TowardsZeroSource: CounterDataSource { func incrementForCount(count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() println(counter.count) }
mit
7dfd1e1c68c6969ad85b04ee383889c2
26.422764
298
0.664493
4.315139
false
false
false
false
damouse/Silvery
Silvery/Silvery.swift
1
6988
// // Model.swift // Dynamic // // Created by Bradley Hilton on 7/20/15. // Copyright © 2015 Skyvive. All rights reserved. // /* The following is taken from the Swift ABI found here: https://github.com/apple/swift/blob/master/docs/ABI.rst#type-metadata Structs and tuples currently share the same layout algorithm, noted as the "Universal" layout algorithm in the compiler implementation. The algorithm is as follows: Start with a size of 0 and an alignment of 1. Iterate through the fields, in element order for tuples, or in var declaration order for structs. For each field: Update size by rounding up to the alignment of the field, that is, increasing it to the least value greater or equal to size and evenly divisible by the alignment of the field. Assign the offset of the field to the current value of size. Update size by adding the size of the field. Update alignment to the max of alignment and the alignment of the field. The final size and alignment are the size and alignment of the aggregate. The stride of the type is the final size rounded up to alignment. */ /** Enables dynamic, KVC-style behavior for native Swift classes and structures. Keep in mind the following caveats: - All properties must conform to the Property protocol - Properties may not be implicitly unwrapped optionals */ // Magic numbers for offsetting into objects let WORD_SIZE = 8 let DEFAULT_CLASS_OFFSET = 2 public protocol Silvery : Property {} extension Silvery { public subscript (key: String) -> Property? { get { do { return try valueForKey(key) } catch { return nil } } set { do { try setValue(newValue, forKey: key) } catch let e { print("Failed to set \(key). Error: \(e)") } } } // Return all property names as a list of strings public func keys() -> [String] { return mirroredChildren().filter({ $0.label != nil }).map { $0.label! } } // Return all properties as a list of mirrored elements. These are aliased as (String, Any) func mirroredChildren() -> [Mirror.Child] { // Collect supeclass fields. Relative ordering is important! var ancestor: Mirror? = Mirror(reflecting: self) var properties: [Mirror.Child] = [] while ancestor != nil { var kids = ancestor!.children.map {$0} kids.appendContentsOf(properties) properties = kids ancestor = ancestor?.superclassMirror() } return properties } public mutating func setValue(value: Property?, forKey key: String) throws { var offset = WORD_SIZE * DEFAULT_CLASS_OFFSET let properties = mirroredChildren() // Look for the target property for child in properties { guard let property = child.value.dynamicType as? Property.Type else { throw Error.TypeDoesNotConformToProperty(type: child.value.dynamicType) } // *Always* have to check up on the alignment of the current field before using the offset variable let align = property.align() // The offset of this field must be a multiple of its alignment, but offset is incremented // based on the size of the previous field-- pad as needed if offset % align != 0 { offset += align - ((offset + align) % align) } // If found then grab a pointer to the child's memory and attempt to write in the new value if child.label == key { let pointer = pointerAdvancedBy(offset) if let optionalPropertyType = child.value.dynamicType as? OptionalProperty.Type, let propertyType = optionalPropertyType.propertyType() { if var optionalValue = value { try x(optionalValue, isY: propertyType) optionalValue.codeOptionalInto(pointer) } else if let nilValue = child.value.dynamicType as? OptionalProperty.Type { nilValue.codeNilInto(pointer) } } else if var sureValue = value { try x(sureValue, isY: child.value.dynamicType) sureValue.codeInto(pointer) } } else { offset += property.size() } } } public func valueForKey(key: String) throws -> Property? { for child in mirroredChildren() { // There used to be a nil check here. Failure case likely still exists-- if the thing being coded for is not // a property, is an optional, and is currently nil then child.value.dynamicType can fail... I think? if child.label == key { if let property = child.value as? OptionalProperty { return property.property() } else if let property = child.value as? Property { return property } else { throw Error.TypeDoesNotConformToProperty(type: child.value.dynamicType) } } } return nil } public func typeForKey(key: String) throws -> Any.Type? { for child in mirroredChildren() { if child.label == key { if let optionalPropertyType = child.value.dynamicType as? OptionalProperty.Type, let propertyType = optionalPropertyType.propertyType() { return propertyType } else if let property = child.value as? Property { return property.dynamicType } else { // Should we just return the type here if its not a property? throw Error.TypeDoesNotConformToProperty(type: child.value.dynamicType) } } } return nil } mutating func pointerAdvancedBy(offset: Int) -> UnsafePointer<Void> { if let object = self as? AnyObject { return UnsafePointer(bitPattern: unsafeAddressOf(object).hashValue).advancedBy(offset) } else { return withUnsafePointer(&self) { UnsafePointer($0).advancedBy(offset) } } } } func x(x: Any, isY y: Any.Type) throws { if x.dynamicType == y { } else if let x = x as? AnyObject, let y = y as? AnyClass where x.isKindOfClass(y) { } else { throw Error.CannotSetTypeAsType(x: x.dynamicType, y: y) } } // We must create two seperate kinds of object here // i think this belongs in DSON, not here. This is a library for access based on keys, not conversion to and from DSON // But what about "all keys," ignore functions, etc? public class SilveryClass: Silvery { public required init() { } }
mit
762c670db7dab2d41f18ef4911caa61f
36.767568
177
0.600401
4.8826
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/weibo/Classes/Home/View/Cell/HomeStatusFooterView.swift
1
2718
// // HomeStatusFooterView.swift // weibo // // Created by mada on 15/10/12. // Copyright © 2015年 MD. All rights reserved. // import UIKit class HomeStatusFooterView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { // 添加子控件 addSubview(retweetView) addSubview(commentView) addSubview(unlikeView) addSubview(lineView1) addSubview(lineView2) // 布局子控件 retweetView.snp_makeConstraints { (make) -> Void in make.left.equalTo(self) make.top.equalTo(self) make.height.equalTo(self) } commentView.snp_makeConstraints { (make) -> Void in make.left.equalTo(retweetView.snp_right) make.top.equalTo(self) make.height.equalTo(retweetView) make.width.equalTo(retweetView) } unlikeView.snp_makeConstraints { (make) -> Void in make.left.equalTo(commentView.snp_right) make.right.equalTo(self) make.top.equalTo(self) make.height.equalTo(retweetView) make.width.equalTo(retweetView) } lineView1.snp_makeConstraints { (make) -> Void in make.height.equalTo(44 * 0.6) make.width.equalTo(0.5) make.centerX.equalTo(retweetView.snp_right) make.centerY.equalTo(self) } lineView2.snp_makeConstraints { (make) -> Void in make.height.equalTo(44 * 0.6) make.width.equalTo(0.5) make.centerX.equalTo(commentView.snp_right) make.centerY.equalTo(self) } } // MARK: - 懒加载 // 转发 private lazy var retweetView: UIButton = { let btn = UIButton(title: "转发", imageName: "timeline_icon_retweet") return btn }() // 评论 private lazy var commentView: UIButton = { let btn = UIButton(title: "评论", imageName: "timeline_icon_comment") return btn }() // 赞 private lazy var unlikeView: UIButton = { let btn = UIButton(title: "赞", imageName: "timeline_icon_unlike") return btn }() // 分割线 private lazy var lineView1: UIView = self.createLineView() private lazy var lineView2: UIView = self.createLineView() private func createLineView() -> UIView { let line = UIView() line.backgroundColor = UIColor.darkGrayColor() return line } }
mit
9f327bb05f81e5264a1403e376c70919
27.031579
75
0.572662
4.253994
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Renderers/LineChartRenderer.swift
6
26908
// // LineChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class LineChartRenderer: LineRadarChartRenderer { public weak var dataProvider: LineChartDataProvider? public init(dataProvider: LineChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let lineData = dataProvider?.lineData else { return } for i in 0 ..< lineData.dataSetCount { guard let set = lineData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is ILineChartDataSet) { fatalError("Datasets for LineChartRenderer must conform to ILineChartDataSet") } drawDataSet(context: context, dataSet: set as! ILineChartDataSet) } } } public func drawDataSet(context context: CGContext, dataSet: ILineChartDataSet) { let entryCount = dataSet.entryCount if (entryCount < 1) { return } CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.lineWidth) if (dataSet.lineDashLengths != nil) { CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths!, dataSet.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // if drawing cubic lines is enabled if (dataSet.isDrawCubicEnabled) { drawCubic(context: context, dataSet: dataSet) } else { // draw normal (straight) lines drawLinear(context: context, dataSet: dataSet) } CGContextRestoreGState(context) } public func drawCubic(context context: CGContext, dataSet: ILineChartDataSet) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency), animator = animator else { return } let entryCount = dataSet.entryCount guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { return } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff - 1, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) let phaseX = animator.phaseX let phaseY = animator.phaseY // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGPathCreateMutable() var valueToPixelMatrix = trans.valueToPixelMatrix let size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) if (size - minx >= 2) { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 var prevPrev: ChartDataEntry! = dataSet.entryForIndex(minx) var prev: ChartDataEntry! = prevPrev var cur: ChartDataEntry! = prev var next: ChartDataEntry! = dataSet.entryForIndex(minx + 1) if cur == nil || next == nil { return } // let the spline start CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) for j in minx + 1 ..< min(size, entryCount - 1) { prevPrev = prev prev = cur cur = next next = dataSet.entryForIndex(j + 1) if next == nil { break } prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } if (size > entryCount - 1) { prevPrev = dataSet.entryForIndex(entryCount - (entryCount >= 3 ? 3 : 2)) prev = dataSet.entryForIndex(entryCount - 2) cur = dataSet.entryForIndex(entryCount - 1) next = cur if prevPrev == nil || prev == nil || cur == nil { return } prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity // the last cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } } CGContextSaveGState(context) if (dataSet.isDrawFilledEnabled) { // Copy this path because we make changes to it let fillPath = CGPathCreateMutableCopy(cubicPath) drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, from: minx, to: size) } CGContextBeginPath(context) CGContextAddPath(context, cubicPath) CGContextSetStrokeColorWithColor(context, drawingColor.CGColor) CGContextStrokePath(context) CGContextRestoreGState(context) } public func drawCubicFill(context context: CGContext, dataSet: ILineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, from: Int, to: Int) { guard let dataProvider = dataProvider else { return } if to - from <= 1 { return } let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0 // Take the from/to xIndex from the entries themselves, // so missing entries won't screw up the filling. // What we need to draw is line from points of the xIndexes - not arbitrary entry indexes! let xTo = dataSet.entryForIndex(to - 1)?.xIndex ?? 0 let xFrom = dataSet.entryForIndex(from)?.xIndex ?? 0 var pt1 = CGPoint(x: CGFloat(xTo), y: fillMin) var pt2 = CGPoint(x: CGFloat(xFrom), y: fillMin) pt1 = CGPointApplyAffineTransform(pt1, matrix) pt2 = CGPointApplyAffineTransform(pt2, matrix) CGPathAddLineToPoint(spline, nil, pt1.x, pt1.y) CGPathAddLineToPoint(spline, nil, pt2.x, pt2.y) CGPathCloseSubpath(spline) if dataSet.fill != nil { drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawLinear(context context: CGContext, dataSet: ILineChartDataSet) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency), animator = animator else { return } let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let isDrawSteppedEnabled = dataSet.isDrawSteppedEnabled let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2 let phaseX = animator.phaseX let phaseY = animator.phaseY guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { return } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) CGContextSaveGState(context) CGContextSetLineCap(context, dataSet.lineCapType) // more than 1 color if (dataSet.colors.count > 1) { if (_lineSegments.count != pointsPerEntryPair) { _lineSegments = [CGPoint](count: pointsPerEntryPair, repeatedValue: CGPoint()) } let count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) for j in minx ..< count { if (count > 1 && j == count - 1) { // Last point, we have already drawn a line to this point break } var e: ChartDataEntry! = dataSet.entryForIndex(j) if e == nil { continue } _lineSegments[0].x = CGFloat(e.xIndex) _lineSegments[0].y = CGFloat(e.value) * phaseY if (j + 1 < count) { e = dataSet.entryForIndex(j + 1) if e == nil { break } if isDrawSteppedEnabled { _lineSegments[1] = CGPoint(x: CGFloat(e.xIndex), y: _lineSegments[0].y) _lineSegments[2] = _lineSegments[1] _lineSegments[3] = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY) } else { _lineSegments[1] = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY) } } else { _lineSegments[1] = _lineSegments[0] } for i in 0..<_lineSegments.count { _lineSegments[i] = CGPointApplyAffineTransform(_lineSegments[i], valueToPixelMatrix) } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))) { continue } // get the color that is set for this line-segment CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextStrokeLineSegments(context, _lineSegments, pointsPerEntryPair) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! if (_lineSegments.count != max((entryCount - 1) * pointsPerEntryPair, pointsPerEntryPair)) { _lineSegments = [CGPoint](count: max((entryCount - 1) * pointsPerEntryPair, pointsPerEntryPair), repeatedValue: CGPoint()) } e1 = dataSet.entryForIndex(minx) if e1 != nil { let count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) var j = 0 for x in (count > 1 ? minx + 1 : minx) ..< count { e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1)) e2 = dataSet.entryForIndex(x) if e1 == nil || e2 == nil { continue } _lineSegments[j] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY ), valueToPixelMatrix) j += 1 if isDrawSteppedEnabled { _lineSegments[j] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e2.xIndex), y: CGFloat(e1.value) * phaseY ), valueToPixelMatrix) j += 1 _lineSegments[j] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e2.xIndex), y: CGFloat(e1.value) * phaseY ), valueToPixelMatrix) j += 1 } _lineSegments[j] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY ), valueToPixelMatrix) j += 1 } let size = max((count - minx - 1) * pointsPerEntryPair, pointsPerEntryPair) CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextStrokeLineSegments(context, _lineSegments, size) } } CGContextRestoreGState(context) // if drawing filled is enabled if (dataSet.isDrawFilledEnabled && entryCount > 0) { drawLinearFill(context: context, dataSet: dataSet, minx: minx, maxx: maxx, trans: trans) } } public func drawLinearFill(context context: CGContext, dataSet: ILineChartDataSet, minx: Int, maxx: Int, trans: ChartTransformer) { guard let dataProvider = dataProvider else { return } let filled = generateFilledPath( dataSet: dataSet, fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0, from: minx, to: maxx, matrix: trans.valueToPixelMatrix) if dataSet.fill != nil { drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } /// Generates the path that is used for filled drawing. private func generateFilledPath(dataSet dataSet: ILineChartDataSet, fillMin: CGFloat, from: Int, to: Int, matrix: CGAffineTransform) -> CGPath { let phaseX = animator?.phaseX ?? 1.0 let phaseY = animator?.phaseY ?? 1.0 let isDrawSteppedEnabled = dataSet.isDrawSteppedEnabled var matrix = matrix var e: ChartDataEntry! let filled = CGPathCreateMutable() e = dataSet.entryForIndex(from) if e != nil { CGPathMoveToPoint(filled, &matrix, CGFloat(e.xIndex), fillMin) CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // create a new path for x in (from + 1).stride(to: Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))), by: 1) { guard let e = dataSet.entryForIndex(x) else { continue } if isDrawSteppedEnabled { guard let ePrev = dataSet.entryForIndex(x-1) else { continue } CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(ePrev.value) * phaseY) } CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // close up e = dataSet.entryForIndex(max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, dataSet.entryCount - 1), 0)) if e != nil { CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), fillMin) } CGPathCloseSubpath(filled) return filled } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, lineData = dataProvider.lineData, animator = animator else { return } if (CGFloat(lineData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX) { var dataSets = lineData.dataSets let phaseX = animator.phaseX let phaseY = animator.phaseY var pt = CGPoint() for i in 0 ..< dataSets.count { guard let dataSet = dataSets[i] as? ILineChartDataSet else { continue } if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if (!dataSet.isDrawCirclesEnabled) { valOffset = valOffset / 2 } let entryCount = dataSet.entryCount guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { continue } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) for j in minx ..< Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } ChartUtils.drawText(context: context, text: formatter.stringFromNumber(e.value)!, point: CGPoint( x: pt.x, y: pt.y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]) } } } } public override func drawExtras(context context: CGContext) { drawCircles(context: context) } private func drawCircles(context context: CGContext) { guard let dataProvider = dataProvider, lineData = dataProvider.lineData, animator = animator else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY let dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() CGContextSaveGState(context) for i in 0 ..< dataSets.count { guard let dataSet = lineData.getDataSetByIndex(i) as? ILineChartDataSet else { continue } if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0 { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleDiameter = circleRadius let circleHoleRadius = circleHoleDiameter / 2.0 let isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { continue } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) for j in minx ..< Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter CGContextFillEllipseInRect(context, rect) if (isDrawCircleHoleEnabled) { CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor) rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter CGContextFillEllipseInRect(context, rect) } } } CGContextRestoreGState(context) } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let lineData = dataProvider?.lineData, chartXMax = dataProvider?.chartXMax, animator = animator else { return } CGContextSaveGState(context) for i in 0 ..< indices.count { guard let set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as? ILineChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX) { continue } let yValue = set.yValForXIndex(xIndex) if (yValue.isNaN) { continue } let y = CGFloat(yValue) * animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider?.getTransformer(set.axisDependency) trans?.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
apache-2.0
fe55a60f4cd22603973f777292004907
37.223011
155
0.518768
5.712951
false
false
false
false
quran/quran-ios
Sources/QuranTextKit/Search/Searchers/TranslationSearcher.swift
1
1906
// // TranslationSearcher.swift // // // Created by Mohamed Afifi on 2021-11-17. // import Foundation import PromiseKit import QuranKit import TranslationService struct TranslationSearcher: AsyncSearcher { let localTranslationRetriever: LocalTranslationsRetriever let versePersistenceBuilder: (Translation, Quran) -> SearchableTextPersistence let quran: Quran private func getLocalTranslations() -> Promise<[Translation]> { localTranslationRetriever .getLocalTranslations() .map { $0.filter(\.isDownloaded) } } func autocomplete(term: String) -> Promise<[SearchAutocompletion]> { getLocalTranslations() .map { translations -> [SearchAutocompletion] in for translation in translations { let persistence = self.versePersistenceBuilder(translation, quran) let persistenceSearcher = PersistenceSearcher(versePersistence: persistence, source: .translation(translation)) let results = try persistenceSearcher.autocomplete(term: term) if !results.isEmpty { return results } } return [] } } func search(for term: String) -> Promise<[SearchResults]> { getLocalTranslations() .map { translations -> [SearchResults] in let results = try translations.map { translation -> [SearchResults] in let persistence = self.versePersistenceBuilder(translation, quran) let persistenceSearcher = PersistenceSearcher(versePersistence: persistence, source: .translation(translation)) let results = try persistenceSearcher.search(for: term) return results } return results.flatMap { $0 } } } }
apache-2.0
70e7a8b8807ae828a2f3ab973b51d999
36.372549
131
0.613851
5.706587
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Home/FirefoxHomeViewController.swift
1
41227
/* 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 Shared import UIKit import Storage import SDWebImage import XCGLogger import SyncTelemetry import SnapKit private let log = Logger.browserLogger // MARK: - Lifecycle struct FirefoxHomeUX { static let rowSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 30 : 20 static let highlightCellHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 250 : 200 static let sectionInsetsForSizeClass = UXSizeClasses(compact: 0, regular: 101, other: 20) static let numberOfItemsPerRowForSizeClassIpad = UXSizeClasses(compact: 3, regular: 4, other: 2) static let SectionInsetsForIpad: CGFloat = 101 static let SectionInsetsForIphone: CGFloat = 20 static let MinimumInsets: CGFloat = 20 static let TopSitesInsets: CGFloat = 6 static let LibraryShortcutsHeight: CGFloat = 100 static let LibraryShortcutsMaxWidth: CGFloat = 350 } /* Size classes are the way Apple requires us to specify our UI. Split view on iPad can make a landscape app appear with the demensions of an iPhone app Use UXSizeClasses to specify things like offsets/itemsizes with respect to size classes For a primer on size classes https://useyourloaf.com/blog/size-classes/ */ struct UXSizeClasses { var compact: CGFloat var regular: CGFloat var unspecified: CGFloat init(compact: CGFloat, regular: CGFloat, other: CGFloat) { self.compact = compact self.regular = regular self.unspecified = other } subscript(sizeClass: UIUserInterfaceSizeClass) -> CGFloat { switch sizeClass { case .compact: return self.compact case .regular: return self.regular case .unspecified: return self.unspecified @unknown default: fatalError() } } } protocol HomePanelDelegate: AnyObject { func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) func homePanel(didSelectURL url: URL, visitType: VisitType, isGoogleTopSite: Bool) func homePanelDidRequestToOpenLibrary(panel: LibraryPanelType) } protocol HomePanel: Themeable { var homePanelDelegate: HomePanelDelegate? { get set } } enum HomePanelType: Int { case topSites = 0 var internalUrl: URL { let aboutUrl: URL! = URL(string: "\(InternalURL.baseUrl)/\(AboutHomeHandler.path)") return URL(string: "#panel=\(self.rawValue)", relativeTo: aboutUrl)! } } protocol HomePanelContextMenu { func getSiteDetails(for indexPath: IndexPath) -> Site? func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? func presentContextMenu(for indexPath: IndexPath) func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) } extension HomePanelContextMenu { func presentContextMenu(for indexPath: IndexPath) { guard let site = getSiteDetails(for: indexPath) else { return } presentContextMenu(for: site, with: indexPath, completionHandler: { return self.contextMenu(for: site, with: indexPath) }) } func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? { guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil } let contextMenu = PhotonActionSheet(site: site, actions: actions) contextMenu.modalPresentationStyle = .overFullScreen contextMenu.modalTransitionStyle = .crossDissolve let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() return contextMenu } func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [PhotonActionSheetItem]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { _, _ in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { _, _ in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } return [openInNewTabAction, openInNewPrivateTabAction] } } class FirefoxHomeViewController: UICollectionViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? fileprivate let profile: Profile fileprivate let pocketAPI = Pocket() fileprivate let flowLayout = UICollectionViewFlowLayout() fileprivate lazy var topSitesManager: ASHorizontalScrollCellManager = { let manager = ASHorizontalScrollCellManager() return manager }() fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() // Not used for displaying. Only used for calculating layout. lazy var topSiteCell: ASHorizontalScrollCell = { let customCell = ASHorizontalScrollCell(frame: CGRect(width: self.view.frame.size.width, height: 0)) customCell.delegate = self.topSitesManager return customCell }() lazy var defaultBrowserCard: DefaultBrowserCard = { let card = DefaultBrowserCard() card.backgroundColor = UIColor.theme.homePanel.topSitesBackground return card }() var pocketStories: [PocketStory] = [] init(profile: Profile) { self.profile = profile super.init(collectionViewLayout: flowLayout) self.collectionView?.delegate = self self.collectionView?.dataSource = self collectionView?.addGestureRecognizer(longPressRecognizer) let refreshEvents: [Notification.Name] = [.DynamicFontChanged, .HomePanelPrefsChanged] refreshEvents.forEach { NotificationCenter.default.addObserver(self, selector: #selector(reload), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() Section.allValues.forEach { self.collectionView?.register(Section($0.rawValue).cellType, forCellWithReuseIdentifier: Section($0.rawValue).cellIdentifier) } self.collectionView?.register(ASHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header") self.collectionView?.register(ASFooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "Footer") collectionView?.keyboardDismissMode = .onDrag if #available(iOS 14.0, *), !UserDefaults.standard.bool(forKey: "DidDismissDefaultBrowserCard") { self.view.addSubview(defaultBrowserCard) defaultBrowserCard.snp.makeConstraints { make in make.top.equalToSuperview() make.bottom.equalTo(collectionView.snp.top) make.width.lessThanOrEqualTo(508) make.centerX.equalTo(self.view) } collectionView.snp.makeConstraints { make in make.top.equalTo(defaultBrowserCard.snp.bottom) make.bottom.left.right.equalToSuperview() } defaultBrowserCard.dismissClosure = { self.dismissDefaultBrowserCard() } } self.view.backgroundColor = UIColor.theme.homePanel.topSitesBackground self.profile.panelDataObservers.activityStream.delegate = self applyTheme() } public func dismissDefaultBrowserCard() { self.defaultBrowserCard.removeFromSuperview() self.collectionView.snp.makeConstraints { make in make.top.equalToSuperview() make.bottom.left.right.equalToSuperview() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadAll() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: {context in //The AS context menu does not behave correctly. Dismiss it when rotating. if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } self.collectionViewLayout.invalidateLayout() self.collectionView?.reloadData() }, completion: { _ in // Workaround: label positions are not correct without additional reload self.collectionView?.reloadData() }) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.topSitesManager.currentTraits = self.traitCollection } @objc func reload(notification: Notification) { reloadAll() } func applyTheme() { defaultBrowserCard.applyTheme() collectionView?.backgroundColor = UIColor.theme.homePanel.topSitesBackground self.view.backgroundColor = UIColor.theme.homePanel.topSitesBackground topSiteCell.collectionView.reloadData() if let collectionView = self.collectionView, collectionView.numberOfSections > 0, collectionView.numberOfItems(inSection: 0) > 0 { collectionView.reloadData() } } func scrollToTop(animated: Bool = false) { collectionView?.setContentOffset(.zero, animated: animated) } } // MARK: - Section management extension FirefoxHomeViewController { enum Section: Int { case topSites case libraryShortcuts case pocket static let count = 3 static let allValues = [topSites, libraryShortcuts, pocket] var title: String? { switch self { case .pocket: return Strings.ASPocketTitle case .topSites: return Strings.ASTopSitesTitle case .libraryShortcuts: return Strings.AppMenuLibraryTitleString } } var headerHeight: CGSize { return CGSize(width: 50, height: 40) } var headerImage: UIImage? { switch self { case .pocket: return UIImage.templateImageNamed("menu-pocket") case .topSites: return UIImage.templateImageNamed("menu-panel-TopSites") case .libraryShortcuts: // We want to validate that the Nimbus experiments library is working, from the UI // all the way back to the data science backend. We're not testing the user's preference // or response, we're end-to-end testing the experiments platform. // So here, we're running multiple identical branches with the same treatment, and if the // user isn't targeted, then we get still get the same treatment. return Experiments.shared.withExperiment(featureId: .nimbusValidation) { branch -> UIImage? in switch branch { case .some(ExperimentBranch.a1): return UIImage.templateImageNamed("menu-library") case .some(ExperimentBranch.a2): return UIImage.templateImageNamed("menu-library") default: return UIImage.templateImageNamed("menu-library") } } } } var footerHeight: CGSize { switch self { case .pocket: return .zero case .topSites, .libraryShortcuts: return CGSize(width: 50, height: 5) } } func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat { switch self { case .pocket: return FirefoxHomeUX.highlightCellHeight case .topSites: return 0 //calculated dynamically case .libraryShortcuts: return FirefoxHomeUX.LibraryShortcutsHeight } } /* There are edge cases to handle when calculating section insets - An iPhone 7+ is considered regular width when in landscape - An iPad in 66% split view is still considered regular width */ func sectionInsets(_ traits: UITraitCollection, frameWidth: CGFloat) -> CGFloat { var currentTraits = traits if (traits.horizontalSizeClass == .regular && UIScreen.main.bounds.size.width != frameWidth) || UIDevice.current.userInterfaceIdiom == .phone { currentTraits = UITraitCollection(horizontalSizeClass: .compact) } var insets = FirefoxHomeUX.sectionInsetsForSizeClass[currentTraits.horizontalSizeClass] switch self { case .pocket, .libraryShortcuts: let window = UIApplication.shared.keyWindow let safeAreaInsets = window?.safeAreaInsets.left ?? 0 insets += FirefoxHomeUX.MinimumInsets + safeAreaInsets return insets case .topSites: insets += FirefoxHomeUX.TopSitesInsets return insets } } func numberOfItemsForRow(_ traits: UITraitCollection) -> CGFloat { switch self { case .pocket: var numItems: CGFloat = FirefoxHomeUX.numberOfItemsPerRowForSizeClassIpad[traits.horizontalSizeClass] if UIApplication.shared.statusBarOrientation.isPortrait { numItems = numItems - 1 } if traits.horizontalSizeClass == .compact && UIApplication.shared.statusBarOrientation.isLandscape { numItems = numItems - 1 } return numItems case .topSites, .libraryShortcuts: return 1 } } func cellSize(for traits: UITraitCollection, frameWidth: CGFloat) -> CGSize { let height = cellHeight(traits, width: frameWidth) let inset = sectionInsets(traits, frameWidth: frameWidth) * 2 switch self { case .pocket: let numItems = numberOfItemsForRow(traits) return CGSize(width: floor(((frameWidth - inset) - (FirefoxHomeUX.MinimumInsets * (numItems - 1))) / numItems), height: height) case .topSites, .libraryShortcuts: return CGSize(width: frameWidth - inset, height: height) } } var headerView: UIView? { let view = ASHeaderView() view.title = title return view } var cellIdentifier: String { switch self { case .topSites: return "TopSiteCell" case .pocket: return "PocketCell" case .libraryShortcuts: return "LibraryShortcutsCell" } } var cellType: UICollectionViewCell.Type { switch self { case .topSites: return ASHorizontalScrollCell.self case .pocket: return FirefoxHomeHighlightCell.self case .libraryShortcuts: return ASLibraryCell.self } } init(at indexPath: IndexPath) { self.init(rawValue: indexPath.section)! } init(_ section: Int) { self.init(rawValue: section)! } } } // MARK: - Tableview Delegate extension FirefoxHomeViewController: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! ASHeaderView view.iconView.isHidden = false view.iconView.image = Section(indexPath.section).headerImage let title = Section(indexPath.section).title switch Section(indexPath.section) { case .pocket: view.title = title view.moreButton.isHidden = false view.moreButton.setTitle(Strings.PocketMoreStoriesText, for: .normal) view.moreButton.addTarget(self, action: #selector(showMorePocketStories), for: .touchUpInside) view.titleLabel.textColor = UIColor.Pocket.red view.titleLabel.accessibilityIdentifier = "pocketTitle" view.moreButton.setTitleColor(UIColor.Pocket.red, for: .normal) view.iconView.tintColor = UIColor.Pocket.red return view case .topSites: view.title = title view.titleLabel.accessibilityIdentifier = "topSitesTitle" view.moreButton.isHidden = true return view case .libraryShortcuts: view.title = title view.moreButton.isHidden = false view.moreButton.setTitle(Strings.AppMenuLibrarySeeAllTitleString, for: .normal) view.moreButton.addTarget(self, action: #selector(openHistory), for: .touchUpInside) view.moreButton.accessibilityIdentifier = "libraryMoreButton" view.titleLabel.accessibilityIdentifier = "libraryTitle" return view } case UICollectionView.elementKindSectionFooter: let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "Footer", for: indexPath) as! ASFooterView switch Section(indexPath.section) { case .topSites, .pocket: return view case .libraryShortcuts: view.separatorLineView?.isHidden = true return view } default: return UICollectionReusableView() } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.longPressRecognizer.isEnabled = false selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellSize = Section(indexPath.section).cellSize(for: self.traitCollection, frameWidth: self.view.frame.width) switch Section(indexPath.section) { case .topSites: // Create a temporary cell so we can calculate the height. let layout = topSiteCell.collectionView.collectionViewLayout as! HorizontalFlowLayout let estimatedLayout = layout.calculateLayout(for: CGSize(width: cellSize.width, height: 0)) return CGSize(width: cellSize.width, height: estimatedLayout.size.height) case .pocket: return cellSize case .libraryShortcuts: let numberofshortcuts: CGFloat = 4 let titleSpacing: CGFloat = 10 let width = min(FirefoxHomeUX.LibraryShortcutsMaxWidth, cellSize.width) return CGSize(width: width, height: (width / numberofshortcuts) + titleSpacing) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { switch Section(section) { case .pocket: return pocketStories.isEmpty ? .zero : Section(section).headerHeight case .topSites: return Section(section).headerHeight case .libraryShortcuts: return UIDevice.current.userInterfaceIdiom == .pad ? CGSize.zero : Section(section).headerHeight } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { switch Section(section) { case .pocket: return .zero case .topSites: return Section(section).footerHeight case .libraryShortcuts: return UIDevice.current.userInterfaceIdiom == .pad ? CGSize.zero : Section(section).footerHeight } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return FirefoxHomeUX.rowSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let insets = Section(section).sectionInsets(self.traitCollection, frameWidth: self.view.frame.width) return UIEdgeInsets(top: 0, left: insets, bottom: 0, right: insets) } fileprivate func showSiteWithURLHandler(_ url: URL, isGoogleTopSite: Bool = false) { let visitType = VisitType.bookmark homePanelDelegate?.homePanel(didSelectURL: url, visitType: visitType, isGoogleTopSite: isGoogleTopSite) } } // MARK: - Tableview Data Source extension FirefoxHomeViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var numItems: CGFloat = FirefoxHomeUX.numberOfItemsPerRowForSizeClassIpad[self.traitCollection.horizontalSizeClass] if UIApplication.shared.statusBarOrientation.isPortrait { numItems = numItems - 1 } if self.traitCollection.horizontalSizeClass == .compact && UIApplication.shared.statusBarOrientation.isLandscape { numItems = numItems - 1 } switch Section(section) { case .topSites: return topSitesManager.content.isEmpty ? 0 : 1 case .pocket: // There should always be a full row of pocket stories (numItems) otherwise don't show them return pocketStories.count case .libraryShortcuts: // disable the libary shortcuts on the ipad return UIDevice.current.userInterfaceIdiom == .pad ? 0 : 1 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier = Section(indexPath.section).cellIdentifier let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) switch Section(indexPath.section) { case .topSites: return configureTopSitesCell(cell, forIndexPath: indexPath) case .pocket: return configurePocketItemCell(cell, forIndexPath: indexPath) case .libraryShortcuts: return configureLibraryShortcutsCell(cell, forIndexPath: indexPath) } } func configureLibraryShortcutsCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let libraryCell = cell as! ASLibraryCell let targets = [#selector(openBookmarks), #selector(openReadingList), #selector(openDownloads), #selector(openSyncedTabs)] libraryCell.libraryButtons.map({ $0.button }).zip(targets).forEach { (button, selector) in button.removeTarget(nil, action: nil, for: .allEvents) button.addTarget(self, action: selector, for: .touchUpInside) } libraryCell.applyTheme() return cell } //should all be collectionview func configureTopSitesCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let topSiteCell = cell as! ASHorizontalScrollCell topSiteCell.delegate = self.topSitesManager topSiteCell.setNeedsLayout() topSiteCell.collectionView.reloadData() return cell } func configurePocketItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell { let pocketStory = pocketStories[indexPath.row] let pocketItemCell = cell as! FirefoxHomeHighlightCell pocketItemCell.configureWithPocketStory(pocketStory) return pocketItemCell } } // MARK: - Data Management extension FirefoxHomeViewController: DataObserverDelegate { // Reloads both highlights and top sites data from their respective caches. Does not invalidate the cache. // See ActivityStreamDataObserver for invalidation logic. func reloadAll() { // If the pocket stories are not availible for the Locale the PocketAPI will return nil // So it is okay if the default here is true TopSitesHandler.getTopSites(profile: profile).uponQueue(.main) { result in // If there is no pending cache update and highlights are empty. Show the onboarding screen self.collectionView?.reloadData() self.topSitesManager.currentTraits = self.view.traitCollection let numRows = max(self.profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows, 1) let maxItems = Int(numRows) * self.topSitesManager.numberOfHorizontalItems() var sites = Array(result.prefix(maxItems)) // Check if all result items are pinned site var pinnedSites = 0 result.forEach { if let _ = $0 as? PinnedSite { pinnedSites += 1 } } // Special case: Adding Google topsite let googleTopSite = GoogleTopSiteHelper(prefs: self.profile.prefs) if !googleTopSite.isHidden, let gSite = googleTopSite.suggestedSiteData() { // Once Google top site is added, we don't remove unless it's explicitly unpinned // Add it when pinned websites are less than max pinned sites if googleTopSite.hasAdded || pinnedSites < maxItems { sites.insert(gSite, at: 0) // Purge unwated websites from the end of list if sites.count > maxItems { sites.removeLast(sites.count - maxItems) } googleTopSite.hasAdded = true } } self.topSitesManager.content = sites self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in self.longPressRecognizer.isEnabled = false let isGoogleTopSiteUrl = url.absoluteString == GoogleTopSiteConstants.usUrl || url.absoluteString == GoogleTopSiteConstants.rowUrl self.showSiteWithURLHandler(url as URL, isGoogleTopSite: isGoogleTopSiteUrl) } self.getPocketSites().uponQueue(.main) { _ in if !self.pocketStories.isEmpty { self.collectionView?.reloadData() } } // Refresh the AS data in the background so we'll have fresh data next time we show. self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: false) } } func getPocketSites() -> Success { let showPocket = (profile.prefs.boolForKey(PrefsKeys.ASPocketStoriesVisible) ?? Pocket.IslocaleSupported(Locale.current.identifier)) guard showPocket else { self.pocketStories = [] return succeed() } return pocketAPI.globalFeed(items: 10).bindQueue(.main) { pStory in self.pocketStories = pStory return succeed() } } @objc func showMorePocketStories() { showSiteWithURLHandler(Pocket.MoreStoriesURL) } // Invoked by the ActivityStreamDataObserver when highlights/top sites invalidation is complete. func didInvalidateDataSources(refresh forced: Bool, topSitesRefreshed: Bool) { // Do not reload panel unless we're currently showing the highlight intro or if we // force-reloaded the highlights or top sites. This should prevent reloading the // panel after we've invalidated in the background on the first load. if forced { reloadAll() } } func hideURLFromTopSites(_ site: Site) { guard let host = site.tileURL.normalizedHost else { return } let url = site.tileURL.absoluteString // if the default top sites contains the siteurl. also wipe it from default suggested sites. if defaultTopSites().filter({$0.url == url}).isEmpty == false { deleteTileForSuggestedSite(url) } profile.history.removeHostFromTopSites(host).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true) } } func pinTopSite(_ site: Site) { profile.history.addPinnedTopSite(site).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true) } } func removePinTopSite(_ site: Site) { // Special Case: Hide google top site if site.guid == GoogleTopSiteConstants.googleGUID { let gTopSite = GoogleTopSiteHelper(prefs: self.profile.prefs) gTopSite.isHidden = true } profile.history.removeFromPinnedTopSites(site).uponQueue(.main) { result in guard result.isSuccess else { return } self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true) } } fileprivate func deleteTileForSuggestedSite(_ siteURL: String) { var deletedSuggestedSites = profile.prefs.arrayForKey(TopSitesHandler.DefaultSuggestedSitesKey) as? [String] ?? [] deletedSuggestedSites.append(siteURL) profile.prefs.setObject(deletedSuggestedSites, forKey: TopSitesHandler.DefaultSuggestedSitesKey) } func defaultTopSites() -> [Site] { let suggested = SuggestedSites.asArray() let deleted = profile.prefs.arrayForKey(TopSitesHandler.DefaultSuggestedSitesKey) as? [String] ?? [] return suggested.filter({deleted.firstIndex(of: $0.url) == .none}) } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let point = longPressGestureRecognizer.location(in: self.collectionView) guard let indexPath = self.collectionView?.indexPathForItem(at: point) else { return } switch Section(indexPath.section) { case .pocket: presentContextMenu(for: indexPath) case .topSites: let topSiteCell = self.collectionView?.cellForItem(at: indexPath) as! ASHorizontalScrollCell let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView) guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return } presentContextMenu(for: topSiteIndexPath) case .libraryShortcuts: return } } fileprivate func fetchBookmarkStatus(for site: Site, with indexPath: IndexPath, forSection section: Section, completionHandler: @escaping () -> Void) { profile.places.isBookmarked(url: site.url).uponQueue(.main) { result in let isBookmarked = result.successValue ?? false site.setBookmarked(isBookmarked) completionHandler() } } func selectItemAtIndex(_ index: Int, inSection section: Section) { let site: Site? switch section { case .pocket: site = Site(url: pocketStories[index].url.absoluteString, title: pocketStories[index].title) let params = ["Source": "Activity Stream", "StoryType": "Article"] TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .pocketStory) LeanPlumClient.shared.track(event: .openedPocketStory, withParameters: params) case .topSites: return case .libraryShortcuts: return } if let site = site { showSiteWithURLHandler(URL(string: site.url)!) } } } extension FirefoxHomeViewController { @objc func openBookmarks() { homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .bookmarks) } @objc func openHistory() { homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .history) } @objc func openSyncedTabs() { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .syncHomeShortcut) homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .syncedTabs) } @objc func openReadingList() { homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .readingList) } @objc func openDownloads() { homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .downloads) } } extension FirefoxHomeViewController: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { fetchBookmarkStatus(for: site, with: indexPath, forSection: Section(indexPath.section)) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } } func getSiteDetails(for indexPath: IndexPath) -> Site? { switch Section(indexPath.section) { case .pocket: return Site(url: pocketStories[indexPath.row].url.absoluteString, title: pocketStories[indexPath.row].title) case .topSites: return topSitesManager.content[indexPath.item] case .libraryShortcuts: return nil } } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard let siteURL = URL(string: site.url) else { return nil } var sourceView: UIView? switch Section(indexPath.section) { case .topSites: if let topSiteCell = self.collectionView?.cellForItem(at: IndexPath(row: 0, section: 0)) as? ASHorizontalScrollCell { sourceView = topSiteCell.collectionView.cellForItem(at: indexPath) } case .pocket: sourceView = self.collectionView?.cellForItem(at: indexPath) case .libraryShortcuts: return nil } let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { _, _ in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) let source = ["Source": "Activity Stream Long Press Context Menu"] LeanPlumClient.shared.track(event: .openedNewTab, withParameters: source) if Section(indexPath.section) == .pocket { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .pocketStory) LeanPlumClient.shared.track(event: .openedPocketStory, withParameters: source) } } let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { _, _ in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } let bookmarkAction: PhotonActionSheetItem if site.bookmarked ?? false { bookmarkAction = PhotonActionSheetItem(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { _, _ in self.profile.places.deleteBookmarksWithURL(url: site.url) >>== { self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: false) site.setBookmarked(false) } TelemetryWrapper.recordEvent(category: .action, method: .delete, object: .bookmark, value: .activityStream) }) } else { bookmarkAction = PhotonActionSheetItem(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { _, _ in let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon) _ = self.profile.places.createBookmark(parentGUID: BookmarkRoots.MobileFolderGUID, url: shareItem.url, title: shareItem.title) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: .shared) site.setBookmarked(true) self.profile.panelDataObservers.activityStream.refreshIfNeeded(forceTopSites: true) LeanPlumClient.shared.track(event: .savedBookmark) TelemetryWrapper.recordEvent(category: .action, method: .add, object: .bookmark, value: .activityStream) }) } let shareAction = PhotonActionSheetItem(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { _, _ in let helper = ShareExtensionHelper(url: siteURL, tab: nil) let controller = helper.createActivityViewController({ (_, _) in }) if UI_USER_INTERFACE_IDIOM() == .pad, let popoverController = controller.popoverPresentationController { let cellRect = sourceView?.frame ?? .zero let cellFrameInSuperview = self.collectionView?.convert(cellRect, to: self.collectionView) ?? .zero popoverController.sourceView = sourceView popoverController.sourceRect = CGRect(origin: CGPoint(x: cellFrameInSuperview.size.width/2, y: cellFrameInSuperview.height/2), size: .zero) popoverController.permittedArrowDirections = [.up, .down, .left] popoverController.delegate = self } self.present(controller, animated: true, completion: nil) }) let removeTopSiteAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { _, _ in self.hideURLFromTopSites(site) }) let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { _, _ in self.pinTopSite(site) }) let removePinTopSite = PhotonActionSheetItem(title: Strings.RemovePinTopsiteActionTitle, iconString: "action_unpin", handler: { _, _ in self.removePinTopSite(site) }) let topSiteActions: [PhotonActionSheetItem] if let _ = site as? PinnedSite { topSiteActions = [removePinTopSite] } else { topSiteActions = [pinTopSite, removeTopSiteAction] } var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction] switch Section(indexPath.section) { case .pocket: break case .topSites: actions.append(contentsOf: topSiteActions) case .libraryShortcuts: break } return actions } } extension FirefoxHomeViewController: UIPopoverPresentationControllerDelegate { // Dismiss the popover if the device is being rotated. // This is used by the Share UIActivityViewController action sheet on iPad func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) { popoverPresentationController.presentedViewController.dismiss(animated: false, completion: nil) } }
mpl-2.0
3dd51d21d61b584eb01100a8f344297a
44.205044
218
0.660465
5.429606
false
false
false
false
soapyigu/LeetCode_Swift
LinkedList/PalindromeLinkedList.swift
1
1245
/** * Question Link: https://leetcode.com/problems/palindrome-linked-list/ * Primary idea: Runner tech, reverse the first half linkedlist, then compare it to the next half * Time Complexity: O(n), Space Complexity: O(1) * * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class PalindromeLinkedList { func isPalindrome(head: ListNode?) -> Bool { guard head != nil else { return true } var slow = head var fast = head var prev: ListNode? var post = slow!.next while fast != nil && fast!.next != nil { fast = fast!.next!.next slow!.next = prev prev = slow slow = post post = post!.next } if fast != nil { slow = post } while prev != nil { if prev!.val != slow!.val { return false } prev = prev!.next slow = slow!.next } return true } }
mit
06fb358077453de718e32fb515f7f739
22.961538
97
0.473896
4.478417
false
false
false
false
NobodyNada/SwiftChatSE
Sources/SwiftChatSE/WebSocket.swift
1
12939
// // WebSocket-Linux.swift // FireAlarm // // Created by NobodyNada on 11/17/16. // Copyright © 2016 NobodyNada. All rights reserved. // //#if os(Linux) import Foundation import Clibwebsockets private func binToStr(_ data: Data) -> String? { var withNull = data if data[data.count - 1] != 0 { withNull.append(0) } return String(data: data, encoding: .utf8) } private func websocketCallback( _ wsi: OpaquePointer?, _ reason: lws_callback_reasons, _ user: UnsafeMutableRawPointer?, _ inData: UnsafeMutableRawPointer?, _ len: size_t ) -> Int32 { let reasons = [ //The callback reasons to listen for. LWS_CALLBACK_CLIENT_RECEIVE, LWS_CALLBACK_CLIENT_WRITEABLE, LWS_CALLBACK_CLIENT_RECEIVE_PONG, LWS_CALLBACK_CLIENT_ESTABLISHED, LWS_CALLBACK_CLIENT_HTTP_WRITEABLE, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER, LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED, LWS_CALLBACK_CLOSED, /*LWS_CALLBACK_LOCK_POLL, LWS_CALLBACK_UNLOCK_POLL, LWS_CALLBACK_ADD_POLL_FD, LWS_CALLBACK_DEL_POLL_FD, LWS_CALLBACK_CHANGE_MODE_POLL_FD, LWS_CALLBACK_GET_THREAD_ID*/ ] if !reasons.contains(where: {$0 == reason}) { return 0 } var ws: WebSocket! if let socket = user?.bindMemory(to: WebSocket.self, capacity: 1).pointee { ws = socket } else { for socket in WebSocket.sockets { if socket.ws == wsi { ws = socket } } } switch reason { case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: for socket in WebSocket.sockets { if socket.state == .connecting { if let headers = socket.customHeaders { guard headers.lengthOfBytes(using: .utf8) <= len else { print("Not enough buffer space for custom headers!") return 0 } let ptr = inData!.bindMemory(to: UnsafeMutablePointer<CChar>.self, capacity: 1) let p = ptr.pointee strncpy(p, headers, len) ptr.pointee = p.advanced(by: Int(strlen(headers))) } } } case LWS_CALLBACK_CLIENT_ESTABLISHED: ws.opened() user?.bindMemory(to: WebSocket.self, capacity: 1).pointee = ws break case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: let message = inData.map { String(cString: $0.bindMemory(to: Int8.self, capacity: len)) } ws.connectionError(message) case LWS_CALLBACK_CLIENT_RECEIVE: (inData?.bindMemory(to: UInt8.self, capacity: len)).map { ws?.received(data: $0, length: len) } case LWS_CALLBACK_CLIENT_WRITEABLE: guard let (data, format) = ws.toWrite.first else { break } ws.toWrite.removeFirst() //SWIFT_LWS_PRE_PADDING and SWIFT_LWS_POST_PADDING are defined in my wrapper header "libwebsockets/lws.h" let size = Int(SWIFT_LWS_PRE_PADDING) + data.count + Int(SWIFT_LWS_POST_PADDING) let ptr = malloc(size).bindMemory(to: UInt8.self, capacity: size) let buf = UnsafeMutableBufferPointer<UInt8>( start: ptr.advanced(by: Int(SWIFT_LWS_PRE_PADDING)), count: data.count + Int(LWS_SEND_BUFFER_POST_PADDING) ) let _ = data.copyBytes(to: buf) guard lws_write(ws.ws, buf.baseAddress, data.count, format) != -1 else { ws.state = .error ws.error = WebSocket.WebSocketError.writeFailed ws.errorHandler?(ws) return -1 } case LWS_CALLBACK_CLOSED: ws?.connectionClosed() break default: break } if ws != nil { if ws.state == .disconnecting { return -1 } } return 0 } fileprivate func wsLog(level: Int32, buf: UnsafePointer<Int8>?) { buf.map { print("libwebsockets: " + String(cString: $0), terminator: "") } } ///Handles all the websocket connections. public class WebSocket { public static var debugLoggingEnabled = false public enum WebSocketError: Error { case notURL(str: String) case invalidURL(url: URL) case creationFailed case lwsError(error: String?) case textNotUTF8(text: String) case writeFailed } public enum WebSocketState: Equatable { case disconnected case connecting case connected case disconnecting case error } public let origin: String? public let customHeaders: String? public let url: URL public let secure: Bool public var state: WebSocketState = .disconnected public fileprivate(set) var error: WebSocketError? public var openHandler: ((WebSocket) -> Void)? public var textHandler: ((WebSocket, String) -> Void)? public var binaryHandler: ((WebSocket, Data) -> Void)? public var errorHandler: ((WebSocket) -> Void)? public var closeHandler: ((WebSocket) -> Void)? public func onOpen(_ handler: ((WebSocket) -> Void)?) { openHandler = handler } public func onText(_ handler: ((WebSocket, String) -> Void)?) { textHandler = handler } public func onBinary(_ handler: ((WebSocket, Data) -> Void)?) { binaryHandler = handler } public func onError(_ handler: ((WebSocket) -> Void)?) { errorHandler = handler } public func onClose(_ handler: ((WebSocket) -> Void)?) { closeHandler = handler } public convenience init(_ str: String, origin: String? = nil, headers: String? = nil) throws { guard let url = URL(string: str) else { throw WebSocketError.notURL(str: str) } try self.init(url, origin: origin, headers: headers) } public init(_ url: URL, origin: String? = nil, headers: String? = nil) throws { if url.scheme == nil || url.scheme == "wss" { secure = true } else if url.scheme == "ws" { secure = false } else { throw WebSocketError.invalidURL(url: url) } guard url.host != nil else { throw WebSocketError.invalidURL(url: url) } self.url = url self.origin = origin self.customHeaders = headers } public static func open(_ str: String, origin: String? = nil, headers: String? = nil) throws -> WebSocket { let ws = try WebSocket(str, origin: origin, headers: headers) try ws.connect() return ws } public static func open(_ url: URL, origin: String? = nil, headers: String? = nil) throws -> WebSocket { let ws = try WebSocket(url, origin: origin, headers: headers) try ws.connect() return ws } public func connect() throws { state = .connecting let hostSize = url.host!.lengthOfBytes(using: .utf8) let host = malloc(hostSize + 1).bindMemory(to: Int8.self, capacity: hostSize + 1) strcpy(host, url.host!) let urlPath = url.path + (url.query != nil ? ("?" + url.query!) : "") let pathSize = urlPath.lengthOfBytes(using: .utf8) let path = malloc(pathSize + 1).bindMemory(to: Int8.self, capacity: pathSize + 1) strcpy(path, urlPath) var originBuf: UnsafeMutablePointer<Int8>? origin.map {origin in let originSize = origin.lengthOfBytes(using: .utf8) originBuf = malloc(originSize + 1).bindMemory(to: Int8.self, capacity: originSize + 1) strcpy(originBuf!, origin) } var info = lws_client_connect_info() info.context = WebSocket.context info.address = UnsafePointer<Int8>(host) info.host = info.address info.path = UnsafePointer<Int8>(path) info.port = secure ? 443 : 80 info.ssl_connection = secure ? 1 : 0 info.origin = UnsafePointer<Int8>(originBuf) info.protocol = nil ws = lws_client_connect_via_info(&info) WebSocket.sockets.append(self) if WebSocket.sockets.count == 1 { WebSocket.runSockets() } guard ws != nil else { try error(.creationFailed) } } ///Sends a text message across the socket. public func write(_ text: String) { guard let data = text.data(using: .utf8) else { print("text not UTF-8") return } doWrite(data, LWS_WRITE_TEXT) } ///Sends a binary message across the socket. public func write(_ data: Data) { doWrite(data, LWS_WRITE_BINARY) } private func doWrite(_ data: Data, _ format: lws_write_protocol) { guard state == .connected else { return } toWrite.append((data, format)) lws_callback_on_writable(ws) } public func disconnect() { guard state == .connecting || state == .connected else { return } state = .disconnecting //force a callback so LWS knows to close the connection //lws_callback_all_protocol(WebSocket.context, WebSocket.protocols, Int32(LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION)) lws_callback_on_writable(ws) } fileprivate var ws: OpaquePointer? fileprivate var toWrite = [(Data, lws_write_protocol)]() fileprivate var requestedClose = false private var incomingData: Data? fileprivate static var sockets = [WebSocket]() fileprivate func connectionError(_ message: String?) { state = .error error = .lwsError(error: message) errorHandler?(self) } fileprivate func opened() { state = .connected openHandler?(self) } fileprivate func connectionClosed() { state = .disconnected closeHandler?(self) if let index = WebSocket.sockets.index(where: { $0 === self }) { WebSocket.sockets.remove(at: index) } } fileprivate func received(data: UnsafePointer<UInt8>, length: Int) { let data = Data(bytes: data, count: length) if incomingData == nil { incomingData = data } else { incomingData!.append(data) } if lws_is_final_fragment(ws) != 0 { if lws_frame_is_binary(ws) == 0, let text = binToStr(incomingData!) { textHandler?(self, text) } else { binaryHandler?(self, incomingData!) } incomingData = nil } } private func error(_ error: WebSocketError) throws -> Never { state = .error self.error = error throw error } private static func _runSockets() { while !sockets.isEmpty { //every 100ms, check for websocket events lws_service(context, 100) //usleep(100000) } } #if os(macOS) @objc private static func _runSockets_thunk() { _runSockets() } private static func runSockets_selector() { Thread.detachNewThreadSelector(#selector(_runSockets_thunk), toTarget: self, with: nil) } #endif @available(OSX 10.12, *) private static func runSockets_block() { Thread.detachNewThread { _runSockets() } } static func runSockets() { #if os(Linux) runSockets_block() #else if #available(OSX 10.12, *) { runSockets_block() } else { runSockets_selector() } #endif } private static var _context: OpaquePointer? private static var _protocols: UnsafeMutablePointer<lws_protocols>? private static var protocols: UnsafeMutablePointer<lws_protocols> { if _protocols == nil { _protocols = UnsafeMutablePointer<lws_protocols>.allocate(capacity: 3) _protocols!.initialize(to: lws_protocols()) let str = "http-only" let buf = UnsafeMutablePointer<Int8>.allocate(capacity: str.lengthOfBytes(using: .utf8)) let _ = str.data(using: .utf8)!.copyBytes( to: UnsafeMutableBufferPointer<Int8>(start: buf, count: str.lengthOfBytes(using: .utf8)) ) let empty = UnsafeMutablePointer<Int8>.allocate(capacity: 1) empty.initialize(to: 0) _protocols!.advanced(by: 0).pointee.name = UnsafePointer<Int8>(buf) _protocols!.advanced(by: 1).pointee.name = UnsafePointer<Int8>(empty) _protocols!.advanced(by: 2).pointee.name = UnsafePointer<Int8>(empty) _protocols!.advanced(by: 0).pointee.callback = websocketCallback _protocols!.advanced(by: 1).pointee.callback = websocketCallback _protocols!.advanced(by: 2).pointee.callback = nil _protocols!.advanced(by: 0).pointee.id = 0 _protocols!.advanced(by: 1).pointee.id = 0 _protocols!.advanced(by: 2).pointee.id = 0 _protocols!.advanced(by: 0).pointee.per_session_data_size = MemoryLayout<UnsafeMutablePointer<WebSocket>>.size _protocols!.advanced(by: 1).pointee.per_session_data_size = MemoryLayout<UnsafeMutablePointer<WebSocket>>.size _protocols!.advanced(by: 2).pointee.per_session_data_size = MemoryLayout<UnsafeMutablePointer<WebSocket>>.size _protocols!.advanced(by: 0).pointee.user = nil _protocols!.advanced(by: 1).pointee.user = nil _protocols!.advanced(by: 2).pointee.user = nil _protocols!.advanced(by: 0).pointee.rx_buffer_size = 0 _protocols!.advanced(by: 1).pointee.rx_buffer_size = 0 _protocols!.advanced(by: 2).pointee.rx_buffer_size = 0 } return _protocols! } private static var context: OpaquePointer { if _context == nil { //Create a libwebsockets context. var info = lws_context_creation_info() info.port = CONTEXT_PORT_NO_LISTEN info.iface = nil info.protocols = UnsafePointer<lws_protocols>(protocols) info.extensions = nil info.ssl_cert_filepath = nil info.ssl_private_key_filepath = nil info.gid = -1 info.uid = -1 info.options = UInt64(bitPattern: LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT) info.user = nil if debugLoggingEnabled { lws_set_log_level(0xFFFF, wsLog) } _context = lws_create_context(&info) if _context == nil { fatalError("Failed to create websocket context!") } } return _context! } } //#endif
mit
075da8d1374bee21c048f8dddd170abc
24.927856
117
0.67236
3.286259
false
false
false
false
zjjzmw1/speedxSwift
speedxSwift/speedxSwift/SimpleViewController.swift
1
1876
// // SimpleViewController.swift // swiftDemo1 // // Created by xiaoming on 16/3/7. // Copyright © 2016年 shandandan. All rights reserved. // import UIKit class SimpleViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() // 没有从新赋值的变量都应该用let 否则有警告 // 简单变量 let name = "xiaoming" var age = 26 let height = 180.0 let des = "iOS工程师" let isMan = true // true false 不是OC 里面的 YES NO 了 var isManString = "女" if isMan { isManString = "男" } var sexString:String = isMan ? "男":"女" // sexString ?? "不知道"// 如果为空就为后面的值 age += 1 print(name + String(age) + String(height) + des + String(isMan)) // 数组 let arr = ["apple","banana"] print(arr) print(arr[0]) // 用UILabel 把上面的文字展示出来 let aLabel = UILabel() aLabel.frame = CGRectMake(20, 100, kScreenWidth - 40, 0) aLabel.backgroundColor = UIColor.clearColor() aLabel.font = UIFont.systemFontOfSize(20) aLabel.textColor = UIColor.blackColor() aLabel.text = "姓名:" + name + "年龄:" + String(age) + "身高:" + String(height) + "\n职位:" + des + "性别:" + isManString + sexString + "\n喜欢吃的水果:" + arr[0] + "," + arr[1] aLabel.numberOfLines = 0 // 需要换行的时候需要,高度设置为0 aLabel.sizeToFit() self.view .addSubview(aLabel) } func studay(){ let str = "hello,swift" str.lowercaseString let str1 : String = NSString(format: "%@", "好的") as String str1.lowercaseString } }
mit
4fbc7f83c6d23c5b9e55050f7dc579c9
25.140625
169
0.538553
3.605603
false
false
false
false
SoufianeLasri/Sisley
Sisley/AngleGradientBorderView.swift
1
2205
// // AngleGradientBorderView.swift // Sisley // // Created by Soufiane Lasri on 30/11/2015. // Copyright © 2015 Soufiane Lasri. All rights reserved. // // // AngleGradientBorderView.swift // AngleGradientBorderTutorial // import UIKit class AngleGradientBorderView: UIView { // Constants let DefaultGradientBorderColors: [AnyObject] = [ UIColor( red: 0.78, green: 0.82, blue: 0.85, alpha: 1 ).CGColor, UIColor.clearColor().CGColor ] let DefaultGradientBorderWidth: CGFloat = 2 // Set the UIView's layer class to be our AngleGradientBorderLayer override class func layerClass() -> AnyClass { return AngleGradientBorderLayer.self } // Initializer required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupGradientLayer() } // Custom initializer init( frame: CGRect, borderColors gradientBorderColors: [AnyObject]? = nil, borderWidth gradientBorderWidth: CGFloat? = nil ) { super.init( frame: frame ) self.backgroundColor = UIColor.clearColor() setupGradientLayer( borderColors: gradientBorderColors, borderWidth: gradientBorderWidth ) } // Setup the attributes of this view's layer func setupGradientLayer( borderColors gradientBorderColors: [AnyObject]? = nil, borderWidth gradientBorderWidth: CGFloat? = nil ) { // Grab this UIView's layer and cast it as AngleGradientBorderLayer let l: AngleGradientBorderLayer = self.layer as! AngleGradientBorderLayer // NOTE: Since our gradient layer is built as an image, // we need to scale it to match the display of the device. l.contentsScale = UIScreen.mainScreen().scale // Set the gradient colors if gradientBorderColors != nil { l.colors = gradientBorderColors! } else { l.colors = DefaultGradientBorderColors } // Set the border width of the gradient if gradientBorderWidth != nil { l.gradientBorderWidth = gradientBorderWidth! } else { l.gradientBorderWidth = DefaultGradientBorderWidth } } }
mit
d33b2c16c7afb08de87fe46722dcd77c
31.910448
135
0.656987
4.780911
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
SwiftSideMenuDemo/SwiftSideMenuDemo/SideMenu.swift
1
4872
// // SideMenu.swift // SwiftSideMenuDemo // // Created by Edward Salter on 9/5/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import Foundation import UIKit @objc protocol SideMenuDelegate { func sideMenuDidSelectItemAtIndex(index:Int) optional func sideMenuWillOpen() optional func sideMenuWillClose() } class SideMenu : NSObject, TableVCDelegate { let menuWidth : CGFloat = 220.0 let menuTVInsetTop : CGFloat = 84.0 let menuTVInsetLeft : CGFloat = 0.0 let menuContView = UIView() let menuTVC = TableVC() var animator : UIDynamicAnimator! let sourceView : UIView! var delegate : SideMenuDelegate? var isMenuOpen : Bool = false init(sourceView: UIView, menuData:Array<String>) { super.init() self.sourceView = sourceView self.menuTVC.tableData = menuData self.setupMenuView() animator = UIDynamicAnimator(referenceView:sourceView) // Add show gesture recognizer var showGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("handleGesture:")) showGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right sourceView.addGestureRecognizer(showGestureRecognizer) // Add hide gesture recognizer var hideGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("handleGesture:")) hideGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left menuContView.addGestureRecognizer(hideGestureRecognizer) } func setupMenuView() { // Configure side menu container menuContView.frame = CGRectMake(-menuWidth-1.0, sourceView.frame.origin.y, menuWidth, sourceView.frame.size.height) menuContView.backgroundColor = UIColor.clearColor() menuContView.clipsToBounds = true menuContView.layer.masksToBounds = false; menuContView.layer.shadowOffset = CGSizeMake(1.0, 1.0); menuContView.layer.shadowRadius = 1.0; menuContView.layer.shadowOpacity = 0.125; menuContView.layer.shadowPath = UIBezierPath(rect: menuContView.bounds).CGPath sourceView.addSubview(menuContView) // Add blur view var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView visualEffectView.frame = menuContView.bounds menuContView.addSubview(visualEffectView) // Configure side menu table view menuTVC.delegate = self menuTVC.tableView.frame = menuContView.bounds menuTVC.tableView.clipsToBounds = false menuTVC.tableView.separatorStyle = .None menuTVC.tableView.backgroundColor = UIColor.clearColor() menuTVC.tableView.scrollsToTop = false menuTVC.tableView.contentInset = UIEdgeInsetsMake(menuTVInsetTop, menuTVInsetLeft, 0, 0) menuTVC.tableView.reloadData() menuContView.addSubview(menuTVC.tableView) } func handleGesture(gesture: UISwipeGestureRecognizer) { if (gesture.direction == .Left) { toggleMenu(false) delegate?.sideMenuWillClose?() } else{ toggleMenu(true) delegate?.sideMenuWillOpen?() } } func toggleMenu (shouldOpen: Bool) { animator.removeAllBehaviors() isMenuOpen = shouldOpen let gravityDirectionX: CGFloat = (shouldOpen) ? 0.5 : -0.5; let pushMagnitude: CGFloat = (shouldOpen) ? 80.0 : -80.0; let boundaryPointX: CGFloat = (shouldOpen) ? menuWidth : -menuWidth-1.0; let gravityBehavior = UIGravityBehavior(items: [menuContView]) gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0.0) animator.addBehavior(gravityBehavior) let collisionBehavior = UICollisionBehavior(items: [menuContView]) collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, 20.0), toPoint: CGPointMake(boundaryPointX, sourceView.frame.size.height)) animator.addBehavior(collisionBehavior) let pushBehavior = UIPushBehavior(items: [menuContView], mode: UIPushBehaviorMode.Instantaneous) pushBehavior.magnitude = pushMagnitude animator.addBehavior(pushBehavior) let menuViewBehavior = UIDynamicItemBehavior(items: [menuContView]) menuViewBehavior.elasticity = 0.2 animator.addBehavior(menuViewBehavior) } func menuControllerDidSelectRow(indexPath:NSIndexPath) { delegate?.sideMenuDidSelectItemAtIndex(indexPath.row) } func toggleMenu () { if (isMenuOpen) { toggleMenu(false) } else { toggleMenu(true) } } }
gpl-2.0
214984a61ff035c3b631b151d118254f
36.476923
123
0.675082
5.085595
false
false
false
false
mitchtreece/Bulletin
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UITransition/Transitions/UISlideTransition.swift
1
1922
// // UISlideTransition.swift // Espresso // // Created by Mitch Treece on 6/26/18. // import UIKit /** A sliding view controller transition. */ public class UISlideTransition: UITransition { public var duration: TimeInterval /** Initializes the transition with parameters. - Parameter duration: The transition's animation duration; _defaults to 0.6_. */ public init(duration: TimeInterval = 0.6) { self.duration = duration } override public func transitionController(for transitionType: TransitionType, info: Info) -> UITransitionController { let sourceVC = info.sourceViewController let destinationVC = info.destinationViewController let container = info.transitionContainerView let context = info.context let settings = self.settings(for: transitionType) return UITransitionController(setup: { destinationVC.view.frame = context.finalFrame(for: destinationVC) destinationVC.view.transform = self.boundsTransform( in: container, direction: settings.direction.reversed() ) container.addSubview(destinationVC.view) }, animations: { UIAnimation(.spring(damping: 0.9, velocity: CGVector(dx: 0.25, dy: 0)), duration: self.duration, { sourceVC.view.transform = self.boundsTransform( in: container, direction: settings.direction ) destinationVC.view.transform = .identity }) }, completion: { sourceVC.view.transform = .identity context.completeTransition(!context.transitionWasCancelled) }) } }
mit
4a3dbe3bc0117794364d0088ac3b1e76
28.121212
121
0.570239
5.669617
false
false
false
false
iosyoujian/iOS8-day-by-day
38-handoff/MapOff/MapOff/ViewController.swift
21
2187
// // Copyright 2014 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! let activityType = "com.shinobicontrols.MapOff.viewport" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if userActivity?.activityType != activityType { userActivity?.invalidate() userActivity = NSUserActivity(activityType: activityType) } userActivity?.needsSave = true mapView.delegate = self } // MARK:- UIResponder Activity Handling override func updateUserActivityState(activity: NSUserActivity) { let regionData = withUnsafePointer(&mapView.region) { NSData(bytes: $0, length: sizeof(MKCoordinateRegion)) } activity.userInfo = ["region" : regionData] } override func restoreUserActivityState(activity: NSUserActivity) { if activity.activityType == activityType { // Extract the data let regionData = activity.userInfo!["region"] as! NSData // Need an empty coordinate region to populate var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), span: MKCoordinateSpan(latitudeDelta: 0.0, longitudeDelta: 0.0)) regionData.getBytes(&region, length: sizeof(MKCoordinateRegion)) mapView.setRegion(region, animated: true) } } // MARK:- MKMapViewDelegate func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) { userActivity?.needsSave = true } }
apache-2.0
c42fa21c4c737ecf90b29ecad0021f1f
33.171875
104
0.71102
4.827815
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Keyboard/States/MKeyboardStateSubtract.swift
1
831
import UIKit class MKeyboardStateSubtract:MKeyboardState { private let previousValue:Double private let kNeedsUpdate:Bool = true init(previousValue:Double, editing:String) { self.previousValue = previousValue super.init( editing:editing, needsUpdate:kNeedsUpdate) } override func commitState(model:MKeyboard, view:UITextView) { let currentValue:Double = model.lastNumber() let newValue:Double = previousValue - currentValue editing = model.numberAsString(scalar:newValue) view.text = model.kEmpty view.insertText(editing) let currentString:String = model.numberAsString( scalar:currentValue) commitingDescription = "- \(currentString) = \(editing)" } }
mit
a9ec75ef9cf8203dfe216579b6b33043
26.7
64
0.638989
5.006024
false
false
false
false
kkirsche/Algorhythm
Algorhythm/PlaylistDetailViewController.swift
1
1340
// // PlaylistDetailViewController.swift // Algorhythm // // Created by Kirsche, Kevin Richard on 10/28/15. // Copyright © 2015 Kevin Kirsche. All rights reserved. // import UIKit class PlaylistDetailViewController: UIViewController { @IBOutlet weak var playlistCoverImage: UIImageView! @IBOutlet weak var playlistTitle: UILabel! @IBOutlet weak var playlistDescription: UILabel! @IBOutlet weak var playlistArtist0: UILabel! @IBOutlet weak var playlistArtist1: UILabel! @IBOutlet weak var playlistArtist2: UILabel! var playlist: Playlist? override func viewDidLoad() { super.viewDidLoad() if playlist != nil { // Set the background image stuff playlistCoverImage.image = playlist!.largeIcon playlistCoverImage.backgroundColor = playlist!.backgroundColor // Set the overlay information playlistTitle.text = playlist!.title playlistDescription.text = playlist!.description playlistArtist0.text = playlist!.artists[0] playlistArtist1.text = playlist!.artists[1] playlistArtist2.text = playlist!.artists[2] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
268fb473158af17881eef1a3d7ea6a95
30.139535
74
0.678118
4.996269
false
false
false
false
tschob/AudioPlayerManager
Example/Core/Views/MultiplePlayerInstancesTableViewCell.swift
1
700
// // MultiplePlayerInstancesTableViewCell.swift // Example // // Created by Hans Seiffert on 20.08.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import UIKit import AudioPlayerManager import MediaPlayer class MultiplePlayerInstancesTableViewCell: UITableViewCell { @IBOutlet fileprivate weak var titleLabel : UILabel? @IBOutlet fileprivate weak var playIconImageView : UIImageView? @IBOutlet fileprivate weak var stopIconImageView : UIImageView? func setup(with mediaItem: MPMediaItem, isPlaying: Bool) { self.titleLabel?.text = mediaItem.title self.playIconImageView?.isHidden = (isPlaying == true) self.stopIconImageView?.isHidden = (isPlaying == false) } }
mit
841286002fe58ac55fdbd7d7d39e00f5
28.125
64
0.773963
4.288344
false
false
false
false
sersoft-gmbh/XMLWrangler
Sources/XMLWrangler/XMLElement.swift
1
4753
/// Represents an element in an XML structure. public struct XMLElement: Equatable, Identifiable, CustomStringConvertible, CustomDebugStringConvertible { /// The name of the element. public let name: Name /// The attributes of the element. public var attributes: Attributes /// The content of the element. public var content: Content /// inherited @inlinable public var id: Name { name } /// inherited public var description: String { "XMLElement '\(name)' { \(attributes.storage.count) attribute(s), \(content.storage.count) content element(s) }" } /// inherited public var debugDescription: String { """ XMLElement '\(name.debugDescription)' { attributes: \(attributes.debugDescription) contents: \(content.debugDescription) } """ } /// Creates a new element using the given parameters. /// - Parameters: /// - name: The name of the new element. /// - attributes: The attributes of the new element (defaults to empty attributes). /// - content: The content of the new element (defaults to empty contents). public init(name: Name, attributes: Attributes = [:], content: Content = []) { self.name = name self.attributes = attributes self.content = content } /// Creates a new element using the given parameters. /// - Parameters: /// - name: The name of the new element. /// - attributes: The attributes of the new element (defaults to empty attributes). /// - content: The variadic list of content elements for the new element. @inlinable public init(name: Name, attributes: Attributes = [:], content: Content.Element...) { self.init(name: name, attributes: attributes, content: .init(storage: content)) } /// Creates a new element using the given parameters. /// - Parameters: /// - name: The name of the new element. /// - attributes: The attributes of the new element (defaults to empty attributes). /// - elements: A sequence of `XMLElement`s to use as content for the new element. @inlinable public init<Elements>(name: Name, attributes: Attributes = [:], elements: Elements) where Elements: Sequence, Elements.Element == XMLElement { self.init(name: name, attributes: attributes, content: .init(storage: elements.map { .element($0) })) } /// Creates a new element using the given parameters. /// - Parameters: /// - name: The name of the new element. /// - attributes: The attributes of the new element (defaults to empty attributes). /// - elements: A variadic list of `XMLElement`s to use as content for the new element. @inlinable public init(name: Name, attributes: Attributes = [:], elements: XMLElement...) { self.init(name: name, attributes: attributes, elements: elements) } /// Creates a new element using the given parameters. /// - Parameters: /// - name: The name of the new element. /// - attributes: The attributes of the new element (defaults to empty attributes). /// - stringContent: The string content for the new element. @inlinable public init(name: Name, attributes: Attributes = [:], stringContent: Content.Element.StringPart) { self.init(name: name, attributes: attributes, content: .string(stringContent)) } } extension XMLElement: XMLElementRepresentable { /// inherited @inlinable public var xml: XMLElement { self } /// inherited @inlinable public init(xml: XMLElement) { self = xml } } extension XMLElement { /// Represents the name of an element. @frozen public struct Name: RawRepresentable, Hashable, Codable, ExpressibleByStringLiteral, XMLAttributeContentRepresentable, CustomStringConvertible, CustomDebugStringConvertible { public typealias RawValue = String public typealias StringLiteralType = RawValue /// inherited public let rawValue: RawValue /// inherited public var description: String { rawValue } /// inherited public var debugDescription: String { "\(Self.self)(\(rawValue))" } /// inherited public init(rawValue: RawValue) { self.rawValue = rawValue } /// Creates a new name using the given raw value. @inlinable public init(_ rawValue: RawValue) { self.init(rawValue: rawValue) } /// inherited @inlinable public init(stringLiteral value: StringLiteralType) { self.init(rawValue: value) } } } /// A typealias for `XMLWrangler.XWElement`. /// Use this if you run into conflicts with `Foundation.XMLElement`. public typealias XWElement = XMLElement
apache-2.0
a9f51414ef667289fecbc31c4edef73a
37.330645
178
0.656007
4.825381
false
false
false
false
mdiep/Tentacle
Sources/Tentacle/Repository.swift
1
1145
// // Repository.swift // Tentacle // // Created by Matt Diephouse on 3/3/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation extension Repository { /// A request for the repository's Info /// /// https://developer.github.com/v3/repos/#get public var info: Request<RepositoryInfo> { return Request(method: .get, path: "/repos/\(owner)/\(name)") } } /// A GitHub.com or GitHub Enterprise repository. public struct Repository: CustomStringConvertible { public let owner: String public let name: String public init(owner: String, name: String) { self.owner = owner self.name = name } public var description: String { return "\(owner)/\(name)" } } extension Repository: Hashable { public static func ==(lhs: Repository, rhs: Repository) -> Bool { return lhs.owner.caseInsensitiveCompare(rhs.owner) == .orderedSame && lhs.name.caseInsensitiveCompare(rhs.name) == .orderedSame } public func hash(into hasher: inout Hasher) { description.lowercased().hash(into: &hasher) } }
mit
2ad4755caa1b6c0dbc4e03eab33839a7
23.340426
74
0.638112
4.190476
false
false
false
false
TheBasicMind/SlackReporter
Pod/Classes/SlackCommand.swift
1
15981
// // SlackCommand.swift // SlackReporter // // Created by Paul Lancefield on 02/01/2016. // Copyright © 2016 Paul Lancefield. All rights reserved. // Released under the MIT license // import Foundation let baseSlackURLWebhook = "https://hooks.slack.com/" let baseSlackURLWebAPI = "https://slack.com/" let webAPI = "api/" let webhook = "services/" let jsonContentType = "application/json charset=utf-8" enum SRCommandError: ErrorType { case InvalidArgumentsForCommandForType case SettingOptionalCommandsForTypeThatHasNone case InternalError case ArgumentsAreNotJSONCompliant case CouldNotParseFormData case CouldNotParseJSON case NoInternetConnection case CouldNotConstructHTTPRequest //case RequestError(request: NSURLRequest, response: NSHTTPURLResponse) //case ServerResponseError(request: NSURLRequest, response: NSHTTPURLResponse) case Success(request: NSURLRequest, response: NSHTTPURLResponse) } enum SRCommandStatus { case InternalError(SRCommandError) case RequestError(NSURLRequest) case ServerResponseError(NSURLRequest, NSHTTPURLResponse) case Success(NSURLRequest, NSHTTPURLResponse, NSData) } public enum CommandType: String { case Webhook = "" case Chat_postMessage = "chat.postMessage" case Chat_delete = "chat.delete" case Chat_update = "chat.update" } public enum Arg : String { case Token = "token" case TimeStamp = "ts" case Channel = "channel" case Text = "text" case Username = "username" case AsUser = "as_user" case Parse = "parse" case LinkNames = "link_names" case Attachments = "attachments" case UnfurlLinks = "unfurl_links" case UnfurlMedia = "unfurl_media" case IconUrl = "icon_url" case IconEmoji = "icon_emoji" } let CommandTable: [ CommandType : (required: [Arg], optional: [Arg]? ) ] = [ .Webhook : ( required: [Arg.Token], optional: [Arg.Attachments, Arg.Parse, Arg.LinkNames, Arg.Attachments, Arg.UnfurlLinks, Arg.UnfurlMedia, Arg.IconUrl, Arg.IconEmoji] ), .Chat_postMessage : ( required: [Arg.Token, Arg.Channel, Arg.Text], optional: [Arg.Username, Arg.AsUser, Arg.Parse, Arg.LinkNames, Arg.Attachments, Arg.UnfurlLinks, Arg.UnfurlMedia, Arg.IconUrl, Arg.IconEmoji] ), ] public class SlackCommand { private(set) var command: CommandType private(set) var requiredArguments: [Arg : AnyObject] private(set) var optionalArguments: [Arg : AnyObject] = [:] private(set) var compositedPayloadDictionary: [NSString : AnyObject] = [:] var token: String { get { return requiredArguments[.Token] as! String } set { requiredArguments[.Token] = newValue } } /** Create a slack command for the SRWebServiceClient. May fail and throws an error. To ensure successful command creation use a specific command subclass if one is available for the command you wish to dispatch. - paramter command: The command type required of the command. This value constrains which arguments will need to be supplied to the required parameter - parameter required: The required arguements supplied must match the required arguments expected by the SlackAPI. Initialisation fails if the supplied arguments do not match requirements. */ init?(command aCommand: CommandType, requiredArguments: (argument: Arg, value: AnyObject)...) throws { let argStrings: [ String ] = requiredArguments.map({ $0.argument.rawValue }).sort() let allowedCommands: (required: [Arg], optional: [Arg]? ) = CommandTable[aCommand]! let requiredCommands = allowedCommands.required.map({ $0.rawValue }).sort() self.command = aCommand self.requiredArguments = [:] do { try self.requiredArguments = SlackCommand.dictionaryForArguments( requiredArguments ) } catch { throw SRCommandError.ArgumentsAreNotJSONCompliant } if argStrings.elementsEqual(requiredCommands) == false { throw SRCommandError.InvalidArgumentsForCommandForType } } private class func dictionaryForArguments(arguments: [ (argument: Arg, value: AnyObject) ] ) throws ->[ Arg : AnyObject ] { var dictionary: [Arg : AnyObject] = [:] var jsonDict: [String : AnyObject] = [:] for argumentTuple in arguments { let value = argumentTuple.value //if NSJSONSerialization.isValidJSONObject( value ) == false { // throw SRCommandError.ArgumentsAreNotJSONCompliant //} dictionary[argumentTuple.argument] = value jsonDict[argumentTuple.argument.rawValue] = argumentTuple.value } return dictionary } func setOptionalArguments(arguments: (argument: Arg, value: AnyObject)...) throws { let argStrings: [ String ] = arguments.map({ $0.argument.rawValue }).sort() let allowedArguments: (required: [Arg], optional: [Arg]? ) = CommandTable[command]! guard let optionalArguments = allowedArguments.optional?.map({ $0.rawValue }).sort() else { throw SRCommandError.SettingOptionalCommandsForTypeThatHasNone } for optionalArgument in argStrings { if optionalArguments.contains(optionalArgument) == false { throw SRCommandError.InvalidArgumentsForCommandForType } } do { try self.optionalArguments = SlackCommand.dictionaryForArguments( arguments ) } catch { throw error } } /** Create a URLRequest encapsulating this slack command */ func URLRequest()throws -> NSMutableURLRequest { let request: NSMutableURLRequest var dictionary : [String: AnyObject] = [:] let boundary = "Boundary-\(NSUUID().UUIDString)" let contentType = "multipart/form-data; boundary=\(boundary)" for (s, a) in requiredArguments { dictionary[s.rawValue] = a } for (s, a) in optionalArguments { dictionary[s.rawValue] = a } self.compositedPayloadDictionary = dictionary let data:NSData do { try data = formDataWithDictionary(dictionary, boundary: boundary) } catch { // This is an error case for which retry makes no sense // so we remove the form from the queue and abandon throw SRError.CouldNotParseJSON } // URL of the endpoint we're going to contact. guard let myURL = NSURL(string:"\(baseSlackURLWebAPI)api/\(command.rawValue)") else { throw SRError.InvalidURLComponent } // Create a POST request with our JSON as a request body. request = NSMutableURLRequest(URL: myURL) request.HTTPMethod = "POST"; request.setValue(contentType, forHTTPHeaderField:"Content-Type") request.HTTPBody = data //print( NSString(data: data, encoding: NSUTF8StringEncoding)! ) return request } /** Post the request object to Slack */ func postSlackCommand(completion: ( SRCommandStatus )->Void ) { let request: NSMutableURLRequest do { try request = URLRequest() } catch { completion( SRCommandStatus.InternalError(SRCommandError.CouldNotConstructHTTPRequest) ) return } let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, httpResp, error) in let httpURLResp = httpResp as! NSHTTPURLResponse? guard error == nil else { // failure condition completion( SRCommandStatus.RequestError(request) ) return } guard (200..<300).contains( httpURLResp!.statusCode) else { // Status code in an unexpected range. // Something has gone awry completion( SRCommandStatus.ServerResponseError(request, httpURLResp!)) return } completion( SRCommandStatus.Success(request, httpURLResp!, data!)) } // Start the task task.resume() } /** Produces data encoded for the multi-part forms specification which Slack currently requires for the web API (Slack are apparently switching to JSON content type soon). */ func formDataWithDictionary(dictionary: [ NSString : AnyObject ], boundary: String) throws ->NSData { let httpBody = NSMutableData() for (argument, value) in dictionary { httpBody.appendData( "--\(boundary)\r\n".dataUsingEncoding( NSUTF8StringEncoding )! ) httpBody.appendData( "Content-Disposition: form-data; name=\"\(argument)\"\r\n\r\n".dataUsingEncoding( NSUTF8StringEncoding )! ) switch value { case is Array<AnyObject>: fallthrough case is Dictionary<NSObject,AnyObject>: let data: NSData do { try data = NSJSONSerialization.dataWithJSONObject(value, options:.PrettyPrinted) } catch { throw SRCommandError.CouldNotParseJSON } httpBody.appendData(data) httpBody.appendData( "\r\n".dataUsingEncoding( NSUTF8StringEncoding )! ) case is String: httpBody.appendData( "\(value)\r\n".dataUsingEncoding( NSUTF8StringEncoding )! ) default: httpBody.appendData( "\(value)\r\n".dataUsingEncoding( NSUTF8StringEncoding )! ) } } httpBody.appendData("--\(boundary)--\r\n".dataUsingEncoding( NSUTF8StringEncoding )! ) return httpBody } } public class SlackWebhook: SlackCommand { private override init(command aCommand: CommandType, requiredArguments: (argument: Arg, value: AnyObject)...) { do { try super.init(command: .Webhook, requiredArguments: requiredArguments[0] )! } catch { } } /** Create a webhook command for sending some message text to slack (message text may include markup) */ convenience init(webhookID token: String, text: String = "" ) { self.init(command: .Webhook, requiredArguments: (argument: .Token, value: token) ) self.optionalArguments[.Text] = text } var webhookID: String { get { return requiredArguments[.Token] as! String } set { requiredArguments[.Token] = newValue } } /// Only accepts the attachment if it is a valid JSON /// compatible object or collection. var attachments: AnyObject? { get { return optionalArguments[.Attachments] as AnyObject? } set { guard let attachments = newValue else { return } if NSJSONSerialization.isValidJSONObject(attachments) { optionalArguments[.Attachments] = attachments } } } /** Create a URLRequest encapsulating this slack command */ override func URLRequest()throws -> NSMutableURLRequest { let request: NSMutableURLRequest var dictionary : [String: AnyObject] = [:] for (s, a) in requiredArguments { dictionary[s.rawValue] = a } for (s, a) in optionalArguments { dictionary[s.rawValue] = a } // Remove the token element let hookID = webhookID dictionary["token"] = nil let data:NSData do { try data = NSJSONSerialization.dataWithJSONObject(dictionary, options:.PrettyPrinted) } catch { // This is an error case for which retry makes no sense // so we remove the form from the queue and abandon throw SRError.CouldNotParseJSON } // URL of the endpoint we're going to contact. guard let myURL = NSURL(string:"\(baseSlackURLWebhook)services/\(hookID)") else { throw SRError.InvalidURLComponent } // Create a POST request with our JSON as a request body. request = NSMutableURLRequest(URL: myURL) request.HTTPMethod = "POST"; request.setValue(jsonContentType, forHTTPHeaderField:"Content-Type") request.HTTPBody = data return request } } public class SlackPostMessage : SlackCommand { var channel: String { get { return requiredArguments[.Channel] as! String } set { requiredArguments[.Channel] = newValue } } var text: String { get { return requiredArguments[.Text] as! String } set { requiredArguments[.Text] = newValue } } /// Only accepts the attachment if it is a valid JSON /// compatible object or collection. var attachments: AnyObject? { get { return optionalArguments[.Attachments] as AnyObject? } set { guard let attachments = newValue else { return } if NSJSONSerialization.isValidJSONObject(attachments) { optionalArguments[.Attachments] = attachments } } } /** The specialised init interface of for the post message command. */ init(token: String, channel: String, text: String = "", username: String = "", asUser: Bool = false) { do { try super.init( command: .Chat_postMessage, requiredArguments: (argument: .Token, value: token ), (argument: .Channel, value: channel), (argument: .Text, value: text) )! self.optionalArguments = [.Username: username, .AsUser : asUser] } catch { } } /** The specialised initialisation interface of for the post message command. If using this command, the default token will be supplied. */ init(channel: String, text: String) { do { try super.init( command: .Chat_postMessage, requiredArguments: (argument: .Token, value: "" ), (argument: .Channel, value: channel), (argument: .Text, value: text) )! } catch { } } }
mit
93612cbde8b389bca3bb1fac911bef52
34.275938
140
0.558323
5.319574
false
false
false
false
wcharysz/BJSS-iOS-basket-assignment-source-code
ShoppingList/ExternalLibraries/ObjectMapper/Mapper.swift
3
10592
// // Mapper.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // Copyright (c) 2014 hearst. All rights reserved. // import Foundation public protocol Mappable { init?(_ map: Map) 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) 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(map) { 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) if result.isEmpty { return nil } 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 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, prettyPrint: Bool) -> String? { let JSONDict = toJSON(object) if NSJSONSerialization.isValidJSONObject(JSONDict) { let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : [] let JSONData: NSData? do { JSONData = try NSJSONSerialization.dataWithJSONObject(JSONDict, options: options) } catch let error { print(error) JSONData = nil } if let JSON = JSONData { return NSString(data: JSON, encoding: NSUTF8StringEncoding) as? String } } 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 } }
apache-2.0
b67c8385095fa7283ffe88a8500439d6
27.021164
123
0.688822
3.822447
false
false
false
false
cubixlabs/SocialGIST
Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUIViewController.swift
1
5332
// // BaseUIViewController.swift // GISTFramework // // Created by Shoaib Abdul on 14/06/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit /// BaseUIViewController is a subclass of UIViewController. It has some extra proporties and support for SyncEngine. open class BaseUIViewController: UIViewController { /// Inspectable property for navigation back button - Default back button image is 'NavBackButton' @IBInspectable open var backBtnImageName:String = GIST_CONFIG.navigationBackButtonImgName; private var _hasBackButton:Bool = true; /// Flag for back button visibility. open var hasBackButton:Bool { get { return _hasBackButton; } set { _hasBackButton = newValue; } } //P.E. private var _hasForcedBackButton = false; /// Flag for back button visibility by force. open var hasForcedBackButton:Bool { get { return _hasForcedBackButton; } set { _hasForcedBackButton = newValue; if (_hasForcedBackButton) { _hasBackButton = true; } } } //P.E. private var _lastSyncedDate:String? private var _titleKey:String?; /// Overriden title property to set title from SyncEngine (Hint '#' prefix). override open var title: String? { get { return super.title; } set { if let key:String = newValue , key.hasPrefix("#") == true { _titleKey = key; // holding key for using later super.title = SyncedText.text(forKey: key); } else { super.title = newValue; } } } //P.E. //MARK: - Constructors /// Overridden constructor to setup/ initialize components. /// /// - Parameters: /// - nibNameOrNil: Nib Name /// - nibBundleOrNil: Nib Bundle Name /// - backButton: Flag for back button public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, backButton:Bool) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); _hasBackButton = backButton; } //F.E. /// Overridden constructor to setup/ initialize components. /// /// - Parameters: /// - nibNameOrNil: Nib Name /// - nibBundleOrNil: Nib Bundle Name /// - backButtonForced: Flag to show back button by force public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, backButtonForced:Bool) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); _hasBackButton = backButtonForced; _hasForcedBackButton = backButtonForced; } //F.E. /// Required constructor implemented. override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); } //F.E. /// Required constructor implemented. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } //F.E. //MARK: - Overridden Methods /// Overridden method to setup/ initialize components. override open func viewDidLoad() { super.viewDidLoad(); _lastSyncedDate = SyncEngine.lastSyncedServerDate; } //F.E. /// Overridden method to setup/ initialize components. override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); self.setupBackBtn(); self.updateSyncedData(); }//F.E. //MARK: - Methods ///Setting up custom back button. private func setupBackBtn() { if (_hasBackButton) { if (self.navigationItem.leftBarButtonItem == nil && (_hasForcedBackButton || (self.navigationController != nil && (self.navigationController!.viewControllers as NSArray).count > 1))) { self.navigationItem.hidesBackButton = true; self.navigationItem.leftBarButtonItem = BaseUIBarButtonItem(image: UIImage(named: self.backBtnImageName), style:UIBarButtonItemStyle.plain, target: self, action: #selector(backButtonTapped)); (self.navigationItem.leftBarButtonItem as? BaseUIBarButtonItem)?.respectRTL = true; } } } //F.E. ///Navigation back button tap handler. open func backButtonTapped() { self.view.endEditing(true); _ = self.navigationController?.popViewController(animated: true) } //F.E. /// Recursive update of layout and content from Sync Engine. @discardableResult func updateSyncedData() -> Bool { if let syncedDate:String = SyncEngine.lastSyncedServerDate , syncedDate != _lastSyncedDate { _lastSyncedDate = syncedDate; if _titleKey != nil { self.title = _titleKey; } self.view.updateSyncedData(); (self.navigationController as? BaseUINavigationController)?.updateSyncedData(); return true; } else { return false; } } //F.E. } //CLS END
gpl-3.0
b913fb86de27a28f4af576eada1a95b2
31.506098
207
0.594635
5.057875
false
false
false
false
vmanot/swift-package-manager
Tests/PackageLoadingTests/ManifestTests.swift
1
13692
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 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 Swift project authors */ import XCTest import Basic import Utility import PackageDescription import PackageModel import TestSupport @testable import PackageLoading // FIXME: Rename to PackageDescription (v3) loading tests. class ManifestTests: XCTestCase { let manifestLoader = ManifestLoader(resources: Resources.default) private func loadManifest(_ inputName: String, line: UInt = #line, body: (Manifest) -> Void) { do { let input = AbsolutePath(#file).parentDirectory.appending(component: "Inputs").appending(component: inputName) body(try manifestLoader.loadFile(path: input, baseURL: input.parentDirectory.asString, version: nil)) } catch { XCTFail("Unexpected error: \(error)", file: #file, line: line) } } private func loadManifest(_ contents: ByteString, baseURL: String? = nil) throws -> Manifest { let fs = InMemoryFileSystem() let manifestPath = AbsolutePath.root.appending(component: Manifest.filename) try fs.writeFileContents(manifestPath, bytes: contents) return try manifestLoader.loadFile(path: manifestPath, baseURL: baseURL ?? AbsolutePath.root.asString, version: nil, fileSystem: fs) } private func loadManifest(_ contents: ByteString, baseURL: String? = nil, line: UInt = #line, body: (Manifest) -> Void) { do { let manifest = try loadManifest(contents, baseURL: baseURL) if case .v3 = manifest.package {} else { return XCTFail("Invalid manfiest version") } body(manifest) } catch { XCTFail("Unexpected error: \(error)", file: #file, line: line) } } func testManifestLoading() { // Check a trivial manifest. loadManifest("trivial-manifest.swift") { manifest in XCTAssertEqual(manifest.name, "Trivial") XCTAssertEqual(manifest.manifestVersion, .three) XCTAssertEqual(manifest.package.targets, []) XCTAssertEqual(manifest.package.dependencies, []) } // Check a manifest with package specifications. loadManifest("package-deps-manifest.swift") { manifest in XCTAssertEqual(manifest.name, "PackageDeps") guard case .v3(let package) = manifest.package else { return XCTFail() } XCTAssertEqual(package.targets, []) XCTAssertEqual(package.dependencies, [Package.Dependency.Package(url: "https://example.com/example", majorVersion: 1)]) } // Check a manifest with targets. loadManifest("target-deps-manifest.swift") { manifest in XCTAssertEqual(manifest.name, "TargetDeps") guard case .v3(let package) = manifest.package else { return XCTFail() } XCTAssertEqual(package.targets, [ Target( name: "sys", dependencies: [.Target(name: "libc")]), Target( name: "dep", dependencies: [.Target(name: "sys"), .Target(name: "libc")])]) } // Check loading a manifest from a file system. let trivialManifest = ByteString(encodingAsUTF8: ( "import PackageDescription\n" + "let package = Package(name: \"Trivial\")")) loadManifest(trivialManifest) { manifest in XCTAssertEqual(manifest.name, "Trivial") XCTAssertEqual(manifest.package.targets, []) XCTAssertEqual(manifest.package.dependencies, []) } } func testNoManifest() { XCTAssertThrows(PackageModel.Package.Error.noManifest(baseURL: "/foo", version: nil)) { _ = try manifestLoader.loadFile(path: AbsolutePath("/non-existent-file"), baseURL: "/foo", version: nil) } XCTAssertThrows(PackageModel.Package.Error.noManifest(baseURL: "/bar", version: "1.0.0")) { _ = try manifestLoader.loadFile(path: AbsolutePath("/non-existent-file"), baseURL: "/bar", version: "1.0.0", fileSystem: InMemoryFileSystem()) } } func testNonexistentBaseURL() { let stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Trivial\"," <<< "\n" stream <<< " targets: [" <<< "\n" stream <<< " Target(name: \"Foo\", dependencies: [\"Bar\"])" <<< "\n" stream <<< " ]" <<< "\n" stream <<< ")" <<< "\n" loadManifest(stream.bytes, baseURL: "/non-existent-path") { manifest in XCTAssertEqual(manifest.name, "Trivial") XCTAssertEqual(manifest.package.targets.count, 1) let foo = manifest.package.targets[0] XCTAssertEqual(foo.name, "Foo") XCTAssertEqual(foo.dependencies, [.target(name: "Bar")]) XCTAssertEqual(manifest.package.dependencies, []) } } func testInvalidTargetName() { fixture(name: "Miscellaneous/PackageWithInvalidTargets") { (prefix: AbsolutePath) in do { let manifest = try manifestLoader.loadFile(path: prefix.appending(component: "Package.swift"), baseURL: prefix.asString, version: nil) _ = try PackageBuilder(manifest: manifest, path: prefix, diagnostics: DiagnosticsEngine(), isRootPackage: false).construct() } catch ModuleError.modulesNotFound(let moduleNames) { XCTAssertEqual(Set(moduleNames), Set(["Bake", "Fake"])) } catch { XCTFail("Failed with error: \(error)") } } } /// Check that we load the manifest appropriate for the current version, if /// version specific customization is used. func testVersionSpecificLoading() throws { let bogusManifest: ByteString = "THIS WILL NOT PARSE" let trivialManifest = ByteString(encodingAsUTF8: ( "import PackageDescription\n" + "let package = Package(name: \"Trivial\")")) // Check at each possible spelling. let currentVersion = Versioning.currentVersion let possibleSuffixes = [ "\(currentVersion.major).\(currentVersion.minor).\(currentVersion.patch)", "\(currentVersion.major).\(currentVersion.minor)", "\(currentVersion.major)" ] for (i, key) in possibleSuffixes.enumerated() { let root = AbsolutePath.root // Create a temporary FS with the version we want to test, and everything else as bogus. let fs = InMemoryFileSystem() // Write the good manifests. try fs.writeFileContents( root.appending(component: Manifest.basename + "@swift-\(key).swift"), bytes: trivialManifest) // Write the bad manifests. let badManifests = [Manifest.filename] + possibleSuffixes[i+1 ..< possibleSuffixes.count].map{ Manifest.basename + "@swift-\($0).swift" } try badManifests.forEach { try fs.writeFileContents( root.appending(component: $0), bytes: bogusManifest) } // Check we can load the repository. let manifest = try manifestLoader.load(package: root, baseURL: root.asString, manifestVersion: .three, fileSystem: fs) XCTAssertEqual(manifest.name, "Trivial") } } func testEmptyManifest() throws { do { let stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" let manifest = try loadManifest(stream.bytes) XCTFail("Unexpected success \(manifest)") } catch ManifestParseError.emptyManifestFile {} do { let manifest = try loadManifest("") XCTFail("Unexpected success \(manifest)") } catch ManifestParseError.emptyManifestFile {} } func testCompatibleSwiftVersions() throws { var stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Foo\"," <<< "\n" stream <<< " swiftLanguageVersions: [3, 4]" <<< "\n" stream <<< ")" <<< "\n" var manifest = try loadManifest(stream.bytes) XCTAssertEqual(manifest.package.swiftLanguageVersions ?? [], [3, 4]) stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Foo\"," <<< "\n" stream <<< " swiftLanguageVersions: []" <<< "\n" stream <<< ")" <<< "\n" manifest = try loadManifest(stream.bytes) XCTAssertEqual(manifest.package.swiftLanguageVersions!, []) stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Foo\")" <<< "\n" manifest = try loadManifest(stream.bytes) XCTAssert(manifest.package.swiftLanguageVersions == nil) } func testRuntimeManifestErrors() throws { let stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Foo\"," <<< "\n" stream <<< " dependencies: [" <<< "\n" stream <<< " .Package(url: \"/url\", \"1.0,0\")" <<< "\n" stream <<< " ])" <<< "\n" <<< "\n" do { let manifest = try loadManifest(stream.bytes) XCTFail("Unexpected success \(manifest)") } catch ManifestParseError.runtimeManifestErrors(let errors) { XCTAssertEqual(errors, ["Invalid version string: 1.0,0"]) } } func testProducts() throws { let stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Foo\"" <<< "\n" stream <<< ")" <<< "\n" <<< "\n" stream <<< "products.append(Product(name: \"libfooD\", type: .Library(.Dynamic), modules: [\"Foo\"]))" <<< "\n" stream <<< "products.append(Product(name: \"libfooS\", type: .Library(.Static), modules: [\"Foo\"]))" <<< "\n" stream <<< "products.append(Product(name: \"exe\", type: .Executable, modules: [\"Foo\"]))" <<< "\n" let manifest = try loadManifest(stream.bytes) let products = Dictionary(items: manifest.legacyProducts.map{ ($0.name, $0) }) XCTAssertEqual(products["libfooD"], PackageDescription.Product(name: "libfooD", type: .Library(.Dynamic), modules: ["Foo"])) XCTAssertEqual(products["libfooS"], PackageDescription.Product(name: "libfooS", type: .Library(.Static), modules: ["Foo"])) XCTAssertEqual(products["exe"], PackageDescription.Product(name: "exe", type: .Executable, modules: ["Foo"])) } func testSwiftInterpreterErrors() throws { // Forgot importing package description. var stream = BufferedOutputByteStream() stream <<< "let package = Package(" <<< "\n" stream <<< " name: \"Foo\")" assertManifestContainsError(error: "use of unresolved identifier 'Package'", stream: stream) // Missing name in package object. stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package()" <<< "\n" assertManifestContainsError(error: "missing argument for parameter 'name' in call", stream: stream) // Random syntax error. stream = BufferedOutputByteStream() stream <<< "import PackageDescription" <<< "\n" stream <<< "let package = Package(name: \"foo\")'" <<< "\n" assertManifestContainsError(error: "error: unterminated string literal", stream: stream) } /// Helper to check for swift interpreter errors while loading manifest. private func assertManifestContainsError(error: String, stream: BufferedOutputByteStream, file: StaticString = #file, line: UInt = #line) { do { let manifest = try loadManifest(stream.bytes) XCTFail("Unexpected success \(manifest)", file: file, line: line) } catch ManifestParseError.invalidManifestFormat(let errors) { XCTAssertTrue(errors.contains(error), "\nActual:\n\(errors) \n\nExpected: \(error)", file: file, line: line) } catch { XCTFail("Unexpected error \(error)", file: file, line: line) } } static var allTests = [ ("testEmptyManifest", testEmptyManifest), ("testManifestLoading", testManifestLoading), ("testNoManifest", testNoManifest), ("testNonexistentBaseURL", testNonexistentBaseURL), ("testInvalidTargetName", testInvalidTargetName), ("testVersionSpecificLoading", testVersionSpecificLoading), ("testCompatibleSwiftVersions", testCompatibleSwiftVersions), ("testRuntimeManifestErrors", testRuntimeManifestErrors), ("testProducts", testProducts), ("testSwiftInterpreterErrors", testSwiftInterpreterErrors), ] }
apache-2.0
385462e87a189e384717d2a0e376a840
44.188119
154
0.600643
4.814346
false
true
false
false
vmanot/swift-package-manager
Sources/PackageModel/Package.swift
1
4300
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 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 Swift project authors */ import Basic import Utility // Re-export Version from PackageModel, since it is a key part of the model. @_exported import struct Utility.Version /// The basic package representation. /// /// The package manager conceptually works with five different kinds of /// packages, of which this is only one: /// /// 1. Informally, the repository containing a package can be thought of in some /// sense as the "package". However, this isn't accurate, because the actual /// Package is derived from its manifest, a Package only actually exists at a /// particular repository revision (typically a tag). We also may eventually /// want to support multiple packages within a single repository. /// /// 2. The `PackageDescription.Package` as defined inside a manifest is a /// declarative specification for (part of) the package but not the object that /// the package manager itself is typically working with internally. Rather, /// that specification is primarily used to load the package (see the /// `PackageLoading` target). /// /// 3. A loaded `PackageModel.Manifest` is an abstract representation of a /// package, and is used during package dependency resolution. It contains the /// loaded PackageDescription and information necessary for dependency /// resolution, but nothing else. /// /// 4. A loaded `PackageModel.Package` which has had dependencies loaded and /// resolved. This is the result after `Get.get()`. /// /// 5. A loaded package, as in #4, for which the targets have also been /// loaded. There is not currently a data structure for this, but it is the /// result after `PackageLoading.transmute()`. public final class Package { /// The manifest describing the package. public let manifest: Manifest /// The local path of the package. public let path: AbsolutePath /// The name of the package. public var name: String { return manifest.name } /// The targets contained in the package. public let targets: [Target] /// The products produced by the package. public let products: [Product] // The directory containing the targets which did not explicitly specify // their path. If all targets are explicit, this is the preferred path for // future targets. public let targetSearchPath: AbsolutePath // The directory containing the test targets which did not explicitly specify // their path. If all test targets are explicit, this is the preferred path // for future test targets. public let testTargetSearchPath: AbsolutePath public init( manifest: Manifest, path: AbsolutePath, targets: [Target], products: [Product], targetSearchPath: AbsolutePath, testTargetSearchPath: AbsolutePath ) { self.manifest = manifest self.path = path self.targets = targets self.products = products self.targetSearchPath = targetSearchPath self.testTargetSearchPath = testTargetSearchPath } public enum Error: Swift.Error { case noManifest(baseURL: String, version: String?) case noOrigin(String) } } extension Package: CustomStringConvertible { public var description: String { return name } } extension Package: Hashable, Equatable { public var hashValue: Int { return ObjectIdentifier(self).hashValue } public static func == (lhs: Package, rhs: Package) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } } extension Package.Error: Equatable { public static func == (lhs: Package.Error, rhs: Package.Error) -> Bool { switch (lhs, rhs) { case let (.noManifest(lhs), .noManifest(rhs)): return lhs.baseURL == rhs.baseURL && lhs.version == rhs.version case (.noManifest, _): return false case let (.noOrigin(lhs), .noOrigin(rhs)): return lhs == rhs case (.noOrigin, _): return false } } }
apache-2.0
58c59693070dcc0fb2caceaa13b29ba1
34.245902
81
0.692558
4.689204
false
true
false
false
headione/criticalmaps-ios
CriticalMapsKit/Sources/NextRideFeature/NextRideCore.swift
1
3469
import Combine import ComposableArchitecture import CoreLocation import Foundation import Logger import SharedModels import UserDefaultsClient // MARK: State public struct NextRideState: Equatable { public init(nextRide: Ride? = nil, hasConnectivity: Bool = true) { self.nextRide = nextRide self.hasConnectivity = hasConnectivity } public var hasConnectivity: Bool public var nextRide: Ride? } // MARK: Actions public enum NextRideAction: Equatable { case getNextRide(Coordinate) case nextRideResponse(Result<[Ride], NextRideService.Failure>) case setNextRide(Ride) } // MARK: Environment public struct NextRideEnvironment { public init( service: NextRideService = .live(), store: UserDefaultsClient = .live(), now: @escaping () -> Date = Date.init, mainQueue: AnySchedulerOf<DispatchQueue>, coordinateObfuscator: CoordinateObfuscator = .live ) { self.service = service self.store = store self.now = now self.mainQueue = mainQueue self.coordinateObfuscator = coordinateObfuscator } let service: NextRideService let store: UserDefaultsClient let now: () -> Date let mainQueue: AnySchedulerOf<DispatchQueue> let coordinateObfuscator: CoordinateObfuscator } // MARK: Reducer /// Reducer handling next ride feature actions public let nextRideReducer = Reducer<NextRideState, NextRideAction, NextRideEnvironment> { state, action, env in switch action { case .getNextRide(let coordinate): guard env.store.rideEventSettings().isEnabled else { logger.debug("NextRide featue is disabled") return .none } guard state.hasConnectivity else { logger.debug("Not fetching next ride. No connectivity") return .none } let obfuscatedCoordinate = env.coordinateObfuscator.obfuscate( coordinate, .thirdDecimal ) return env.service.nextRide( obfuscatedCoordinate, env.store.rideEventSettings().eventDistance.rawValue ) .receive(on: env.mainQueue) .catchToEffect() .map(NextRideAction.nextRideResponse) case let .nextRideResponse(.failure(error)): logger.error("Get next ride failed 🛑 with error: \(error)") return .none case let .nextRideResponse(.success(rides)): guard !rides.isEmpty else { logger.info("Rides array is empty") return .none } guard !rides.map(\.rideType).isEmpty else { logger.info("No upcoming events for filter selection rideType") return .none } // Sort rides by date and pick the first one with a date greater than now let ride = rides // swiftlint:disable:this sorted_first_last .lazy .filter { guard let type = $0.rideType else { return true } return env.store.rideEventSettings().typeSettings .lazy .filter(\.isEnabled) .map(\.type) .contains(type) } .filter(\.enabled) .sorted(by: \.dateTime) .first(where: { ride in ride.dateTime > env.now() }) guard let filteredRide = ride else { logger.info("No upcoming events after filter") return .none } return Effect(value: .setNextRide(filteredRide)) case let .setNextRide(ride): state.nextRide = ride return .none } } enum EventError: Error, LocalizedError { case eventsAreNotEnabled case invalidDateError case rideIsOutOfRangeError case noUpcomingRides case rideTypeIsFiltered case rideDisabled }
mit
b9fe5e6676a8c624591830743611636b
26.507937
112
0.692441
4.343358
false
false
false
false
Nikita2k/Himotoki
Himotoki/decode.swift
1
1129
// // decode.swift // Himotoki // // Created by Syo Ikeda on 5/19/15. // Copyright (c) 2015 Syo Ikeda. All rights reserved. // /// - Throws: DecodeError public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) throws -> T { let extractor = Extractor(object) return try T.decode(extractor) } /// - Throws: DecodeError public func decodeArray<T: Decodable where T.DecodedType == T>(object: AnyObject) throws -> [T] { guard let array = object as? [AnyObject] else { throw DecodeError.TypeMismatch(expected: "Array", actual: "\(object)", keyPath: nil) } return try array.map(decode) } /// - Throws: DecodeError public func decodeDictionary<T: Decodable where T.DecodedType == T>(object: AnyObject) throws -> [String: T] { guard let dictionary = object as? [String: AnyObject] else { throw DecodeError.TypeMismatch(expected: "Dictionary", actual: "\(object)", keyPath: nil) } return try dictionary.reduce([:]) { (var accum: [String: T], element) in let (key, value) = element accum[key] = try decode(value) as T return accum } }
mit
5c5afc0768efdb406c7490c7326aa239
31.257143
110
0.655447
3.853242
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Helpers/OrientationDelta.swift
1
3217
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit /// Represents the orientation delta between the interface orientation (as a reference) and the device orientation enum OrientationDelta: Int, CaseIterable { case equal case rotatedLeft case upsideDown case rotatedRight static func + (lhs: OrientationDelta, rhs: OrientationDelta) -> OrientationDelta? { let value = (lhs.rawValue + rhs.rawValue) % OrientationDelta.allCases.count return OrientationDelta(rawValue: value) } init(interfaceOrientation: UIInterfaceOrientation = UIWindow.interfaceOrientation ?? .unknown, deviceOrientation: UIDeviceOrientation = UIDevice.current.orientation) { guard let delta = deviceOrientation.deltaFromPortrait + interfaceOrientation.deltaFromPortrait else { self = .equal return } self = delta } var radians: CGFloat { switch self { case .upsideDown: return OrientationAngle.straight.radians case .rotatedLeft: return OrientationAngle.right.radians case .rotatedRight: return -OrientationAngle.right.radians default: return OrientationAngle.none.radians } } var edgeInsetsShiftAmount: Int { switch self { case .rotatedLeft: return 1 case .rotatedRight: return -1 case .upsideDown: return 2 default: return 0 } } } enum OrientationAngle { case none // 0° case right // 90° case straight // 180° var radians: CGFloat { switch self { case .none: return 0 case .right: return .pi / 2 case .straight: return .pi } } } private extension UIDeviceOrientation { var deltaFromPortrait: OrientationDelta { switch self { case .landscapeLeft: return .rotatedLeft case .landscapeRight: return .rotatedRight case .portraitUpsideDown: return .upsideDown default: return .equal } } } private extension UIInterfaceOrientation { var deltaFromPortrait: OrientationDelta { switch self { case .landscapeLeft: return .rotatedLeft case .landscapeRight: return .rotatedRight case .portraitUpsideDown: return .upsideDown default: return .equal } } }
gpl-3.0
ee08b545b4f06f49e4e9de79236aee22
26.947826
114
0.630367
4.998445
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAEmailVerificationStep.swift
1
9250
// // SBAEmailVerificationStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit open class SBAEmailVerificationStep: SBAInstructionStep, SBASharedInfoController { lazy open var sharedAppDelegate: SBAAppInfoDelegate = { return UIApplication.shared.delegate as! SBAAppInfoDelegate }() public override init(identifier: String) { super.init(identifier: identifier) commonInit() } public init(inputItem: SBASurveyItem, appInfo: SBAAppInfoDelegate?) { super.init(identifier: inputItem.identifier) if appInfo != nil { self.sharedAppDelegate = appInfo! } commonInit() } func commonInit() { if self.title == nil { self.title = Localization.localizedString("VERIFICATION_STEP_TITLE") } if self.detailText == nil { self.detailText = Localization.localizedStringWithFormatKey("REGISTRATION_VERIFICATION_DETAIL_%@", Localization.buttonNext()) } if self.footnote == nil { self.footnote = Localization.localizedString("REGISTRATION_VERIFICATION_FOOTNOTE") } if self.iconImage == nil { self.iconImage = self.sharedAppDelegate.bridgeInfo.logoImage } if self.learnMoreAction == nil { self.learnMoreAction = SBAEmailVerificationLearnMoreAction(identifier: "additionalEmailActions") self.learnMoreAction?.learnMoreButtonText = Localization.localizedString("REGISTRATION_EMAIL_ACTIONS_BUTTON_TEXT") } } // Override the text to display the user's email and the app name. open override var text: String? { get { guard let email = sharedUser.email else { return nil } let appName = Localization.localizedAppName return Localization.localizedStringWithFormatKey("REGISTRATION_VERIFICATION_TEXT_%@_%@", appName, email) } set {} // do nothing } open override func stepViewControllerClass() -> AnyClass { return SBAEmailVerificationStepViewController.classForCoder() } // Mark: NSCoding public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } open class SBAEmailVerificationStepViewController: SBAInstructionStepViewController, SBAUserRegistrationController { // MARK: SBASharedInfoController lazy open var sharedAppDelegate: SBAAppInfoDelegate = { return UIApplication.shared.delegate as! SBAAppInfoDelegate }() // MARK: SBAUserRegistrationController open var failedValidationMessage = Localization.localizedString("SBA_REGISTRATION_UNKNOWN_FAILED") open var failedRegistrationTitle = Localization.localizedString("SBA_REGISTRATION_FAILED_TITLE") // MARK: Navigation overrides - cannot go back and override go forward to register open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Continue button should always say "Next" self.continueButtonTitle = Localization.buttonNext() // set the back and cancel buttons to empty items self.backButtonItem = UIBarButtonItem() } // Override the default method for goForward and attempt user registration. Do not allow subclasses // to override this method final public override func goForward() { showLoadingView() sharedUser.verifyRegistration { [weak self] error in if let error = error { self?.handleFailedRegistration(error) } else { self?.goNext() } } } func goNext() { // Then call super to go forward super.goForward() } override open func goBackward() { // Do nothing } func handleWrongEmailAction() { let task = ORKOrderedTask(identifier: "changeEmail", steps: [SBAChangeEmailStep(identifier: "changeEmail")]) let taskVC = SBATaskViewController(task: task, taskRun: nil) self.present(taskVC, animated: true, completion: nil) } func handleResendEmailAction() { showLoadingView() sharedUser.resendVerificationEmail { [weak self] (error) in if let error = error { self?.handleFailedRegistration(error) } else { self?.hideLoadingView() } } } } @objc open class SBAEmailVerificationLearnMoreAction: SBALearnMoreAction { override open func learnMoreAction(for step: SBALearnMoreActionStep, with taskViewController: ORKTaskViewController) { guard let emailVC = taskViewController.currentStepViewController as? SBAEmailVerificationStepViewController else { return } let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: Localization.buttonCancel(), style: .cancel) { (_) in // do nothing } let wrongEmailAction = UIAlertAction(title: Localization.localizedString("REGISTRATION_WRONG_EMAIL"), style: .default) { (_) in emailVC.handleWrongEmailAction() } let resentEmailAction = UIAlertAction(title: Localization.localizedString("REGISTRATION_RESEND_EMAIL"), style: .default) { (_) in emailVC.handleResendEmailAction() } alertController.addAction(wrongEmailAction) alertController.addAction(resentEmailAction) alertController.addAction(cancelAction) taskViewController.present(alertController, animated: true, completion: nil) } } class SBAChangeEmailStep: ORKFormStep { override init(identifier: String) { super.init(identifier: identifier) let profileInfo = SBAProfileInfoOptions(includes: [.email]) self.title = Localization.localizedString("REGISTRATION_CHANGE_EMAIL_TITLE") self.formItems = profileInfo.makeFormItems(surveyItemType: .account(.emailVerification)) self.isOptional = false } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func stepViewControllerClass() -> AnyClass { return SBAChangeEmailStepViewController.classForCoder() } } class SBAChangeEmailStepViewController: ORKFormStepViewController, SBAUserRegistrationController { // MARK: SBASharedInfoController lazy open var sharedAppDelegate: SBAAppInfoDelegate = { return UIApplication.shared.delegate as! SBAAppInfoDelegate }() // MARK: SBAUserRegistrationController open var failedValidationMessage = Localization.localizedString("SBA_REGISTRATION_UNKNOWN_FAILED") open var failedRegistrationTitle = Localization.localizedString("SBA_REGISTRATION_FAILED_TITLE") // Override the default method for goForward and attempt user registration. Do not allow subclasses // to override this method final public override func goForward() { showLoadingView() sharedUser.changeUserEmailAddress(email!) { [weak self] error in if let error = error { self?.handleFailedRegistration(error) } else { self?.goNext() } } } func goNext() { // Then call super to go forward super.goForward() } }
bsd-3-clause
f7d326b1869a343588a983674fe780aa
36.144578
137
0.674235
5.312464
false
false
false
false
lennet/proNotes
app/proNotes/DocumentOverview/DocumentOverviewCollectionViewCell.swift
1
2757
// // DocumentOverviewCollectionViewCell.swift // proNotes // // Created by Leo Thomas on 16/01/16. // Copyright © 2016 leonardthomas. All rights reserved. // import UIKit protocol DocumentOverviewCollectionViewCellDelegate: class { func didPressedDeleteButton(forCell cell: DocumentOverviewCollectionViewCell) func didRenamedDocument(forCell cell: DocumentOverviewCollectionViewCell, newName: String) } class DocumentOverviewCollectionViewCell: UICollectionViewCell { static let reusableIdentifier = "DocumentOverviewCollectionViewCellIdentifier" @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var thumbImageViewWidthConstraint: NSLayoutConstraint! @IBOutlet weak var thumbImageViewHeightConstraint: NSLayoutConstraint! weak var delegate: DocumentOverviewCollectionViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() thumbImageView.layer.setUpDefaultShaddow() let renameMenutItem = UIMenuItem(title: "Rename", action: #selector(rename)) UIMenuController.shared.menuItems = [renameMenutItem] } override func prepareForReuse() { thumbImageViewWidthConstraint.constant = 65 thumbImageViewHeightConstraint.constant = 100 thumbImageView.image = nil thumbImageView.contentMode = .scaleToFill activityIndicator.stopAnimating() activityIndicator.isHidden = true } override var canBecomeFirstResponder: Bool { get { return true } } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { let actionString = NSStringFromSelector(action) return actionString == "delete:" || actionString == "rename:" } override func delete(_ sender: Any?) { delegate?.didPressedDeleteButton(forCell: self) } func rename(_ sender: AnyObject?) { nameTextField.isUserInteractionEnabled = true nameTextField.becomeFirstResponder() nameTextField.borderStyle = .roundedRect } } extension DocumentOverviewCollectionViewCell: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let text = textField.text else { return false } nameTextField.isUserInteractionEnabled = false nameTextField.borderStyle = .none delegate?.didRenamedDocument(forCell: self, newName: text) textField.resignFirstResponder() return true } }
mit
fb013e3af0360661f84822d5f55b9711
29.622222
94
0.699202
5.901499
false
false
false
false
PhilippeBoisney/AlertViewLoveNotification
Pod/Classes/AlertViewLoveNotification.swift
2
29948
// // AlertViewLoveNotification.swift // AlertViewLoveNotification // // Created by Philippe on 07/10/2016. // Copyright © 2016 CookMinute. All rights reserved. // // // AlertOnboarding.swift // AlertOnboarding // // Created by Philippe Boisney on 23/06/2016. // Copyright © 2016 Philippe Boisney. All rights reserved. // import UIKit import UserNotifications open class AlertViewLoveNotification: UIView { //FOR DATA ------------------------ fileprivate var imageName: String! fileprivate var labelTitleText: String! fileprivate var labelDescriptionText: String! fileprivate var buttonYESText: String! fileprivate var buttonNOText: String! fileprivate var labelTitleSize: CGFloat = 15 fileprivate var labelDescriptionSize: CGFloat = 10 fileprivate var labelButtonSize: CGFloat = 13 //FOR DESIGN ------------------------ fileprivate var buttonYES: UIButton! fileprivate var buttonNO: UIButton! fileprivate var labelTitle: UILabel! fileprivate var labelDescription: UILabel! fileprivate var imageView: UIImageView! //FOR (BETTER) DESIGN ------------------ fileprivate var topSpace: UIView! fileprivate var labelsSpace: UIView! fileprivate var imageLabelSpace: UIView! fileprivate var imageButtonSpace: UIView! fileprivate var layerBlack: UIView! fileprivate var contenerForImage: UIView! // PUBLIC VARS -------------------------------------------------- ///Height of each view (Total of this height MUST be equal to 1) open var heightOfButtonYes: CGFloat = 0.1 open var heightOfButtonNo: CGFloat = 0.1 open var heightSpaceBetweenViews: CGFloat = 0.05 ///There is 4 spaces open var heightOfContenerForImage: CGFloat = 0.35 open var heightOfTitle: CGFloat = 0.1 open var heightOfDescription: CGFloat = 0.15 ///Width of each view open var widthOfImage: CGFloat = 0.9 open var widthOfTitle: CGFloat = 0.7 open var widthOfDescription: CGFloat = 0.9 open var widthForButtons: CGFloat = 0.8 open var heightOfImage: CGFloat = 0.7 ///Colors of views open var colorLabelTitle = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) open var colorLabelDescription = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) open var colorBackgroundAlertView = UIColor(red:0.87, green:0.93, blue:0.95, alpha:1.0) open var colorBacgroundButtonYes = UIColor(red:0.96, green:0.56, blue:0.46, alpha:1.0) open var colorTextColorButtonYes = UIColor.white open var colorBacgroundButtonNO = UIColor.clear open var colorTextColorButtonNO = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) // SIZE OF ALERTVIEW ------------------------------ fileprivate var percentageRatioHeight: CGFloat { get { if DeviceType.IS_IPAD || DeviceType.IS_IPAD_PRO { return 0.6 } else { return 0.8 } } } fileprivate var percentageRatioWidth: CGFloat { get { if DeviceType.IS_IPAD || DeviceType.IS_IPAD_PRO { return 0.6 } else { return 0.8 } } } //INITIALIZERS public init (imageName: String, labelTitle: String, labelDescription: String, buttonYESTitle: String, buttonNOTitle: String) { super.init(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.imageName = imageName self.labelTitleText = labelTitle self.labelDescriptionText = labelDescription self.buttonYESText = buttonYESTitle self.buttonNOText = buttonNOTitle self.checkPhoneSize() self.configure() self.interceptOrientationChange() } override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //----------------------------------------------------------------------------------------- // MARK: PUBLIC FUNCTIONS -------------------------------------------------------------- //----------------------------------------------------------------------------------------- open func show() { self.configure() // Only show once if self.superview != nil { return } // Find current top viewcontroller if let topController = getTopViewController() { let superView: UIView = topController.view superView.addSubview(self.layerBlack) self.addSubview(self.buttonYES) self.addSubview(self.buttonNO) self.addSubview(self.labelTitle) self.addSubview(self.labelDescription) self.addSubview(self.topSpace) self.addSubview(self.labelsSpace) self.addSubview(self.imageLabelSpace) self.addSubview(self.imageButtonSpace) self.contenerForImage.addSubview(self.imageView) self.addSubview(self.contenerForImage) superView.addSubview(self) self.configureConstraints(topController.view) self.animateForOpening() } } //Hide onboarding with animation @objc open func hide(){ DispatchQueue.main.async { self.animateForEnding() } } //------------------------------------------------------------------------------------------ // MARK: PRIVATE FUNCTIONS -------------------------------------------------------------- //------------------------------------------------------------------------------------------ //MARK: FOR CONFIGURATION -------------------------------------- fileprivate func configure() { self.contenerForImage = UIView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.imageView = UIImageView(image: UIImage(named: self.imageName)) self.topSpace = UIView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.imageButtonSpace = UIView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.imageLabelSpace = UIView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.labelsSpace = UIView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.layerBlack = UIView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.layerBlack.backgroundColor = UIColor.black self.layerBlack.alpha = 0.3 self.buttonYES = UIButton(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.buttonYES.setTitle(self.buttonYESText, for: .normal) self.buttonYES.setTitleColor(self.colorTextColorButtonYes, for: .normal) self.buttonYES.backgroundColor = self.colorBacgroundButtonYes self.buttonYES.titleLabel?.font = UIFont(name: "Avenir-Medium", size: self.labelButtonSize) self.buttonNO = UIButton(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.buttonNO.setTitle(self.buttonNOText, for: .normal) self.buttonNO.setTitleColor(self.colorTextColorButtonNO, for: .normal) self.buttonNO.backgroundColor = self.colorBacgroundButtonNO self.buttonNO.titleLabel?.font = UIFont(name: "Avenir-Light", size: self.labelButtonSize) self.labelTitle = UILabel(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.labelTitle.textColor = self.colorLabelTitle self.labelTitle.font = UIFont(name: "Avenir-Medium", size: self.labelTitleSize) self.labelTitle.textAlignment = NSTextAlignment.center self.labelTitle.numberOfLines = 10 self.labelDescription = UILabel(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))) self.labelDescription.font = UIFont(name: "Avenir-Light", size: self.labelDescriptionSize) self.labelDescription.textAlignment = NSTextAlignment.center self.labelDescription.textColor = self.colorLabelDescription self.labelDescription.numberOfLines = 10 self.labelTitle.text = self.labelTitleText self.labelDescription.text = self.labelDescriptionText self.buttonYES.addTarget(self, action: #selector(AlertViewLoveNotification.onClick), for: .touchUpInside) self.buttonNO.addTarget(self, action: #selector(AlertViewLoveNotification.hide), for: .touchUpInside) self.backgroundColor = self.colorBackgroundAlertView self.clipsToBounds = true self.layer.cornerRadius = 10 } // ----------------------------------------------------- //MARK: FOR CONSTRAINTS -------------------------------- // ----------------------------------------------------- fileprivate func configureConstraints(_ superView: UIView) { self.translatesAutoresizingMaskIntoConstraints = false self.buttonYES.translatesAutoresizingMaskIntoConstraints = false self.buttonNO.translatesAutoresizingMaskIntoConstraints = false self.labelTitle.translatesAutoresizingMaskIntoConstraints = false self.labelDescription.translatesAutoresizingMaskIntoConstraints = false self.topSpace.translatesAutoresizingMaskIntoConstraints = false self.layerBlack.translatesAutoresizingMaskIntoConstraints = false self.labelsSpace.translatesAutoresizingMaskIntoConstraints = false self.labelDescription.translatesAutoresizingMaskIntoConstraints = false self.imageView.translatesAutoresizingMaskIntoConstraints = false self.imageLabelSpace.translatesAutoresizingMaskIntoConstraints = false self.imageButtonSpace.translatesAutoresizingMaskIntoConstraints = false self.contenerForImage.translatesAutoresizingMaskIntoConstraints = false self.removeConstraints(self.constraints) self.buttonYES.removeConstraints(self.buttonYES.constraints) self.buttonNO.removeConstraints(self.buttonNO.constraints) self.labelTitle.removeConstraints(self.labelTitle.constraints) self.labelDescription.removeConstraints(self.labelDescription.constraints) self.topSpace.removeConstraints(self.topSpace.constraints) self.labelsSpace.removeConstraints(self.labelsSpace.constraints) self.layerBlack.removeConstraints(self.layerBlack.constraints) self.labelDescription.removeConstraints(self.labelDescription.constraints) self.imageView.removeConstraints(self.imageView.constraints) self.imageLabelSpace.removeConstraints(self.imageLabelSpace.constraints) self.imageButtonSpace.removeConstraints(self.imageButtonSpace.constraints) self.contenerForImage.removeConstraints(self.contenerForImage.constraints) let heightForAlertView = UIScreen.main.bounds.height*percentageRatioHeight let widthForAlertView = UIScreen.main.bounds.width*percentageRatioWidth let heightForContenerOfImageView = heightForAlertView * self.heightOfContenerForImage let widthForContenerOfImageView = widthForAlertView //Constraints for alertview let horizontalContraintsAlertView = NSLayoutConstraint(item: self, attribute: .centerXWithinMargins, relatedBy: .equal, toItem: superView, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let verticalContraintsAlertView = NSLayoutConstraint(item: self, attribute:.centerYWithinMargins, relatedBy: .equal, toItem: superView, attribute: .centerYWithinMargins, multiplier: 1.0, constant: 0) let heightConstraintForAlertView = NSLayoutConstraint.init(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView) let widthConstraintForAlertView = NSLayoutConstraint.init(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView) //Constraints for black layer let heightConstraintBlackLayer = NSLayoutConstraint.init(item: self.layerBlack, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.height) let widthConstraintBlackLayer = NSLayoutConstraint.init(item: self.layerBlack, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.width) //Constraints for top space let verticalContraintsTopSpace = NSLayoutConstraint(item: self.topSpace, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintTopSpace = NSLayoutConstraint(item: self.topSpace, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView) let heightConstraintTopSpace = NSLayoutConstraint(item: self.topSpace, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightSpaceBetweenViews) let pinContraintsTopTopSpace = NSLayoutConstraint(item: self.topSpace, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0) //Constraints for label title let verticalContraintsLabelTitle = NSLayoutConstraint(item: self.labelTitle, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintLabelTitle = NSLayoutConstraint(item: self.labelTitle, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView*self.widthOfTitle) let heightConstraintLabelTitle = NSLayoutConstraint(item: self.labelTitle, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightOfTitle) let pinContraintsTopLabelTitle = NSLayoutConstraint(item: self.labelTitle, attribute: .top, relatedBy: .equal, toItem: self.topSpace, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for labelsSpaces let verticalContraintsLabelsSpaces = NSLayoutConstraint(item: self.labelsSpace, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintLabelsSpaces = NSLayoutConstraint(item: self.labelsSpace, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView) let heightConstraintLabelsSpaces = NSLayoutConstraint(item: self.labelsSpace, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightSpaceBetweenViews) let pinContraintsTopLabelsSpaces = NSLayoutConstraint(item: self.labelsSpace, attribute: .top, relatedBy: .equal, toItem: labelTitle, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for labelDescription let verticalContraintsLabelDescription = NSLayoutConstraint(item: self.labelDescription, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintLabelDescription = NSLayoutConstraint(item: self.labelDescription, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView*self.widthOfDescription) let heightConstraintLabelDescription = NSLayoutConstraint(item: self.labelDescription, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightOfDescription) let pinContraintsTopLabelDescription = NSLayoutConstraint(item: self.labelDescription, attribute: .top, relatedBy: .equal, toItem: labelsSpace, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for imageLabelSpace let verticalContraintsImageLabelSpace = NSLayoutConstraint(item: self.imageLabelSpace, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintImageLabelSpace = NSLayoutConstraint(item: self.imageLabelSpace, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView) let heightConstraintImageLabelSpace = NSLayoutConstraint(item: self.imageLabelSpace, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightSpaceBetweenViews) let pinContraintsImageLabelSpace = NSLayoutConstraint(item: self.imageLabelSpace, attribute: .top, relatedBy: .equal, toItem: self.labelDescription, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for contener of imageView let verticalContraintsContenerImageView = NSLayoutConstraint(item: self.contenerForImage, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintContenerImageView = NSLayoutConstraint(item: self.contenerForImage, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForContenerOfImageView) let heightConstraintContenerImageView = NSLayoutConstraint(item: self.contenerForImage, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForContenerOfImageView) let pinContraintsContenerImageView = NSLayoutConstraint(item: self.contenerForImage, attribute: .top, relatedBy: .equal, toItem: self.imageLabelSpace, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for imageView let verticalContraintsImageView = NSLayoutConstraint(item: self.imageView, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self.contenerForImage, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let horizontalContraintsImageView = NSLayoutConstraint(item: self.imageView, attribute:.centerYWithinMargins, relatedBy: .equal, toItem: self.contenerForImage, attribute: .centerYWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintImageImageView = NSLayoutConstraint(item: self.imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForContenerOfImageView*self.widthOfImage) let heightConstraintImageView = NSLayoutConstraint(item: self.imageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForContenerOfImageView*self.heightOfImage) //Constraints for imageButtonSpace let verticalContraintsImageButtonSpace = NSLayoutConstraint(item: self.imageButtonSpace, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintImageButtonSpace = NSLayoutConstraint(item: self.imageButtonSpace, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView) let heightConstraintImageButtonSpace = NSLayoutConstraint(item: self.imageButtonSpace, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightSpaceBetweenViews) let pinContraintsImageButtonSpace = NSLayoutConstraint(item: self.imageButtonSpace, attribute: .top, relatedBy: .equal, toItem: self.contenerForImage, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for Button YES let verticalContraintsButtonYes = NSLayoutConstraint(item: self.buttonYES, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintButtonYes = NSLayoutConstraint(item: self.buttonYES, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView*self.widthForButtons) let heightConstraintButtonYes = NSLayoutConstraint(item: self.buttonYES, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightOfButtonYes) let pinContraintsButtonYes = NSLayoutConstraint(item: self.buttonYES, attribute: .top, relatedBy: .equal, toItem: self.imageButtonSpace, attribute: .bottom, multiplier: 1.0, constant: 0) //Constraints for Button NO let verticalContraintsButtonNo = NSLayoutConstraint(item: self.buttonNO, attribute:.centerXWithinMargins, relatedBy: .equal, toItem: self, attribute: .centerXWithinMargins, multiplier: 1.0, constant: 0) let widthConstraintButtonNo = NSLayoutConstraint(item: self.buttonNO, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: widthForAlertView*self.widthForButtons) let heightConstraintButtonNo = NSLayoutConstraint(item: self.buttonNO, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightForAlertView*self.heightOfButtonNo) let pinContraintsButtonNo = NSLayoutConstraint(item: self.buttonNO, attribute: .top, relatedBy: .equal, toItem: self.buttonYES, attribute: .bottom, multiplier: 1.0, constant: 0) NSLayoutConstraint.activate( [horizontalContraintsAlertView, verticalContraintsAlertView,heightConstraintForAlertView, widthConstraintForAlertView, widthConstraintLabelTitle, heightConstraintLabelTitle, pinContraintsTopLabelTitle, verticalContraintsLabelTitle, verticalContraintsTopSpace, widthConstraintTopSpace, heightConstraintTopSpace, pinContraintsTopTopSpace, heightConstraintBlackLayer, widthConstraintBlackLayer, verticalContraintsLabelsSpaces, widthConstraintLabelsSpaces, heightConstraintLabelsSpaces, pinContraintsTopLabelsSpaces, verticalContraintsLabelDescription, widthConstraintLabelDescription, pinContraintsTopLabelDescription, heightConstraintLabelDescription, verticalContraintsImageLabelSpace, widthConstraintImageLabelSpace, heightConstraintImageLabelSpace, pinContraintsImageLabelSpace, verticalContraintsImageView, widthConstraintImageImageView, heightConstraintImageView, horizontalContraintsImageView, verticalContraintsImageButtonSpace, widthConstraintImageButtonSpace, heightConstraintImageButtonSpace, pinContraintsImageButtonSpace, verticalContraintsButtonYes, widthConstraintButtonYes, heightConstraintButtonYes, pinContraintsButtonYes, verticalContraintsButtonNo, widthConstraintButtonNo, heightConstraintButtonNo, pinContraintsButtonNo, verticalContraintsContenerImageView, widthConstraintContenerImageView, heightConstraintContenerImageView, pinContraintsContenerImageView]) } // ----------------------------------------------------- //MARK: FOR ANIMATIONS --------------------------------- // ----------------------------------------------------- fileprivate func animateForOpening(){ self.alpha = 1.0 self.transform = CGAffineTransform(scaleX: 0.3, y: 0.3) UIView.animate(withDuration: 1, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: [], animations: { self.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } fileprivate func animateForEnding(){ UIView.animate(withDuration: 0.2, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.alpha = 0.0 }, completion: { (finished: Bool) -> Void in // On main thread DispatchQueue.main.async { self.contenerForImage.removeFromSuperview() self.removeFromSuperview() self.layerBlack.removeFromSuperview() self.buttonYES.removeFromSuperview() self.buttonNO.removeFromSuperview() self.labelTitle.removeFromSuperview() self.labelDescription.removeFromSuperview() self.topSpace.removeFromSuperview() self.labelsSpace.removeFromSuperview() self.imageLabelSpace.removeFromSuperview() self.imageButtonSpace.removeFromSuperview() self.imageView.removeFromSuperview() self.contenerForImage.removeFromSuperview() } }) } // ----------------------------------------------------- //MARK: BUTTON ACTIONS --------------------------------- // ----------------------------------------------------- @objc func onClick(){ self.hide() let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound] let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil) UIApplication.shared.registerUserNotificationSettings(pushNotificationSettings) UIApplication.shared.registerForRemoteNotifications() } // -------------------------------------------------------------- //MARK: NOTIFICATIONS PROCESS ----------------------------------- // -------------------------------------------------------------- fileprivate func interceptOrientationChange(){ UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(AlertViewLoveNotification.onOrientationChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } @objc func onOrientationChange(){ if let superview = self.superview { self.configureConstraints(superview) } } // -------------------------------------------------------------- //MARK: DESIGN PURPOSES ------------------------------------------ // -------------------------------------------------------------- private func checkPhoneSize(){ if DeviceType.IS_IPHONE_4_OR_LESS { self.labelTitleSize = 14 self.labelDescriptionSize = 10 self.labelButtonSize = 10 } else if DeviceType.IS_IPHONE_5 { self.labelTitleSize = 16 self.labelDescriptionSize = 12 self.labelButtonSize = 12 } else if DeviceType.IS_IPHONE_6 { self.labelTitleSize = 17 self.labelDescriptionSize = 13 self.labelButtonSize = 13 } else if DeviceType.IS_IPHONE_6P { self.labelTitleSize = 20 self.labelDescriptionSize = 15 self.labelButtonSize = 13 } else if DeviceType.IS_IPAD { self.labelTitleSize = 22 self.labelDescriptionSize = 18 self.labelButtonSize = 18 } else if DeviceType.IS_IPAD_PRO { self.labelTitleSize = 25 self.labelDescriptionSize = 20 self.labelButtonSize = 20 } } enum UIUserInterfaceIdiom : Int { case Unspecified case Phone case Pad } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0 static let IS_IPAD_PRO = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0 } // ----------------------------------------------------- //MARK: UTILS --------------------------------------- // ----------------------------------------------------- fileprivate func getTopViewController() -> UIViewController? { var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } }
mit
c1ce3a3a7f73efa2e39f437aef8fa64a
60.49076
248
0.671976
5.11985
false
false
false
false
jozsef-vesza/algorithms
Swift/Algorithms.playground/Pages/Manipulation.xcplaygroundpage/Contents.swift
1
628
//: [Previous](@previous) extension CollectionType where Index: BidirectionalIndexType { func reversed() -> [Generator.Element] { var output: [Generator.Element] = [] var index = endIndex while index != startIndex { output.append(self[index.predecessor()]) index = index.predecessor() } return output } } extension String { func reversed() -> String { return String(characters.reversed()) } } let reversed = "abc".reversed() let reversedArr = [1, 2, 3, 4].reversed() //: [Next](@next)
mit
cc142497a2326bc39f4fc75c83c23f32
19.258065
62
0.547771
4.686567
false
false
false
false
mattrubin/onetimepassword
OneTimePasswordLegacyTests/OTPToken.swift
1
5183
// // OTPToken.swift // OneTimePassword // // Copyright (c) 2013-2018 Matt Rubin and the OneTimePassword authors // // 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 OneTimePassword /// `OTPToken` is a mutable, Objective-C-compatible wrapper around `OneTimePassword.Token`. For more /// information about its properties and methods, consult the underlying `OneTimePassword` /// documentation. public final class OTPToken: NSObject { override public required init() {} @objc public var name: String = OTPToken.defaultName @objc public var issuer: String = OTPToken.defaultIssuer @objc public var type: OTPTokenType = .timer @objc public var secret: Data = Data() @objc public var algorithm: OTPAlgorithm = OTPToken.defaultAlgorithm @objc public var digits: UInt = OTPToken.defaultDigits @objc public var period: TimeInterval = OTPToken.defaultPeriod @objc public var counter: UInt64 = OTPToken.defaultInitialCounter private static let defaultName: String = "" private static let defaultIssuer: String = "" private static let defaultAlgorithm: OTPAlgorithm = .sha1 private static var defaultDigits: UInt = 6 private static var defaultInitialCounter: UInt64 = 0 private static var defaultPeriod: TimeInterval = 30 private func update(with token: Token) { self.name = token.name self.issuer = token.issuer self.secret = token.generator.secret self.algorithm = OTPAlgorithm(token.generator.algorithm) self.digits = UInt(token.generator.digits) switch token.generator.factor { case let .counter(counter): self.type = .counter self.counter = counter case let .timer(period): self.type = .timer self.period = period } } private convenience init(token: Token) { self.init() update(with: token) } @objc public func validate() -> Bool { return (tokenForOTPToken(self) != nil) } } public extension OTPToken { @objc(tokenWithURL:) static func token(from url: URL) -> Self? { return token(from: url, secret: nil) } @objc(tokenWithURL:secret:) static func token(from url: URL, secret: Data?) -> Self? { guard let token = Token(url: url, secret: secret) else { return nil } return self.init(token: token) } @objc func url() -> URL? { guard let token = tokenForOTPToken(self) else { return nil } return try? token.toURL() } } // MARK: Enums // swiftlint:disable explicit_enum_raw_value @objc public enum OTPTokenType: UInt8 { case counter case timer } @objc public enum OTPAlgorithm: UInt32 { @objc(OTPAlgorithmSHA1) case sha1 @objc(OTPAlgorithmSHA256) case sha256 @objc(OTPAlgorithmSHA512) case sha512 } // swiftlint:enable explicit_enum_raw_value // MARK: Conversion private extension OTPAlgorithm { init(_ generatorAlgorithm: Generator.Algorithm) { switch generatorAlgorithm { case .sha1: self = .sha1 case .sha256: self = .sha256 case .sha512: self = .sha512 } } } private func tokenForOTPToken(_ otpToken: OTPToken) -> Token? { guard let generator = Generator( factor: factorForOTPToken(otpToken), secret: otpToken.secret, algorithm: algorithmForOTPAlgorithm(otpToken.algorithm), digits: Int(otpToken.digits) ) else { return nil } return Token(name: otpToken.name, issuer: otpToken.issuer, generator: generator) } private func factorForOTPToken(_ otpToken: OTPToken) -> Generator.Factor { switch otpToken.type { case .counter: return .counter(otpToken.counter) case .timer: return .timer(period: otpToken.period) } } private func algorithmForOTPAlgorithm(_ algorithm: OTPAlgorithm) -> Generator.Algorithm { switch algorithm { case .sha1: return .sha1 case .sha256: return .sha256 case .sha512: return .sha512 } }
mit
66b896fbc7ff41e978bb33294b90dc7b
30.412121
100
0.673355
4.203569
false
false
false
false
lumoslabs/realm-cocoa
RealmSwift-swift2.0/Tests/ObjectTests.swift
2
12893
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift import Foundation class ObjectTests: TestCase { // init() Tests are in ObjectCreationTests.swift // init(value:) tests are in ObjectCreationTests.swift func testRealm() { let standalone = SwiftStringObject() XCTAssertNil(standalone.realm) let realm = try! Realm() var persisted: SwiftStringObject! realm.write { persisted = realm.create(SwiftStringObject.self, value: [:]) XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) } XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) dispatchSyncNewThread { autoreleasepool { XCTAssertNotEqual(try! Realm(), persisted.realm!) } } } func testObjectSchema() { let object = SwiftObject() let schema = object.objectSchema XCTAssert(schema as AnyObject is ObjectSchema) XCTAssert(schema.properties as AnyObject is [Property]) XCTAssertEqual(schema.className, "SwiftObject") XCTAssertEqual(schema.properties.map { $0.name }, ["boolCol", "intCol", "floatCol", "doubleCol", "stringCol", "binaryCol", "dateCol", "objectCol", "arrayCol"]) } func testInvalidated() { let object = SwiftObject() XCTAssertFalse(object.invalidated) let realm = try! Realm() realm.write { realm.add(object) XCTAssertFalse(object.invalidated) } realm.write { realm.deleteAll() XCTAssertTrue(object.invalidated) } XCTAssertTrue(object.invalidated) } func testDescription() { let object = SwiftObject() XCTAssertEqual(object.description, "SwiftObject {\n\tboolCol = 0;\n\tintCol = 123;\n\tfloatCol = 1.23;\n\tdoubleCol = 12.3;\n\tstringCol = a;\n\tbinaryCol = <61 — 1 total bytes>;\n\tdateCol = 1970-01-01 00:00:01 +0000;\n\tobjectCol = SwiftBoolObject {\n\t\tboolCol = 0;\n\t};\n\tarrayCol = List<SwiftBoolObject> (\n\t\n\t);\n}") let recursiveObject = SwiftRecursiveObject() recursiveObject.objects.append(recursiveObject) XCTAssertEqual(recursiveObject.description, "SwiftRecursiveObject {\n\tobjects = List<SwiftRecursiveObject> (\n\t\t[0] SwiftRecursiveObject {\n\t\t\tobjects = List<SwiftRecursiveObject> (\n\t\t\t\t[0] SwiftRecursiveObject {\n\t\t\t\t\tobjects = <Maximum depth exceeded>;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n}") } func testPrimaryKey() { XCTAssertNil(Object.primaryKey(), "primary key should default to nil") XCTAssertNil(SwiftStringObject.primaryKey()) XCTAssertNil(SwiftStringObject().objectSchema.primaryKeyProperty) XCTAssertEqual(SwiftPrimaryStringObject.primaryKey()!, "stringCol") XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol") } func testIgnoredProperties() { XCTAssertEqual(Object.ignoredProperties(), [], "ignored properties should default to []") XCTAssertEqual(SwiftIgnoredPropertiesObject.ignoredProperties().count, 2) XCTAssertNil(SwiftIgnoredPropertiesObject().objectSchema["runtimeProperty"]) } func testIndexedProperties() { XCTAssertEqual(Object.indexedProperties(), [], "indexed properties should default to []") XCTAssertEqual(SwiftIndexedPropertiesObject.indexedProperties().count, 1) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.indexed) } func testLinkingObjects() { let realm = try! Realm() let object = SwiftEmployeeObject() assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees")) realm.write { realm.add(object) self.assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "noSuchCol")) XCTAssertEqual(0, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) for _ in 0..<10 { realm.create(SwiftCompanyObject.self, value: [[object]]) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } func testValueForKey() { let test: (SwiftObject) -> () = { object in XCTAssertEqual(object.valueForKey("boolCol") as! Bool!, false) XCTAssertEqual(object.valueForKey("intCol") as! Int!, 123) XCTAssertEqual(object.valueForKey("floatCol") as! Float!, 1.23 as Float) XCTAssertEqual(object.valueForKey("doubleCol") as! Double!, 12.3) XCTAssertEqual(object.valueForKey("stringCol") as! String!, "a") XCTAssertEqual((object.valueForKey("binaryCol") as! NSData), "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) XCTAssertEqual(object.valueForKey("dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 1)) XCTAssertEqual((object.valueForKey("objectCol")! as! SwiftBoolObject).boolCol, false) XCTAssert(object.valueForKey("arrayCol")! is List<SwiftBoolObject>) } test(SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) test(persistedObject) } } func setAndTestAllTypes(setter: (SwiftObject, AnyObject?, String) -> (), getter: (SwiftObject, String) -> (AnyObject?), object: SwiftObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool!, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int!, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float!, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double!, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String!, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual((getter(object, "binaryCol") as! NSData), "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 333)) let boolObject = SwiftBoolObject(value: [true]) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! SwiftBoolObject, boolObject) XCTAssertEqual((getter(object, "objectCol")! as! SwiftBoolObject).boolCol, true) let list = List<SwiftBoolObject>() list.append(boolObject) setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) } func dynamicSetAndTestAllTypes(setter: (DynamicObject, AnyObject?, String) -> (), getter: (DynamicObject, String) -> (AnyObject?), object: DynamicObject, boolObject: DynamicObject) { setter(object, true, "boolCol") XCTAssertEqual((getter(object, "boolCol") as! Bool), true) setter(object, 321, "intCol") XCTAssertEqual((getter(object, "intCol") as! Int), 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual((getter(object, "floatCol") as! Float), 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual((getter(object, "doubleCol") as! Double), 3.21) setter(object, "z", "stringCol") XCTAssertEqual((getter(object, "stringCol") as! String), "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual((getter(object, "binaryCol") as! NSData), "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual((getter(object, "dateCol") as! NSDate), NSDate(timeIntervalSince1970: 333)) setter(object, boolObject, "objectCol") XCTAssertEqual((getter(object, "objectCol") as! DynamicObject), boolObject) XCTAssertEqual(((getter(object, "objectCol") as! DynamicObject)["boolCol"] as! NSNumber), true as NSNumber) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) let list = getter(object, "arrayCol") as! List<DynamicObject> list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) } /// Yields a read-write migration `SwiftObject` to the given block private func withMigrationObject(block: ((MigrationObject, Migration) -> ())) { autoreleasepool { let realm = self.realmWithTestPath() realm.write { _ = realm.create(SwiftObject) } } autoreleasepool { var enumerated = false setSchemaVersion(1, realmPath: self.testRealmPath()) { migration, _ in migration.enumerate(SwiftObject.className()) { oldObject, newObject in if let newObject = newObject { block(newObject, migration) enumerated = true } } } self.realmWithTestPath() XCTAssert(enumerated) } } func testSetValueForKey() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object.setValue(value, forKey: key) return } let getter : (Object, String) -> (AnyObject?) = { object, key in object.valueForKey(key) } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } func testSubscript() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object[key] = value return } let getter : (Object, String) -> (AnyObject?) = { object, key in object[key] } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } }
apache-2.0
b75bf78168765a36636e87df2f866266
43.916376
336
0.639981
4.804696
false
true
false
false
EagleKing/SwiftStudy
下标脚本.playground/Contents.swift
1
1374
//: Playground - noun: a place where people can play import UIKit struct TimesTable { let multiplier:Int subscript(index:Int)->Int//只读下标,可以不用写在get里面 { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("3的6倍是\(threeTimesTable[6])") //********************下标脚本用法*************************** var numverOfLegs = ["spider":8,"ant":6,"cat":4] numverOfLegs["bird"] = 2 //********************下标脚本选项*************************** struct Matrix { let rows:Int,columns:Int var grid:[Double] init(rows:Int,columns:Int) { self.rows = rows self.columns = columns grid = Array(count: rows * columns, repeatedValue: 0.0) } func indexIsValidForRow(row:Int,column:Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row:Int,column:Int) -> Double { get { assert(indexIsValidForRow(row, column: column), "index out of range") return grid[(row * column) + column] } set { assert(indexIsValidForRow(row, column: column), "index out of range") grid[(row * column) + column] = newValue } } } var matrix = Matrix(rows: 2, columns: 2) matrix[0,1] = 1.5 matrix[1,0] = 3.2
mit
f4d36c397380e4f6024a2b823a59b51e
22.157895
81
0.544697
3.728814
false
false
false
false
XVimProject/XVim2
XVim2/XVim/XVimExArg.swift
1
531
// // XVimExArg.swift // XVim2 // // Created by pebble8888 on 2020/05/24. // Copyright © 2020 Shuichiro Suzuki. All rights reserved. // import Foundation @objc class XVimExArg: NSObject { @objc public var arg: String? @objc public var cmd: String? // @objc public var forceit: Bool = false @objc public var noRangeSpecified: Bool = false @objc public var lineBegin: Int = NSNotFound// line1 @objc public var lineEnd: Int = NSNotFound // line2 // @objc public var addressCount: Int = NSNotFound }
mit
01782ff6ca1abcfc8c29dcecea71cc12
26.894737
59
0.683019
3.581081
false
false
false
false
michalziman/mz-location-picker
MZLocationPicker/Classes/MZSearchTableController.swift
1
1646
// // MZSearchTableController.swift // Pods // // Created by Michal Ziman on 01/09/2017. // // import UIKit import MapKit class MZSearchTableController: MZLocationsTableController { private var locationSearch: MKLocalSearch? var searchQuery: String = "" { didSet { if searchQuery.isEmpty { results = [] tableView.reloadData() } else { locationSearch?.cancel() let request = MKLocalSearchRequest() request.naturalLanguageQuery = searchQuery let newLocationSearch = MKLocalSearch(request: request) locationSearch = newLocationSearch let oldQuery = searchQuery newLocationSearch.start { (response, error) in DispatchQueue.main.async { if let r = response { if self.searchQuery != oldQuery { return } self.results = r.mapItems.map { mapItem -> MZLocation in let placemark = mapItem.placemark return MZLocation(coordinate: placemark.coordinate, name: mapItem.name, address: placemark.address) } self.tableView.reloadData() } else { NSLog("MZLocationPicker:MZSearchTableController:\(#function): \(String(describing: error))") } } } } } } }
mit
1d12d28fec3db1a23b813fdcb0aba0b2
33.291667
131
0.484204
6.118959
false
false
false
false
wftllc/hahastream
Haha Stream/Features/VCS/VCSChannelListViewController.swift
1
2469
import UIKit protocol VCSChannelListDelegate: class { func vcsChannelListDidSelect(channel: Channel); func vcsChannelListDidFocus(channel: Channel); } class VCSChannelListViewController: HahaTableViewController { weak var delegate: VCSChannelListDelegate?; public var items: [Channel] = []; override func viewDidLoad() { super.viewDidLoad() self.items = []; refreshData(); tableView.remembersLastFocusedIndexPath = true; } func refreshData() { self.items = []; self.provider.getChannels(success: { (results) in self.items = results.sorted { $0.title < $1.title }; self.tableView?.reloadData(); }, apiError: self.apiErrorClosure, networkFailure: self.networkFailureClosure) } // override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool { //// print("shouldUpdateFocus: \(context.previouslyFocusedView) => \(context.nextFocusedView)") // return super.shouldUpdateFocus(in: context) // } override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { // print("didUpdateFocus: \(context.previouslyFocusedView) => \(context.nextFocusedView)") } 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 { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "VCSChannelListCell", for: indexPath) as! VCSChannelListCell; let channel = self.items[indexPath.row] cell.textLabel?.text = channel.title; cell.ourImageView?.kf.setImage(with: channel.logoURL) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vcs = self.items[indexPath.row] self.delegate?.vcsChannelListDidSelect(channel: vcs) } override func tableView(_ tableView: UITableView, didUpdateFocusIn context: UITableViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { if let cell = context.nextFocusedView as? VCSChannelListCell { let index = tableView.indexPath(for: cell) self.delegate?.vcsChannelListDidFocus(channel: items[index!.row]) } } }
mit
857621f3969e1afff491a4f151d32cdc
31.92
156
0.754151
4.115
false
false
false
false
ontouchstart/swift3-playground
playground2book/Planets/Planets.playgroundbook/Contents/Chapters/Planets.playgroundchapter/Pages/Planets.playgroundpage/Contents.swift
1
5910
/*: # Planets An example for enumeration, protocol and extension */ import UIKit enum Planet { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } protocol HasEnglish { var english : String { get } } extension Planet: HasEnglish { var english : String { switch self { case .mercury: return "Mercury" case .venus: return "Venus" case .earth: return "Earth" case .mars: return "Mars" case .jupiter: return "Jupiter" case .saturn: return "Saturn" case .uranus: return "Uranus" case .neptune: return "Neptune" } } } protocol 有中文 { var 中文 : String { get } } extension Planet: 有中文 { var 中文 : String { switch self { case .mercury: return "水星" case .venus: return "金星" case .earth: return "地球" case .mars: return "火星" case .jupiter: return "木星" case .saturn: return "土星" case .uranus: return "天王星" case .neptune: return "海王星" } } } protocol HasSymbol { var symbol : String { get } } extension Planet: HasSymbol { var symbol : String { switch self { case .mercury: return "☿" case .venus: return "♀" case .earth: return "♁" case .mars: return "♂" case .jupiter: return "♃" case .saturn: return "♄" case .uranus: return "♅" case .neptune: return "♆" } } } protocol HasPlanetImage { var planetImage : UIImage { get } } extension Planet: HasPlanetImage { var planetImage : UIImage { switch self { case .mercury: return UIImage(named: "mercury.png")! case .venus: return UIImage(named: "venus.png")! case .earth: return UIImage(named: "earth.png")! case .mars: return UIImage(named: "mars.png")! case .jupiter: return UIImage(named: "jupiter.png")! case .saturn: return UIImage(named: "saturn.png")! case .uranus: return UIImage(named: "uranus.png")! case .neptune: return UIImage(named: "neptune.png")! } } } protocol HasPlanetImageWithEnglish { var planetImageWithEnglish : UIImage { get } } extension Planet: HasPlanetImageWithEnglish { var planetImageWithEnglish : UIImage { let textColor: UIColor = .white let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 12)! let textFontAttributes = [ NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor, ] let w = self.planetImage.size.width let h = self.planetImage.size.height UIGraphicsBeginImageContext(self.planetImage.size) self.planetImage.draw(in: CGRect(x: 0, y: 0, width: w, height: h)) let frame = CGRect(x: 0, y: 0, width: 60, height: 32) self.english.draw(in: frame, withAttributes: textFontAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } protocol 有中文行星圖像 { var 中文行星圖像 : UIImage { get } } extension Planet: 有中文行星圖像 { var 中文行星圖像 : UIImage { let textColor: UIColor = .white let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 12)! let textFontAttributes = [ NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor, ] let w = self.planetImage.size.width let h = self.planetImage.size.height UIGraphicsBeginImageContext(self.planetImage.size) self.planetImage.draw(in: CGRect(x: 0, y: 0, width: w, height: h)) let frame = CGRect(x: 0, y: 0, width: 60, height: 32) self.中文.draw(in: frame, withAttributes: textFontAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } protocol PlanetImageWithSymbol { var planetImageWithSymbol : UIImage { get } } extension Planet: PlanetImageWithSymbol { var planetImageWithSymbol : UIImage { let textColor: UIColor = .white let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 30)! let textFontAttributes = [ NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor, ] let w = self.planetImage.size.width let h = self.planetImage.size.height UIGraphicsBeginImageContext(self.planetImage.size) self.planetImage.draw(in: CGRect(x: 0, y: 0, width: w, height: h)) let frame = CGRect(x: 0, y: 0, width: 32, height: 32) self.symbol.draw(in: frame, withAttributes: textFontAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } import PlaygroundSupport import CoreGraphics var imageArray:[UIImage] = [] for var p in [Planet.mercury, Planet.venus, Planet.earth, Planet.mars, Planet.jupiter, Planet.saturn, Planet.uranus, Planet.neptune] { imageArray.append(p.planetImage) imageArray.append(p.planetImageWithEnglish) imageArray.append(p.中文行星圖像) imageArray.append(p.planetImageWithSymbol) } var iV = UIImageView(image: imageArray[0]) iV.animationImages = imageArray iV.animationDuration = 60 iV.startAnimating() let vC = UIViewController() vC.view.addSubview(iV) PlaygroundPage.current.liveView = vC
mit
2aebae9fe8e7d63b38df2e751d4456c5
26.480952
135
0.593934
4.274074
false
false
false
false
TENDIGI/Obsidian-UI-iOS
src/CameraViewController.swift
1
7883
// // AFLCameraViewController.swift // Alfredo // // Created by Eric Kunz on 8/13/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation import AVFoundation import Photos import MobileCoreServices protocol ALFCameraViewControllerDelegate { /// Tells the delegate that the close button was tapped. func didCancelImageCapture(_ cameraController: ALFCameraViewController) /// Tells the delegate that an image has been selected. func cameraControllerDidSelectImage(_ camera: ALFCameraViewController, image: UIImage) } /** Provides a camera for still image capture. Customizaton is available for the capture button (captureButton), flash control button (flashButton), resolution (sessionPreset), and which camera to use (devicePosition). After an image is captured the user is presented with buttons to accept or reject the photo. */ class ALFCameraViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { /** The delegate of a AFLCameraViewController must adopt the AFLCameraViewControllerDelegate protocol. Methods of the protocol allow the delegate to respond to an image selection or cancellation. */ var delegate: ALFCameraViewControllerDelegate? fileprivate var camera: Camera ///Flash firing control. false by defualt. var flashOn = false /// The resolution to set the camera to. var sessionPreset = AVCaptureSession.Preset.vga640x480 /// Determines if image is saved to photo library on capture. Default is false. var savesToPhotoLibrary = false /// The tint color of the photo library picker's navigation bar var pickerNavigationBarTintColor = UIColor.white /// The button that is pressed to capture an image. @IBOutlet weak var captureButton: UIButton? /// The button that determines whether the flash fires while capturing an image. @IBOutlet weak var flashButton: UIButton? /// The view for live camera preview @IBOutlet weak var cameraPreview: UIView? /// Where the camera capture animation happens @IBOutlet weak var flashView: UIView? /// View for image review post image capture @IBOutlet weak fileprivate var capturedImageReview: UIImageView? /// User taps this to pass photo to delegate @IBOutlet weak var acceptButton: UIButton? /// Tapping this returns the user to capturing an image. @IBOutlet weak var rejectButton: UIButton? /// A button that dismisses the camera. @IBOutlet weak var exitButton: UIButton? /// Title at the top of the view. @IBOutlet weak var titleLabel: UILabel? /// A Label shown after image capture - /// e.g. Would you like to use this photo? or. May I take your hat, sir? @IBOutlet weak var questionLabel: UILabel? /// An instruction label below the camera preview @IBOutlet weak var hintDescriptionLabel: UILabel? /// Opens the photo library @IBOutlet weak var photoLibraryButton: UIButton? fileprivate var capturedImage: UIImage? fileprivate var inputCameraConnection: AVCaptureConnection? init(useFrontCamera: Bool) { camera = Camera(useFrontCamera: useFrontCamera, sessionPreset: sessionPreset) super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.isStatusBarHidden = true flashButton?.isHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.isStatusBarHidden = false teardownSession() } override var prefersStatusBarHidden : Bool { return true } fileprivate func teardownSession() { camera.tearDownSession() } // MARK: Actions fileprivate func showAcceptOrRejectView(_ show: Bool) { UIView.animate(withDuration: 1, animations: { () -> Void in self.captureButton?.isHidden = show self.flashButton?.isHidden = show self.cameraPreview?.isHidden = show self.capturedImageReview?.isHidden = !show self.acceptButton?.isHidden = !show self.rejectButton?.isHidden = !show }) } fileprivate func didPressAcceptPhotoButton() { delegate?.cameraControllerDidSelectImage(self, image: capturedImage!) teardownSession() } fileprivate func didPressRejectPhotoButton() { capturedImage = nil showAcceptOrRejectView(false) } fileprivate func didPressExitButton() { delegate?.didCancelImageCapture(self) teardownSession() } fileprivate func takePicture() { camera.captureImage { (capturedImage) -> Void in self.displayCapturedImage(capturedImage) } } fileprivate func displayCapturedImage(_ image: UIImage) { capturedImageReview?.image = image showAcceptOrRejectView(true) } fileprivate func flashCamera() { let key = "opacity" let flash = CABasicAnimation(keyPath: key) flash.fromValue = 0 flash.toValue = 1 flash.autoreverses = true flash.isRemovedOnCompletion = true flash.duration = 0.15 flashView?.layer.add(flash, forKey: key) } // MARK: Photo Library fileprivate func didTapPhotoLibraryButton() { presentPhotoLibraryPicker() } fileprivate func loadPhotoLibraryPreviewImage() { if let libraryButton = photoLibraryButton { Photos().latestAsset(libraryButton.frame.size, contentMode: .aspectFill, completion: { (image: UIImage?) -> Void in libraryButton.imageView?.image = image }) } } fileprivate func configurePhotoLibraryButtonForNoAccess() { photoLibraryButton?.backgroundColor = UIColor.black } fileprivate func presentPhotoLibraryPicker() { let imagePicker = UIImagePickerController() imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary // let availableTypes = UIImagePickerController.availableMediaTypesForSourceType(imagePicker.sourceType) imagePicker.mediaTypes = [kUTTypeImage as String] imagePicker.delegate = self imagePicker.modalPresentationStyle = UIModalPresentationStyle.fullScreen imagePicker.modalTransitionStyle = UIModalTransitionStyle.coverVertical imagePicker.navigationBar.barTintColor = pickerNavigationBarTintColor imagePicker.navigationBar.isTranslucent = false self.present(imagePicker, animated: true, completion: nil) } // MARK: Image Picker Delegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) { dismiss(animated: true, completion: { () -> Void in self.capturedImage = image self.displayCapturedImage(image) UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) }) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: { () -> Void in UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) }) } // MARK: Navigation Controller Delegate func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) } }
mit
e51759bcbd42a0330d9157f85b4dcdcc
32.402542
140
0.700875
5.297715
false
false
false
false
toddisaacs/TIImageViewer
TIImageViewer/ImageViewController.swift
1
9606
// // ModalViewController.swift // ImageViewController // // Created by Todd Isaacs on 12/18/16. // import UIKit public class ImageViewController: UIViewController { var scrollView:UIScrollView! var imageView:UIImageView! var delegate:ImageViewControllerDelegate? var image:UIImage? { didSet { print("image set") } } var scrollViewTopConstraint: NSLayoutConstraint! var scrollViewBottomConstraint: NSLayoutConstraint! var scrollViewLeadingConstraint: NSLayoutConstraint! var scrollViewTrailingConstraint: NSLayoutConstraint! var imageViewTopConstraint: NSLayoutConstraint! var imageViewBottomConstraint: NSLayoutConstraint! var imageViewLeadingConstraint: NSLayoutConstraint! var imageViewTrailingConstraint: NSLayoutConstraint! var doubleTap: UITapGestureRecognizer! var flickDown: UISwipeGestureRecognizer! var imageFullSizeImageZoomScale:CGFloat = 1.0 var imageFullSizeViewZoomScale:CGFloat = 1.0 var index:Int = 0 required public init(image: UIImage) { super.init(nibName: nil, bundle: nil) //adjust the layout margins to remove them self.view.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) self.image = image setupScrollView() addScrollViewConstraints() setupImageView(image: image) addImageViewConstraints() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() resizeViewToFit(animated: false) centerView() } func show(fromController: UIViewController, fullScreen:Bool) { fromController.definesPresentationContext = !fullScreen fromController.present(self, animated: true, completion: nil) resizeViewToFit(animated: false) } private func setupScrollView() { scrollView = UIScrollView() scrollView.delegate = self scrollView.minimumZoomScale = 0.25 scrollView.maximumZoomScale = 10 scrollView.zoomScale = 1 scrollView.showsHorizontalScrollIndicator = true scrollView.showsVerticalScrollIndicator = true scrollView.isUserInteractionEnabled = true scrollView.isScrollEnabled = true scrollView.contentInsetAdjustmentBehavior = .never let swipeDownGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeDown)) swipeDownGesture.direction = .down swipeDownGesture.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(swipeDownGesture) view.addSubview(scrollView) } private func setupImageView(image: UIImage) { //not sure why we need both lines but the frame is not correct without it imageView = UIImageView(image: image) imageView.image = image imageView.contentMode = UIView.ContentMode.scaleAspectFit imageView.isUserInteractionEnabled = true scrollView.addSubview(imageView) doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap)) doubleTap.numberOfTapsRequired = 2 imageView.addGestureRecognizer(doubleTap) } private func addScrollViewConstraints() { scrollViewTopConstraint = NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0) scrollViewBottomConstraint = NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) scrollViewLeadingConstraint = NSLayoutConstraint(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0) scrollViewTrailingConstraint = NSLayoutConstraint(item: scrollView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0) //disable auto resizing mask scrollView.translatesAutoresizingMaskIntoConstraints = false scrollViewTopConstraint.isActive = true scrollViewBottomConstraint.isActive = true scrollViewLeadingConstraint.isActive = true scrollViewTrailingConstraint.isActive = true } private func addImageViewConstraints() { imageViewTopConstraint = NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 0) imageViewBottomConstraint = NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1, constant: 0) imageViewLeadingConstraint = NSLayoutConstraint(item: imageView, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leading, multiplier: 1, constant: 0) imageViewTrailingConstraint = NSLayoutConstraint(item: imageView, attribute: .trailing, relatedBy: .equal, toItem: scrollView, attribute: .trailing, multiplier: 1, constant: 0) //disable auto resizing mask imageView.translatesAutoresizingMaskIntoConstraints = false //activate imageViewTopConstraint.isActive = true imageViewBottomConstraint.isActive = true imageViewLeadingConstraint.isActive = true imageViewTrailingConstraint.isActive = true } @objc func handleSwipeDown(gesture: UISwipeGestureRecognizer) { dismiss(animated: true, completion: nil) } @objc func handleDoubleTap(gesture: UITapGestureRecognizer) { zoomFullScreenHeightOrWidth() } func zoomFullScreenHeightOrWidth() { if scrollView.zoomScale > imageFullSizeImageZoomScale { resizeViewToFit(animated: true) centerView() } else { scrollView.setZoomScale(imageFullSizeViewZoomScale, animated: true) } } public func resizeViewToFit(animated: Bool) { //calculate zoom that shows the whole image let widthScale = view.bounds.width / imageView.bounds.width let heightScale = view.bounds.height / imageView.bounds.height imageFullSizeImageZoomScale = min(heightScale, widthScale) imageFullSizeViewZoomScale = max(heightScale, widthScale) scrollView.setZoomScale(imageFullSizeImageZoomScale, animated: animated) } public func centerView() { let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) * 0.5, 0) let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) * 0.5, 0) self.scrollView.contentInset = UIEdgeInsets.init(top: offsetY, left: offsetX, bottom: 0, right: 0) } } extension ImageViewController: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } public func scrollViewDidZoom(_ scrollView: UIScrollView) { centerView() } public func scrollViewDidScroll(_ scrollView: UIScrollView) { view.layoutIfNeeded() } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { delegate?.imageViewWillBeginZooming?() } } @objc protocol ImageViewControllerDelegate: class { @objc optional func imageViewWillBeginZooming() }
mit
1735894eb342fba07699d0c1e786cae4
35.524715
102
0.551426
6.812766
false
false
false
false
darrinhenein/firefox-ios
Storage/StorageTests/TestJoinedHistoryVisits.swift
3
6037
import Foundation import XCTest class TestJoinedHistoryVisits : XCTestCase { var db: SwiftData! private func addSite(history: JoinedHistoryVisitsTable, url: String, title: String, s: Bool = true) -> Site { var inserted = -1; let site = Site(url: url, title: title) db.withConnection(.ReadWrite) { connection -> NSError? in var err: NSError? = nil inserted = history.insert(connection, item: (site, nil), err: &err) return err } if s { XCTAssert(inserted >= 0, "Inserted succeeded \(url) \(title)") } else { XCTAssert(inserted == -1, "Inserted failed") } return site } private func addVisit(history: JoinedHistoryVisitsTable, site: Site, s: Bool = true) -> Visit { var inserted = -1; let visit = Visit(site: site, date: NSDate()) db.withConnection(.ReadWrite) { connection -> NSError? in var err: NSError? = nil inserted = history.insert(connection, item: (nil, visit), err: &err) return err } if s { XCTAssert(inserted >= 0, "Inserted succeeded") } else { XCTAssert(inserted == -1, "Inserted failed") } return visit } private func checkSites(history: JoinedHistoryVisitsTable, options: QueryOptions?, urls: [String: String], s: Bool = true) { db.withConnection(.ReadOnly) { connection -> NSError? in var cursor = history.query(connection, options: options) XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)") XCTAssertEqual(cursor.count, urls.count, "cursor has right num of entries") for index in 0..<cursor.count { if let (site, visit) = cursor[index] as? (Site,Visit) { XCTAssertNotNil(site, "cursor has a site for entry") let title = urls[site.url] XCTAssertNotNil(title, "Found url") XCTAssertEqual(site.title, title!, "Found right title") } else { XCTAssertFalse(true, "Should not be nil...") } } return nil } } private func checkSitesOrdered(history: JoinedHistoryVisitsTable, options: QueryOptions?, urls: [(String, String)], s: Bool = true) { db.withConnection(.ReadOnly) { connection -> NSError? in var cursor = history.query(connection, options: options) XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)") XCTAssertEqual(cursor.count, urls.count, "cursor has right num of entries") for index in 0..<urls.count { let d = cursor[index] println("Found \(d)") let (site, visit) = cursor[index] as (site: Site, visit: Visit) XCTAssertNotNil(s, "cursor has a site for entry") let info = urls[index] XCTAssertEqual(site.url, info.0, "Found url") XCTAssertEqual(site.title, info.1, "Found right title") } return nil } } private func clear(history: JoinedHistoryVisitsTable, item: (site:Site?, visit:Visit?)? = nil, s: Bool = true) { var deleted = -1; db.withConnection(.ReadWrite) { connection -> NSError? in var err: NSError? = nil deleted = history.delete(connection, item: item, err: &err) return nil } if s { XCTAssert(deleted >= 0, "Delete worked") } else { XCTAssert(deleted == -1, "Delete failed") } } // This is a very basic test. Adds an entry. Retrieves it, and then clears the database func testJoinedHistoryVisitsTable() { let files = MockFiles() self.db = SwiftData(filename: files.get("test.db", basePath: nil)!) let h = JoinedHistoryVisitsTable(files: files) self.db.withConnection(SwiftData.Flags.ReadWriteCreate, cb: { (db) -> NSError? in h.create(db, version: 2) return nil }) // Add a few visits to some sites self.addSite(h, url: "url1", title: "title1") let site = self.addSite(h, url: "url1", title: "title1") self.addSite(h, url: "url2", title: "title2") self.addSite(h, url: "url2", title: "title2") // Query all the sites self.checkSites(h, options: nil, urls: ["url1": "title1", "url2": "title2"]) // Query all the sites sorted by data let opts = QueryOptions() opts.sort = .LastVisit self.checkSitesOrdered(h, options: opts, urls: [("url2", "title2"), ("url1", "title1")]) // Adding an already existing site should update the title self.addSite(h, url: "url1", title: "title1 alt") self.checkSites(h, options: nil, urls: ["url1": "title1 alt", "url2": "title2"]) // Adding an visit with an existing site should update the title let site2 = Site(url: site.url, title: "title1 second alt") let visit = self.addVisit(h, site: site2) self.checkSites(h, options: nil, urls: ["url1": "title1 second alt", "url2": "title2"]) // Filtering should default to matching urls let options = QueryOptions() options.filter = "url2" self.checkSites(h, options: options, urls: ["url2": "title2"]) // Clearing with a site should remove the site self.clear(h, item: (site, nil)) self.checkSites(h, options: nil, urls: ["url2": "title2"]) // Clearing with a site should remove the visit self.clear(h, item: (nil, visit)) self.checkSites(h, options: nil, urls: ["url2": "title2"]) // Clearing with nil should remove everything self.clear(h) self.checkSites(h, options: nil, urls: [String: String]()) files.remove("test.db", basePath: nil) } }
mpl-2.0
e81dc9c536aeeb18f65d48e89169bc2f
40.07483
137
0.576942
4.192361
false
false
false
false
fromkk/FKValidator
Classes/Rules/FKValidatorRuleExactLength.swift
1
794
// // FKValidatorRuleExactLength.swift // FKValidator // // Created by Kazuya Ueoka on 2015/12/13. // Copyright © 2015年 fromKK. All rights reserved. // import Foundation open class FKValidatorRuleExactLength :FKValidatorRule { var length :Int = 0 public init(length :Int) { super.init() self.length = length } public init(length :Int, errorMessage :String) { super.init(errorMessage : errorMessage) self.length = length } override func _commonInit() { self.errorCode = .exactLength } open override func run(_ value: String) -> Bool { if (super.run(value)) { return true } return self.length == value.count } }
mit
6fa0527280b17ea499a20be767b9a4a4
18.292683
54
0.567636
4.141361
false
false
false
false
instacrate/tapcrate-api
Sources/api/Stripe/Stripe.swift
1
6937
// // Stripe.swift // Stripe // // Created by Hakon Hanesand on 12/23/16. // // import JSON import HTTP import Transport import Vapor import Foundation fileprivate func merge(query: [String: NodeRepresentable?], with metadata: [String: NodeRepresentable]) -> [String: NodeRepresentable] { var arguments = metadata.map { (arg: (key: String, value: NodeRepresentable)) -> (String, NodeRepresentable) in let (key, value) = arg return ("metadata[\(key)]", value) } arguments.append(contentsOf: query.filter { (arg) -> Bool in return arg.value != nil }.map { (arg: ((key: String, value: NodeRepresentable))) -> (String, NodeRepresentable) in return (arg.key, arg.value) }) return Dictionary(uniqueKeysWithValues: arguments) } public final class Stripe { public static let publicToken = "pk_test_lGLXGH2jjEx7KFtPmAYz39VA" public static let secretToken = "sk_test_WceGrEBqnYpjCYF6exFBXvnf" private static let base = HTTPClient(baseURL: "https://api.stripe.com/v1/", publicToken, secretToken) private static let uploads = HTTPClient(baseURL: "https://uploads.stripe.com/v1/", publicToken, secretToken) public static func createToken() throws -> Token { return try base.post("tokens", query: ["card[number]" : 4242424242424242, "card[exp_month]" : 12, "card[exp_year]" : 2017, "card[cvc]" : 123]) } public static func createToken(for customer: String, representing card: String, on account: String = Stripe.publicToken) throws -> Token { return try base.post("tokens", query: ["customer" : customer, "card" : card], token: account) } public static func createNormalAccount(email: String, source: String, local_id: Int?, on account: String = Stripe.secretToken) throws -> StripeCustomer { let defaultQuery = ["source" : source] let query = local_id.flatMap { merge(query: defaultQuery, with: ["id" : "\($0)"]) } ?? defaultQuery return try base.post("customers", query: query, token: account) } public static func createManagedAccount(email: String, local_id: Int?) throws -> StripeAccount { let defaultQuery: [String: NodeRepresentable] = ["managed" : true, "country" : "US", "email" : email, "legal_entity[type]" : "company"] let query = local_id.flatMap { merge(query: defaultQuery, with: ["id" : "\($0)"]) } ?? defaultQuery return try base.post("accounts", query: query, token: Stripe.secretToken) } public static func associate(source: String, withStripe id: String, under secretKey: String = Stripe.secretToken) throws -> Card { return try base.post("customers/\(id)/sources", query: ["source" : source], token: secretKey) } public static func createPlan(with price: Double, name: String, interval: Interval, on account: String = Stripe.publicToken) throws -> Plan { let parameters = ["id" : "\(UUID().uuidString)", "amount" : "\(Int(price * 100))", "currency" : "usd", "interval" : interval.rawValue, "name" : name] return try base.post("plans", query: parameters, token: account) } public static func update(customer id: String, parameters: [String : String]) throws-> StripeCustomer { return try base.post("customer/\(id)", query: parameters) } public static func subscribe(user userId: String, to planId: String, with frequency: Interval = .month, oneTime: Bool, cut: Double, coupon: String? = nil, metadata: [String : NodeRepresentable], under publishableKey: String) throws -> StripeSubscription { let subscription: StripeSubscription = try base.post("subscriptions", query: merge(query: ["customer" : userId, "plan" : planId, "application_fee_percent" : cut, "coupon" : coupon], with: metadata), token: publishableKey) if oneTime { let json = try base.delete("/subscriptions/\(subscription.id)", query: ["at_period_end" : true]) guard json["cancel_at_period_end"]?.bool == true else { throw Abort.custom(status: .internalServerError, message: json.makeNode(in: emptyContext).object?.description ?? "Fuck.") } } return subscription } public static func charge(source: String, for price: Double, withFee percent: Double, under account: String = Stripe.publicToken) throws -> Charge { return try base.post("charges", query: ["amount" : Int(price * 100), "currency" : "USD", "application_fee" : Int(price * percent * 100), "source" : source], token: account) } public static func createCoupon(code: String) throws -> StripeCoupon { return try base.post("coupons", query: ["duration": Duration.once.rawValue, "id" : code, "percent_off" : 5, "max_redemptions" : 1]) } public static func paymentInformation(for customer: String, under account: String = Stripe.secretToken) throws -> [Card] { return try base.getList("customers/\(customer)/sources", query: ["object" : "card"], token: account) } public static func customerInformation(for customer: String) throws -> StripeCustomer { return try base.get("customers/\(customer)") } public static func makerInformation(for maker: String) throws -> StripeAccount { return try base.get("accounts/\(maker)") } public static func transfers(for secretKey: String) throws -> [Transfer] { return try base.getList("transfers", token: secretKey) } public static func delete(payment: String, from customer: String) throws -> JSON { return try base.delete("customers/\(customer)/sources/\(payment)") } public static func disputes() throws -> [Dispute] { return try base.getList("disputes") } public static func verificationRequiremnts(for country: CountryCode) throws -> Country { return try base.get("country_specs/\(country.rawValue.uppercased())") } public static func acceptedTermsOfService(for user: String, ip: String) throws -> StripeAccount { return try base.post("accounts/\(user)", query: ["tos_acceptance[date]" : "\(Int(Date().timeIntervalSince1970))", "tos_acceptance[ip]" : ip]) } public static func updateInvoiceMetadata(for id: Int, invoice_id: String) throws -> Invoice { return try base.post("invoices/\(invoice_id)", query: ["metadata[orders]" : "\(id)"]) } public static func updateAccount(id: String, parameters: [String : String]) throws -> StripeAccount { return try base.post("accounts/\(id)", query: parameters) } public static func getCard(with id: String, for customer: String) throws -> Card { return try base.get("customers/\(customer)/sources/\(id)") } public static func checkForError(in json: JSON, from resource: String) throws { if json["error"] != nil { throw StripeHTTPError(node: json.node, code: .internalServerError, resource: resource) } } }
mit
21855d996136604adcf10fcc8ce57451
47.51049
259
0.66412
4.104734
false
false
false
false
Bajocode/ExploringModerniOSArchitectures
Architectures/MVP/Presenter/MovieResultsPresenter.swift
1
2874
// // MovieResultsPresenter.swift // Architectures // // Created by Fabijan Bajo on 29/05/2017. // // import Foundation class MovieResultsPresenter: ResultsViewPresenter { // MARK: - Properties unowned private let view: ResultsView private var movies = [Movie]() var objectsCount: Int { return movies.count } struct PresentableInstance: Transportable { let title: String let thumbnailURL: URL let fullSizeURL: URL let ratingText: String let releaseDateText: String } private let releaseDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-mm-dd" return formatter }() // MARK: - Initializers required init(view: ResultsView) { self.view = view } // Cannot Mock because of movies private access control convenience init(view: ResultsView, testableMovies: [Movie]) { self.init(view: view) movies = testableMovies } // MARK: - Methods func presentableInstance(index: Int) -> Transportable { let movie = movies[index] let thumbnailURL = TmdbAPI.tmdbImageURL(forSize: .thumb, path: movie.posterPath) let fullSizeURL = TmdbAPI.tmdbImageURL(forSize: .full, path: movie.posterPath) let ratingText = String(format: "%.1f", movie.averageRating) let dateObject = releaseDateFormatter.date(from: movie.releaseDate) let releaseDateText = releaseDateFormatter.string(from: dateObject!) return PresentableInstance(title: movie.title, thumbnailURL: thumbnailURL, fullSizeURL: fullSizeURL, ratingText: ratingText, releaseDateText: releaseDateText) } func presentNewObjects() { DataManager.shared.fetchNewTmdbObjects(withType: .movie) { (result) in switch result { case let .success(parsables): self.movies = parsables as! [Movie] case let .failure(error): print(error) } self.view.reloadCollectionData() } } func presentDetail(for indexPath: IndexPath) { let presentable = presentableInstance(index: indexPath.row) as! PresentableInstance let vc = DetailViewController() vc.imageURL = presentable.fullSizeURL vc.navigationItem.title = presentable.title view.show(vc) } } // MARK: - CollectionViewConfigurable extension MovieResultsPresenter: CollectionViewConfigurable { // MARK: - Properties // Required var cellID: String { return "MovieCell" } var widthDivisor: Double { return 2.0 } var heightDivisor: Double { return 2.5 } // Optional var interItemSpacing: Double? { return 1 } var lineSpacing: Double? { return 1 } var bottomInset: Double? { return 49 } }
mit
3a16a0191753c22790e7d00fefc4ee21
29.903226
166
0.646138
4.658023
false
false
false
false
SnipDog/ETV
ETV/Moudel/Main/MainTabBarController.swift
1
1898
// // MainTabBarController.swift // ETV // // Created by Heisenbean on 16/9/29. // Copyright © 2016年 Heisenbean. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.tabBar.barTintColor = UIColor.white setVc() } func setVc() { addChildViewController("Home", "首页", UIImage(named:"menu_homepage_24x24_"), UIImage(named:"menu_homepage_sel_24x24_")) addChildViewController("Game", "游戏", UIImage(named:"menu_youxi_24x24_"), UIImage(named:"menu_youxi_sel_24x24_")) addChildViewController("Entertainment", "娱乐", UIImage(named:"menu_yule_24x24_"),UIImage(named: "menu_yule_sel_24x24_")) addChildViewController("Goddess", "女神", UIImage(named:"menu_goddess_normal_20x21_"), UIImage(named:"menu_goddess_20x21_")) addChildViewController("Mine", "我的", UIImage(named:"menu_mine_24x24_"), UIImage(named:"menu_mine_sel_24x24_")) } fileprivate func addChildViewController(_ sbName: String, _ title: String, _ image: UIImage?, _ selectImage: UIImage?) { let vc = UIStoryboard.initialViewController(sbName) let nav = MainNavigationController(rootViewController: vc) vc.title = title nav.title = title nav.tabBarItem.image = image!.withRenderingMode(.alwaysOriginal) nav.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.init(colorLiteralRed: 36/255.0, green: 205/255.0, blue: 137/255.0, alpha: 1.0)], for: .selected) nav.tabBarItem.selectedImage = selectImage!.withRenderingMode(.alwaysOriginal) addChildViewController(nav) } // MARK: Others override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
598205d54f583da589f69ff970d87a29
38.893617
182
0.6816
4.222973
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/ComOperation/Controller/SAMForSaleOrderDetailController.swift
1
4721
// // SAMForSaleOrderDetailController.swift // SaleManager // // Created by LiuXiaoming on 17/2/22. // Copyright © 2017年 YZH. All rights reserved. // import UIKit private let SAMForSaleDetailCellReuseIdentifier = "SAMForSaleDetailCellReuseIdentifier" class SAMForSaleOrderDetailController: UIViewController { class func instance(forSaleModels: NSMutableArray, selectedIndex: IndexPath) -> SAMForSaleOrderDetailController { let vc = SAMForSaleOrderDetailController() vc.forSaleModels = forSaleModels vc.selectedIndex = selectedIndex return vc } override func viewDidLoad() { super.viewDidLoad() setupData() setupTableView() } //MARK: - 处理数据 fileprivate func setupData() { let selectedForSaleModel = forSaleModels![selectedIndex!.item] as! SAMForSaleModel let selectedCGUnitName = selectedForSaleModel.CGUnitName titleContentLabel.text = selectedForSaleModel.CGUnitName let orderModelArr = forSaleModels?.compare(modelKeys: ["CGUnitName"], searchItems: [selectedCGUnitName]) orderDetaiModels = NSMutableArray() for obj in orderModelArr! { //当前要判断的待售数据模型 let forSaleModel = obj as! SAMForSaleModel //计算统计数据 countP += 1 countM += forSaleModel.meter //与待售详情数据数组进行匹配 let arr = orderDetaiModels!.compare(modelKeys: ["CGUnitName"], searchItems: [forSaleModel.CGUnitName]) if arr.count == 0 { //数据模型数组里面没有这个名称的数据模型 let forSaleDetailModel = SAMForSaleOrderDetailModel() forSaleDetailModel.productIDName = forSaleModel.productIDName forSaleDetailModel.mashuText.append(String(format: "%.1f", forSaleModel.meter)) orderDetaiModels?.add(forSaleDetailModel) }else { //数据模型数组里面有这个名称的数据模型 let model = arr[0] as! SAMForSaleOrderDetailModel model.mashuText.append(String(format: ",%.1f", forSaleModel.meter)) } } //赋值统计数据 countLabel.text = String(format: "%d/%.1f", countP, countM) } //MARK: - 设置tableView fileprivate func setupTableView() { tableView.showsVerticalScrollIndicator = false tableView.dataSource = self tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension //注册CELL tableView.register(UINib.init(nibName: "SAMForSaleDetailCell", bundle: nil), forCellReuseIdentifier: SAMForSaleDetailCellReuseIdentifier) } //MARK: - 用户点击事件 @IBAction func dismissBtnClick(_ sender: UIButton) { dismiss(animated: true, completion: nil) } //MARK: - 属性 fileprivate var forSaleModels: NSMutableArray? fileprivate var selectedIndex: IndexPath? fileprivate var orderDetaiModels: NSMutableArray? fileprivate var countP = 0 fileprivate var countM = 0.0 //MARK: - XIB链接属性 @IBOutlet weak var titleContentLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var countLabel: UILabel! //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("SAMForSaleOrderDetailController", owner: self, options: nil)![0] as! UIView } } //MARK: - vistTableView数据源 extension SAMForSaleOrderDetailController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orderDetaiModels!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SAMForSaleDetailCellReuseIdentifier) as! SAMForSaleDetailCell //传递数据模型 let model = orderDetaiModels![indexPath.row] as! SAMForSaleOrderDetailModel cell.forSaleDetailModel = model return cell } }
apache-2.0
71b8e70d1b424b5111d255f3c0f36593
34.507937
145
0.65646
4.878953
false
false
false
false
RxSwiftCommunity/RxWebKit
Example/ObservingJSEventViewController.swift
1
1679
// // ObservingJSEventViewController.swift // Example // // Created by Jesse Hao on 2019/4/1. // Copyright © 2019 RxSwift Community. All rights reserved. // import UIKit import WebKit import RxWebKit import RxSwift import RxCocoa fileprivate let html = """ <!DOCTYPE html> <meta content="width=device-width,user-scalable=no" name="viewport"> <html> <body> <p>Click the button to display a confirm box.</p> <button onclick="sendScriptMessage()">Send!</button> <p id="demo"></p> <script> function sendScriptMessage() { window.webkit.messageHandlers.RxWebKitScriptMessageHandler.postMessage('Hello RxWebKit') } </script> </body> </html> """ class ObservingJSEventViewController : UIViewController { let bag = DisposeBag() let webview = WKWebView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(webview) webview.configuration.userContentController.rx.scriptMessage(forName: "RxWebKitScriptMessageHandler").bind { [weak self] scriptMessage in guard let message = scriptMessage.body as? String else { return } let alert = UIAlertController(title: "JS Event Observed", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) self?.present(alert, animated: true) }.disposed(by: self.bag) webview.loadHTMLString(html, baseURL: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let originY = UIApplication.shared.statusBarFrame.maxY webview.frame = CGRect(x: 0, y: originY, width: view.bounds.width, height: view.bounds.height) } }
mit
4ffe6b2e4ca599e40ac58894fa3e7fff
27.440678
145
0.695471
4.163772
false
false
false
false
KrishMunot/swift
test/Constraints/assignment.swift
10
1283
// RUN: %target-parse-verify-swift struct X { } struct Y { } struct WithOverloadedSubscript { subscript(i: Int) -> X { get {} set {} } subscript(i: Int) -> Y { get {} set {} } } func test_assign() { var a = WithOverloadedSubscript() a[0] = X() a[0] = Y() } var i: X var j: X var f: Y func getXY() -> (X, Y) {} var ift : (X, Y) var ovl = WithOverloadedSubscript() var slice: [X] i = j (i, f) = getXY() (i, f) = ift (i, f) = (i, f) (ovl[0], ovl[0]) = ift (ovl[0], ovl[0]) = (i, f) (_, ovl[0]) = (i, f) (ovl[0], _) = (i, f) _ = (i, f) slice[7] = i slice[7] = f // expected-error{{cannot assign value of type 'Y' to type 'X'}} slice[7] = _ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} func value(_ x: Int) {} func value2(_ x: inout Int) {} value2(&_) // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} value(_) // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} // <rdar://problem/23798944> = vs. == in Swift if string character count statement causes segmentation fault func f23798944() { let s = "" if s.characters.count = 0 { // expected-error {{cannot assign to property: 'count' is a get-only property}} } }
apache-2.0
59505886ccfae83d26c8ba2eef085644
20.745763
109
0.590803
2.81978
false
false
false
false
thislooksfun/Tavi
Tavi/LoginViewController.swift
1
4273
// // LoginViewController.swift // GitClient // // Created by thislooksfun on 7/6/15. // Copyright (c) 2015 thislooksfun. All rights reserved. // import UIKit class LoginViewController: PortraitViewController, UITextFieldDelegate { @IBOutlet var username: UITextField! @IBOutlet var password: UITextField! @IBOutlet var spinner: UIView! @IBOutlet var message: UILabel! @IBOutlet var onePassSignInButton: UIButton! private var authType: GithubAPI.Auth2fType! override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.username.delegate = self self.password.delegate = self self.username.becomeFirstResponder() let onePassAvailable = OnePasswordExtension.sharedExtension().isAppExtensionAvailable() self.onePassSignInButton.hidden = !onePassAvailable if onePassAvailable { self.username.rightView = UIView(frame: CGRectMake(0, 0, 37, self.username.frame.height)) self.username.rightViewMode = .Always } // Testing stuff self.username.text = "thislooksfun" self.password.becomeFirstResponder() self.password.text = "Coco6=:)" // self.submit() } // Submits the form func submit() { guard Connection.connectedToNetwork() else { self.performSegueWithIdentifier("NoConnection", sender: nil) return } self.spinner.hidden = false self.message.hidden = true GithubAPI.auth(user: username.text!, pass: password.text!, callback: authCallback, forceMainThread: true) } // Checks what state the auth exited in, and performs the appropriate action private func authCallback(state: GithubAPI.AuthState, type: GithubAPI.Auth2fType?) { self.spinner.hidden = true switch (state) { case .Success: //Sucessfully logged in - segue to the main screen let auth = self.navigationController!.parentViewController as! AuthViewController auth.signedIn() case .BadLogin: //Bad login - invalid username/password - try again self.message.text = "Invalid username/email/password" self.message.hidden = false case .Needs2fAuth: //Needs two factor authentication - segue to the 2fauth screen let auth = self.navigationController!.parentViewController as! AuthViewController auth.showBackButton() self.authType = type! self.performSegueWithIdentifier("Do2fAuth", sender: nil) case .Other: //Unknown error - try again self.message.text = "An unknown error occurred.\nPlease try again later." self.message.hidden = false } } // Clears the text fields func clear() { self.username.text = nil self.password.text = nil } func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField == self.username) { //Select next text field self.password.becomeFirstResponder() return false } else if (textField == self.password) { guard self.username.text!.characters.count > 0 && self.password.text!.characters.count > 0 else { return false } self.password.resignFirstResponder() self.submit() } return true } @IBAction func onePasswordLogin(sender: AnyObject) { OnePasswordExtension.sharedExtension().findLoginForURLString("https://github.com", forViewController:self, sender:sender) { (loginDictionary: [NSObject: AnyObject]?, error: NSError?) in guard let dict = loginDictionary else { return } if (dict.count == 0) { if (error != nil && error!.code != Int(AppExtensionErrorCodeCancelledByUser)) { print("Error invoking 1Password App Extension for find login: \(error)"); } return; } self.password.becomeFirstResponder() self.username.text = (dict[AppExtensionUsernameKey] as? String) ?? "" self.password.text = (dict[AppExtensionPasswordKey] as? String) ?? "" } } //Makes it so touching outside the text field causes the keyboard to go away override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.username.resignFirstResponder() self.password.resignFirstResponder() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //Set auth2f user, pass, and authType let auth2f = segue.destinationViewController as? Auth2fViewController auth2f?.setUser(self.username.text!, andPass: self.password.text!) auth2f?.setAuthType(self.authType) } }
gpl-3.0
035d5eb21ebc68cb92892774f89537e9
28.888112
125
0.727592
3.832287
false
false
false
false
RobotRebels/ios-common
ToboxCommon/Extensions/NSDate+Extension.swift
1
1979
// // NSDate+Extension.swift // ToboxCommon // // Created by Ilya Lunkin on 31/10/2016. // Copyright © 2016 Tobox. All rights reserved. // import Foundation public extension NSDate { struct Formatter { static let iso8601: NSDateFormatter = { let formatter = NSDateFormatter() formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601) formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxx" return formatter }() } public var iso8601: String { return Formatter.iso8601.stringFromDate(self) } public func format(format: String, locale: Bool = false) -> String { let dateFormatter = NSDateFormatter() if locale { dateFormatter.locale = NSLocale.currentLocale() } dateFormatter.dateFormat = format return dateFormatter.stringFromDate(self) } public func secondsFrom(date: NSDate) -> Int { return NSCalendar.currentCalendar().components(.Second, fromDate: date, toDate: self, options: []).second } public func addYears(years: Int)-> NSDate { let dateComponents = NSDateComponents() dateComponents.year = years return NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: NSCalendarOptions.WrapComponents)! } } public func > (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate } public func < (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate } public func >= (lhs: NSDate, rhs: NSDate) -> Bool { return (lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate) || (lhs == rhs) } public func <= (lhs: NSDate, rhs: NSDate) -> Bool { return (lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate) || (lhs == rhs) }
mit
de7c94aa36ab88a04ec89aed100bf9e2
31.966667
136
0.720425
4.557604
false
false
false
false
nlambson/CanvasKit
CanvasKitTests/Model Tests/CKILiveAssessmentResultsTests.swift
3
1883
// // CKILiveAssessmentResultsTests.swift // CanvasKit // // Created by Nathan Lambson on 8/7/14. // Copyright (c) 2014 Instructure. All rights reserved. // import UIKit import XCTest class CKILiveAssessmentResultsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testJSONModelConversion() { let liveAssessmentDictionary = Helpers.loadJSONFixture("live_assessment") as NSDictionary let liveAssessmentResult = CKILiveAssessmentResult(fromJSONDictionary: liveAssessmentDictionary) XCTAssertEqual(liveAssessmentResult.id!, "42", "LiveAssessmentResult id did not parse correctly") XCTAssertTrue(liveAssessmentResult.passed, "LiveAssessmentResult passed did not parse correctly") let formatter = ISO8601DateFormatter() formatter.includeTime = true var date = formatter.dateFromString("2014-05-13T00:01:57-06:00") XCTAssertEqual(liveAssessmentResult.assessedAt!, date,"LiveAssessmentResult assessedAt did not parse correctly") XCTAssertEqual(liveAssessmentResult.assessedUserID!, "42", "LiveAssessmentResult assessedUserID did not parse correctly") XCTAssertEqual(liveAssessmentResult.assessorUserID!, "23", "LiveAssessmentResult assessorUserID did not parse correctly") XCTAssertEqual(CKILiveAssessmentResult.keyForJSONAPIContent()!, "results", "LiveAssessmentResult keyForJSONAPIContent was not parsed correctly") XCTAssertEqual(liveAssessmentResult.path!, "/api/v1/results/42", "LiveAssessmentResult path did not parse correctly") } }
mit
4b8b12b0fd9fc69617e4874a9fae3ea5
44.926829
152
0.737653
4.389277
false
true
false
false
matteogobbi/DBPathRecognizer
PathRecognizer/ViewController.swift
1
5528
// // ViewController.swift // PathRecognizer // // Created by Didier Brun on 15/03/2015. // Copyright (c) 2015 Didier Brun. All rights reserved. // import UIKit class ViewController: UIViewController { var rawPoints:[Int] = [] var recognizer:DBPathRecognizer? @IBOutlet weak var renderView: RenderView! @IBOutlet weak var letter: UILabel! enum FilterOperation { case Maximum case Minimum } enum FilterField { case LastPointX case LastPointY } override func viewDidLoad() { let recognizer = DBPathRecognizer(sliceCount: 8, deltaMove: 16.0) let maxy3 = ViewController.customFilter(self)(.Maximum, .LastPointY, 0.3) let miny3 = ViewController.customFilter(self)(.Minimum, .LastPointY, 0.3) let maxy7 = ViewController.customFilter(self)(.Maximum, .LastPointY, 0.7) let miny7 = ViewController.customFilter(self)(.Minimum, .LastPointY, 0.7) recognizer.addModel(PathModel(directions: [7, 1], datas:"A")) recognizer.addModel(PathModel(directions: [2,6,0,1,2,3,4,0,1,2,3,4], datas:"B")) recognizer.addModel(PathModel(directions: [4,3,2,1,0], datas:"C")) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2,3,4], datas:"D", filter:miny7)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,4,3,2,1,0], datas:"E")) recognizer.addModel(PathModel(directions: [4,2], datas:"F")) recognizer.addModel(PathModel(directions: [4,3,2,1,0,7,6,5,0], datas:"G", filter:miny3)) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2], datas:"H")) recognizer.addModel(PathModel(directions: [2], datas:"I")) recognizer.addModel(PathModel(directions: [2,3,4], datas:"J")) recognizer.addModel(PathModel(directions: [3,4,5,6,7,0,1], datas:"K")) recognizer.addModel(PathModel(directions: [2,0], datas:"L")) recognizer.addModel(PathModel(directions: [6,1,7,2], datas:"M")) recognizer.addModel(PathModel(directions: [6,1,6], datas:"N")) recognizer.addModel(PathModel(directions: [4,3,2,1,0,7,6,5,4], datas:"O", filter:maxy3)) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2,3,4], datas:"P", filter:maxy7)) recognizer.addModel(PathModel(directions: [4,3,2,1,0,7,6,5,4,0], datas:"Q", filter: maxy3)) recognizer.addModel(PathModel(directions: [2,6,7,0,1,2,3,4,1], datas:"R")) recognizer.addModel(PathModel(directions: [4,3,2,1,0,1,2,3,4], datas:"S")) recognizer.addModel(PathModel(directions: [0,2], datas:"T")) recognizer.addModel(PathModel(directions: [2,1,0,7,6], datas:"U")) recognizer.addModel(PathModel(directions: [1,7,0], datas:"V")) recognizer.addModel(PathModel(directions: [2,7,1,6], datas:"W")) recognizer.addModel(PathModel(directions: [1,0,7,6,5,4,3], datas:"X")) recognizer.addModel(PathModel(directions: [2,1,0,7,6,2,3,4,5,6,7], datas:"Y")) recognizer.addModel(PathModel(directions: [0,3,0], datas:"Z")) self.recognizer = recognizer super.viewDidLoad() } func minLastY(cost:Int, infos:PathInfos, minValue:Double)->Int { var py:Double = (Double(infos.deltaPoints.last!.y) - Double(infos.boundingBox.top)) / Double(infos.height) return py < minValue ? Int.max : cost } func maxLastY(cost:Int, infos:PathInfos, maxValue:Double)->Int { var py:Double = (Double(infos.deltaPoints.last!.y) - Double(infos.boundingBox.top)) / Double(infos.height) return py > maxValue ? Int.max : cost } func customFilter(operation:FilterOperation,_ field:FilterField, _ value:Double)(cost:Int, infos:PathInfos)->Int { var pvalue:Double switch field { case .LastPointY: pvalue = (Double(infos.deltaPoints.last!.y) - Double(infos.boundingBox.top)) / Double(infos.height) case .LastPointX: pvalue = (Double(infos.deltaPoints.last!.x) - Double(infos.boundingBox.left)) / Double(infos.width) } switch operation { case .Maximum: return pvalue > value ? Int.max : cost case .Minimum: return pvalue < value ? Int.max : cost } } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { rawPoints = [] let touch = touches.allObjects[0] as UITouch let location = touch.locationInView(view) rawPoints.append(Int(location.x)) rawPoints.append(Int(location.y)) } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { let touch = touches.allObjects[0] as UITouch let location = touch.locationInView(view) rawPoints.append(Int(location.x)) rawPoints.append(Int(location.y)) self.renderView.pointsToDraw = rawPoints } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { var path:Path = Path() path.addPointFromRaw(rawPoints) var gesture:PathModel? = self.recognizer!.recognizePath(path) if gesture != nil { letter.text = gesture!.datas as? String } else { letter.text = "-" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
3599323fc56d98a68c8a84beb892b3c1
36.100671
118
0.611614
3.580311
false
false
false
false
mvader/advent-of-code
2020/11/02.swift
1
1676
import Foundation enum Tile { case floor case emptySeat case occupiedSeat } typealias Grid = [[Tile]] let directions = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] func visibleOccupiedSeats(_ grid: Grid, x: Int, y: Int) -> Int { var occupied = 0 for (dx, dy) in directions { var (x, y) = (x + dx, y + dy) while x >= 0 && y >= 0 && y < grid.count && x < grid[y].count { if grid[y][x] == .floor { x += dx y += dy } else { if grid[y][x] == .occupiedSeat { occupied += 1 } break } } } return occupied } func nextState(_ grid: Grid) -> Grid { var result = grid for y in 0..<grid.count { for x in 0..<grid[y].count { switch grid[y][x] { case .emptySeat: if visibleOccupiedSeats(grid, x: x, y: y) == 0 { result[y][x] = .occupiedSeat } case .occupiedSeat: if visibleOccupiedSeats(grid, x: x, y: y) >= 5 { result[y][x] = .emptySeat } default: continue } } } return result } func findStableState(_ grid: Grid) -> Grid { var current = grid var next = nextState(grid) while current != next { current = next next = nextState(current) } return next } func occupiedSeats(_ grid: Grid) -> Int { return grid.reduce(0) { (acc, row) in return acc + row.filter { $0 == .occupiedSeat }.count } } let grid: Grid = try String(contentsOfFile: "./input.txt", encoding: .utf8) .components(separatedBy: "\n") .map { $0.map { $0 == Character(".") ? Tile.floor : Tile.emptySeat } } print(occupiedSeats(findStableState(grid)))
mit
4807b68d1c4f0dc07c0e0eaadbded321
18.952381
75
0.53401
3.162264
false
false
false
false
csnu17/My-Blognone-apps
myblognone/AppDelegate.swift
1
2291
// // AppDelegate.swift // myblognone // // Created by Kittisak Phetrungnapha on 12/18/2559 BE. // Copyright © 2559 Kittisak Phetrungnapha. All rights reserved. // import UIKit import Fabric import Crashlytics import FBSDKCoreKit import ForceUpdateSDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let iTunesID = "1191248877" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Fabric.with([Crashlytics.self]) FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) setupForceUpdate() setupNavigationBar() setupStatusBar() NewsListWireFrame.setNewsListInterface(to: window ?? UIWindow(frame: UIScreen.main.bounds)) return true } func applicationDidBecomeActive(_ application: UIApplication) { FBSDKAppEvents.activateApp() FUSManager.sharedInstance().checkLatestAppStoreVersion() } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) } private func setupStatusBar() { UIApplication.shared.statusBarStyle = .lightContent } private func setupNavigationBar() { UINavigationBar.appearance().barTintColor = UIColor(hexString: UIColor.navigationBarBackground) UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.font: UIFont.fontForNavigationBarTitle(), NSAttributedStringKey.foregroundColor: UIColor.white ] if #available(iOS 11.0, *) { UINavigationBar.appearance().largeTitleTextAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.fontForLargeNavigationBarTitle() ] } } private func setupForceUpdate() { FUSManager.sharedInstance().itunesId = iTunesID } }
mit
a37d7cafaa2c5ab867b5264e88e0b103
33.179104
144
0.696943
5.739348
false
false
false
false
weareopensource/Sample-iOS_Swift_Instagram
Sample-Swift_instagram/APIController.swift
1
2687
// // APIController.swift // Sample-Swift_instagram // // Created by RYPE on 14/05/2015. // Copyright (c) 2015 weareopensource. All rights reserved. // import Foundation /**************************************************************************************************/ // Protocol /**************************************************************************************************/ protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } /**************************************************************************************************/ // Class /**************************************************************************************************/ class APIController { /*************************************************/ // Main /*************************************************/ // Var /*************************/ var delegate: APIControllerProtocol // init /*************************/ init(delegate: APIControllerProtocol) { self.delegate = delegate } /*************************************************/ // Functions /*************************************************/ func get(path: String) { let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if(error != nil) { // If there is an error in the web request, print it to the console print(error!.localizedDescription) } //let jsonString = "{\"name\":\"Fred\", \"age\":40}" //let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)! do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary //print(jsonResult["data"]) if let results = jsonResult["data"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } catch let error as NSError { print(error.description) } }) // The task is just an object with all these properties set // In order to actually make the web request, we need to "resume" task.resume() } func instagram() { get("https://api.instagram.com/v1/users/\(GlobalConstants.TwitterInstaUserId)/media/recent/?access_token=\(GlobalConstants.TwitterInstaAccessToken)") } }
mit
20a586fbdde7e1cabfb2a4a284643887
32.17284
157
0.43022
6.521845
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift
30
26360
// // BarChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class BarChartRenderer: BarLineScatterCandleBubbleRenderer { fileprivate class Buffer { var rects = [CGRect]() } open weak var dataProvider: BarChartDataProvider? public init(dataProvider: BarChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } // [CGRect] per dataset fileprivate var _buffers = [Buffer]() open override func initBuffers() { if let barData = dataProvider?.barData { // Matche buffers count to dataset count if _buffers.count != barData.dataSetCount { while _buffers.count < barData.dataSetCount { _buffers.append(Buffer()) } while _buffers.count > barData.dataSetCount { _buffers.removeLast() } } for i in stride(from: 0, to: barData.dataSetCount, by: 1) { let set = barData.dataSets[i] as! IBarChartDataSet let size = set.entryCount * (set.isStacked ? set.stackSize : 1) if _buffers[i].rects.count != size { _buffers[i].rects = [CGRect](repeating: CGRect(), count: size) } } } else { _buffers.removeAll() } } fileprivate func prepareBuffer(dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider, let barData = dataProvider.barData, let animator = animator else { return } let barWidthHalf = barData.barWidth / 2.0 let buffer = _buffers[index] var bufferIndex = 0 let containsStacks = dataSet.isStacked let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) let phaseY = animator.phaseY var barRect = CGRect() var x: Double var y: Double for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1) { guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue } let vals = e.yValues x = e.x y = e.y if !containsStacks || vals == nil { let left = CGFloat(x - barWidthHalf) let right = CGFloat(x + barWidthHalf) var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if top > 0 { top *= CGFloat(phaseY) } else { bottom *= CGFloat(phaseY) } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top buffer.rects[bufferIndex] = barRect bufferIndex += 1 } else { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // fill the stack for k in 0 ..< vals!.count { let value = vals![k] if value == 0.0 && (posY == 0.0 || negY == 0.0) { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value yStart = y } else if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } let left = CGFloat(x - barWidthHalf) let right = CGFloat(x + barWidthHalf) var top = isInverted ? (y <= yStart ? CGFloat(y) : CGFloat(yStart)) : (y >= yStart ? CGFloat(y) : CGFloat(yStart)) var bottom = isInverted ? (y >= yStart ? CGFloat(y) : CGFloat(yStart)) : (y <= yStart ? CGFloat(y) : CGFloat(yStart)) // multiply the height of the rect with the phase top *= CGFloat(phaseY) bottom *= CGFloat(phaseY) barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top buffer.rects[bufferIndex] = barRect bufferIndex += 1 } } } } open override func drawData(context: CGContext) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } for i in 0 ..< barData.dataSetCount { guard let set = barData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is IBarChartDataSet) { fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset") } drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i) } } } fileprivate var _barShadowRectBuffer: CGRect = CGRect() open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider, let viewPortHandler = self.viewPortHandler else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) prepareBuffer(dataSet: dataSet, index: index) trans.rectValuesToPixel(&_buffers[index].rects) let borderWidth = dataSet.barBorderWidth let borderColor = dataSet.barBorderColor let drawBorder = borderWidth > 0.0 context.saveGState() // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { guard let animator = animator, let barData = dataProvider.barData else { return } let barWidth = barData.barWidth let barWidthHalf = barWidth / 2.0 var x: Double = 0.0 for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1) { guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue } x = e.x _barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf) _barShadowRectBuffer.size.width = CGFloat(barWidth) trans.rectValueToPixel(&_barShadowRectBuffer) if !viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width) { continue } if !viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x) { break } _barShadowRectBuffer.origin.y = viewPortHandler.contentTop _barShadowRectBuffer.size.height = viewPortHandler.contentHeight context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(_barShadowRectBuffer) } } let buffer = _buffers[index] // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { for j in stride(from: 0, to: buffer.rects.count, by: 1) { let barRect = buffer.rects[j] if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(barRect) } } let isSingleColor = dataSet.colors.count == 1 if isSingleColor { context.setFillColor(dataSet.color(atIndex: 0).cgColor) } for j in stride(from: 0, to: buffer.rects.count, by: 1) { let barRect = buffer.rects[j] if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } if !isSingleColor { // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. context.setFillColor(dataSet.color(atIndex: j).cgColor) } context.fill(barRect) if drawBorder { context.setStrokeColor(borderColor.cgColor) context.setLineWidth(borderWidth) context.stroke(barRect) } } context.restoreGState() } open func prepareBarHighlight( x: Double, y1: Double, y2: Double, barWidthHalf: Double, trans: Transformer, rect: inout CGRect) { let left = x - barWidthHalf let right = x + barWidthHalf let top = y1 let bottom = y2 rect.origin.x = CGFloat(left) rect.origin.y = CGFloat(top) rect.size.width = CGFloat(right - left) rect.size.height = CGFloat(bottom - top) trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0) } open override func drawValues(context: CGContext) { // if values are drawn if isDrawingValuesAllowed(dataProvider: dataProvider) { guard let dataProvider = dataProvider, let viewPortHandler = self.viewPortHandler, let barData = dataProvider.barData, let animator = animator else { return } var dataSets = barData.dataSets let valueOffsetPlus: CGFloat = 4.5 var posOffset: CGFloat var negOffset: CGFloat let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled for dataSetIndex in 0 ..< barData.dataSetCount { guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue } if !shouldDrawValues(forDataSet: dataSet) { continue } let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueFont = dataSet.valueFont let valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if isInverted { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } let buffer = _buffers[dataSetIndex] guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY let iconsOffset = dataSet.iconsOffset // if only single values are drawn (sum) if !dataSet.isStacked { for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let rect = buffer.rects[j] let x = rect.origin.x + rect.size.width / 2.0 if !viewPortHandler.isInBoundsRight(x) { break } if !viewPortHandler.isInBoundsY(rect.origin.y) || !viewPortHandler.isInBoundsLeft(x) { continue } let val = e.y if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( val, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler), xPos: x, yPos: val >= 0.0 ? (rect.origin.y + posOffset) : (rect.origin.y + rect.size.height + negOffset), font: valueFont, align: .center, color: dataSet.valueTextColorAt(j)) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = x var py = val >= 0.0 ? (rect.origin.y + posOffset) : (rect.origin.y + rect.size.height + negOffset) px += iconsOffset.x py += iconsOffset.y ChartUtils.drawImage( context: context, image: icon, x: px, y: py, size: icon.size) } } } else { // if we have stacks var bufferIndex = 0 for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue } let vals = e.yValues let rect = buffer.rects[bufferIndex] let x = rect.origin.x + rect.size.width / 2.0 // we still draw stacked bars, but there is one non-stacked in between if vals == nil { if !viewPortHandler.isInBoundsRight(x) { break } if !viewPortHandler.isInBoundsY(rect.origin.y) || !viewPortHandler.isInBoundsLeft(x) { continue } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler), xPos: x, yPos: rect.origin.y + (e.y >= 0 ? posOffset : negOffset), font: valueFont, align: .center, color: dataSet.valueTextColorAt(index)) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = x var py = rect.origin.y + (e.y >= 0 ? posOffset : negOffset) px += iconsOffset.x py += iconsOffset.y ChartUtils.drawImage( context: context, image: icon, x: px, y: py, size: icon.size) } } else { // draw stack values let vals = vals! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for k in 0 ..< vals.count { let value = vals[k] var y: Double if value == 0.0 && (posY == 0.0 || negY == 0.0) { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value } else if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY))) } trans.pointValuesToPixel(&transformed) for k in 0 ..< transformed.count { let val = vals[k] let drawBelow = (val == 0.0 && negY == 0.0 && posY > 0.0) || val < 0.0 let y = transformed[k].y + (drawBelow ? negOffset : posOffset) if !viewPortHandler.isInBoundsRight(x) { break } if !viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x) { continue } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( vals[k], entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler), xPos: x, yPos: y, font: valueFont, align: .center, color: dataSet.valueTextColorAt(index)) } if let icon = e.icon, dataSet.isDrawIconsEnabled { ChartUtils.drawImage( context: context, image: icon, x: x + iconsOffset.x, y: y + iconsOffset.y, size: icon.size) } } } bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count) } } } } } /// Draws a value at the specified x and y position. open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor) { ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color]) } open override func drawExtras(context: CGContext) { } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } context.saveGState() var barRect = CGRect() for high in indices { guard let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet, set.isHighlightEnabled else { continue } if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry { if !isInBoundsX(entry: e, dataSet: set) { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) context.setFillColor(set.highlightColor.cgColor) context.setAlpha(set.highlightAlpha) let isStack = high.stackIndex >= 0 && e.isStacked let y1: Double let y2: Double if isStack { if dataProvider.isHighlightFullBarEnabled { y1 = e.positiveSum y2 = -e.negativeSum } else { let range = e.ranges?[high.stackIndex] y1 = range?.from ?? 0.0 y2 = range?.to ?? 0.0 } } else { y1 = e.y y2 = 0.0 } prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect) setHighlightDrawPos(highlight: high, barRect: barRect) context.fill(barRect) } } context.restoreGState() } /// Sets the drawing position of the highlight object based on the riven bar-rect. internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect) { high.setDraw(x: barRect.midX, y: barRect.origin.y) } }
mit
2fb931eea80cce19828322077349e584
36.657143
186
0.394537
6.688658
false
false
false
false
multinerd/Mia
Mia/Resources/Fonts/FontKit.swift
1
6307
// MARK: - public struct FontKit { public typealias FontLoadedHandler = ([String]) -> Void private typealias FontPath = String private typealias FontName = String private typealias FontExtension = String private typealias FontTuple = (path: FontPath, name: FontName, ext: FontExtension) // MARK: *** Configuration *** public struct Configuration { /// Determines whether debug messages will be logged. Defaults to false. public static var debugMode = false } // MARK: *** Properties *** /// A list of loaded fonts. public static var loadedFonts: [String] = [] // MARK: *** Public Methods *** /// Load all fonts found in a Mia. public static func loadMia() { let bundle = Bundle(for: MiaDummy.self) loadFontsInBundle(withPath: bundle.bundlePath) loadFontsFromBundlesFoundInBundle(path: bundle.bundlePath) } /// Load all fonts found in a specific bundle. /// /// - Parameters: /// - bundle: The bundle to check. Defaults to `Bundle.main` /// - handler: The callback with a [String] containing the loaded font's names. public static func load(bundle: Bundle = Bundle.main, completion handler: FontLoadedHandler? = nil) { loadFontsInBundle(withPath: bundle.bundlePath) loadFontsFromBundlesFoundInBundle(path: bundle.bundlePath) handler?(loadedFonts) } // MARK: *** Private Methods *** /// Loads all fonts found in a bundle. /// /// - Parameter path: The absolute path to the bundle. private static func loadFontsInBundle(withPath path: String) { do { let contents = try FileManager.default.contentsOfDirectory(atPath: path) as [String] let loadedFonts = fonts(fromPath: path, withContents: contents) if !loadedFonts.isEmpty { for font in loadedFonts { loadFont(font: font) } } else { FontKit.debug(message: "No fonts were found in the bundle path: \(path).") } } catch let error as NSError { FontKit.debug(message: "There was an error loading from the bundle.\nPath: \(path).\nError: \(error)") } } /// Loads all fonts found in a bundle that is loaded within another bundle. /// /// - Parameter path: The absolute path to the bundle. private static func loadFontsFromBundlesFoundInBundle(path: String) { do { let contents = try FileManager.default.contentsOfDirectory(atPath: path) for item in contents { if let url = URL(string: path), item.contains(".bundle") { let urlPathString = url.appendingPathComponent(item).absoluteString loadFontsInBundle(withPath: urlPathString) } } } catch let error as NSError { FontKit.debug(message: "There was an error accessing the bundle. \nPath: \(path).\nError: \(error)") } } /// Loads a specific font. /// /// - Parameter font: The font to load. private static func loadFont(font: FontTuple) { let path: FontPath = font.path let name: FontName = font.name let ext: FontExtension = font.ext let url = URL(fileURLWithPath: path).appendingPathComponent(name).appendingPathExtension(ext) var fontError: Unmanaged<CFError>? guard let data = try? Data(contentsOf: url) as CFData, let dataProvider = CGDataProvider(data: data) else { guard let fontError = fontError?.takeRetainedValue() else { FontKit.debug(message: "Failed to load font '\(name)'.") return } let errorDescription = CFErrorCopyDescription(fontError) FontKit.debug(message: "Failed to load font '\(name)': \(String(describing: errorDescription))") return } /// Fixes deadlocking issue caused by `let fontRef = CGFont(dataProvider)`. /// Temporary fix until rdar://18778790 is addressed. /// Open Radar at http://www.openradar.me/18778790 /// Discussion at https://github.com/ArtSabintsev/FontBlaster/issues/19 _ = UIFont() let fontRef = CGFont(dataProvider) if CTFontManagerRegisterGraphicsFont(fontRef!, &fontError) { if let postScriptName = fontRef?.postScriptName { FontKit.debug(message: "Successfully loaded font: '\(postScriptName)'.") loadedFonts.append(String(postScriptName)) } } else if let fontError = fontError?.takeRetainedValue() { let errorDescription = CFErrorCopyDescription(fontError) FontKit.debug(message: "Failed to load font '\(name)': \(String(describing: errorDescription))") } } /// Parses all of the fonts into their name and extension components. /// /// - Parameters: /// - path: The absolute path to the font file. /// - contents: The contents of an Bundle as an array of String objects. /// - Returns: An array of `FontTuple` containing all fonts found at the specified path. private static func fonts(fromPath path: String, withContents contents: [String]) -> [FontTuple] { func splitComponents(fromName name: String) -> (FontName, FontExtension) { let components = name.split { $0 == "." }.map { String($0) } return (components[0], components[1]) } var fonts = [ FontTuple ]() for fontName in contents { var parsedFont: (FontName, FontExtension)? if fontName.contains(".ttf") || fontName.contains(".otf") { parsedFont = splitComponents(fromName: fontName) } if let parsedFont = parsedFont { let font: FontTuple = (path, parsedFont.0, parsedFont.1) fonts.append(font) } } return fonts } /// Prints debug messages to the console if debugEnabled is set to true. /// /// - Parameter message: The message to print to the console. static func debug(message: String) { Rosewood.Framework.print(framework: "FontKit", message: message, debugEnabled: Configuration.debugMode) } }
mit
ec238f0fa229d95aa2386a928dd12bbf
37.224242
115
0.614872
4.752826
false
false
false
false
jum/Charts
Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift
8
5902
// // BarChartDataEntry.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class BarChartDataEntry: ChartDataEntry { /// the values the stacked barchart holds private var _yVals: [Double]? /// the ranges for the individual stack values - automatically calculated private var _ranges: [Range]? /// the sum of all negative values this entry (if stacked) contains private var _negativeSum: Double = 0.0 /// the sum of all positive values this entry (if stacked) contains private var _positiveSum: Double = 0.0 public required init() { super.init() } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double) { super.init(x: x, y: y) } /// Constructor for normal bars (not stacked). public convenience init(x: Double, y: Double, data: Any?) { self.init(x: x, y: y) self.data = data } /// Constructor for normal bars (not stacked). public convenience init(x: Double, y: Double, icon: NSUIImage?) { self.init(x: x, y: y) self.icon = icon } /// Constructor for normal bars (not stacked). public convenience init(x: Double, y: Double, icon: NSUIImage?, data: Any?) { self.init(x: x, y: y) self.icon = icon self.data = data } /// Constructor for stacked bar entries. @objc public init(x: Double, yValues: [Double]) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues)) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack @objc public convenience init(x: Double, yValues: [Double], icon: NSUIImage?) { self.init(x: x, yValues: yValues) self.icon = icon } /// Constructor for stacked bar entries. One data object for whole stack @objc public convenience init(x: Double, yValues: [Double], data: Any?) { self.init(x: x, yValues: yValues) self.data = data } /// Constructor for stacked bar entries. One data object for whole stack @objc public convenience init(x: Double, yValues: [Double], icon: NSUIImage?, data: Any?) { self.init(x: x, yValues: yValues) self.icon = icon self.data = data } @objc open func sumBelow(stackIndex :Int) -> Double { guard let yVals = _yVals else { return 0 } var remainder: Double = 0.0 var index = yVals.count - 1 while (index > stackIndex && index >= 0) { remainder += yVals[index] index -= 1 } return remainder } /// The sum of all negative values this entry (if stacked) contains. (this is a positive number) @objc open var negativeSum: Double { return _negativeSum } /// The sum of all positive values this entry (if stacked) contains. @objc open var positiveSum: Double { return _positiveSum } @objc open func calcPosNegSum() { (_negativeSum, _positiveSum) = _yVals?.reduce(into: (0,0)) { (result, y) in if y < 0 { result.0 += -y } else { result.1 += y } } ?? (0,0) } /// Splits up the stack-values of the given bar-entry into Range objects. /// /// - Parameters: /// - entry: /// - Returns: @objc open func calcRanges() { guard let values = yValues, !values.isEmpty else { return } if _ranges == nil { _ranges = [Range]() } else { _ranges!.removeAll() } _ranges!.reserveCapacity(values.count) var negRemain = -negativeSum var posRemain: Double = 0.0 for value in values { if value < 0 { _ranges!.append(Range(from: negRemain, to: negRemain - value)) negRemain -= value } else { _ranges!.append(Range(from: posRemain, to: posRemain + value)) posRemain += value } } } // MARK: Accessors /// the values the stacked barchart holds @objc open var isStacked: Bool { return _yVals != nil } /// the values the stacked barchart holds @objc open var yValues: [Double]? { get { return self._yVals } set { self.y = BarChartDataEntry.calcSum(values: newValue) self._yVals = newValue calcPosNegSum() calcRanges() } } /// The ranges of the individual stack-entries. Will return null if this entry is not stacked. @objc open var ranges: [Range]? { return _ranges } // MARK: NSCopying open override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! BarChartDataEntry copy._yVals = _yVals copy.y = y copy._negativeSum = _negativeSum copy._positiveSum = _positiveSum return copy } /// Calculates the sum across all values of the given stack. /// /// - Parameters: /// - vals: /// - Returns: private static func calcSum(values: [Double]?) -> Double { guard let values = values else { return 0.0 } var sum = 0.0 for f in values { sum += f } return sum } }
apache-2.0
7d41dab7843f7a46009805e8608ce390
24.66087
100
0.534734
4.420974
false
false
false
false
carlynorama/learningSwift
Projects/Swift3GuessingGame/Swift3GuessingGame/AppDelegate.swift
1
4610
// // AppDelegate.swift // Swift3GuessingGame // // Created by Carlyn Maw on 8/22/16. // Copyright © 2016 carlynorama. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Swift3GuessingGame") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
unlicense
120f7aa556362f5b686e2d6c13aa5cea
48.55914
285
0.687134
5.797484
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Search/Indexing/PartialUpdate.swift
1
9317
// // PartialUpdate.swift // // // Created by Vladislav Fitc on 27/03/2020. // import Foundation public struct PartialUpdate: Equatable { typealias Storage = [Attribute: Action] let storage: Storage } extension PartialUpdate: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (Attribute, Action)...) { self.init(storage: .init(uniqueKeysWithValues: elements)) } } public extension PartialUpdate { /// Partially update an object field. /// - Parameter attribute: Attribute name to update /// - Parameter value: Updated value static func update(attribute: Attribute, value: JSON) -> Self { .init(storage: [attribute: .set(value)]) } } public extension PartialUpdate { /// Increment a numeric attribute /// - Parameter attribute: Attribute name to update /// - Parameter value: Value to increment by static func increment(attribute: Attribute, value: Int) -> Self { .operation(attribute: attribute, operation: .increment, value: .init(value)) } /// Increment a numeric attribute /// - Parameter attribute: Attribute name to update /// - Parameter value: Value to increment by static func increment(attribute: Attribute, value: Float) -> Self { .operation(attribute: attribute, operation: .increment, value: .init(value)) } /// Increment a numeric attribute /// - Parameter attribute: Attribute name to update /// - Parameter value: Value to increment by static func increment(attribute: Attribute, value: Double) -> Self { .operation(attribute: attribute, operation: .increment, value: .init(value)) } } public extension PartialUpdate { /** Increment a numeric integer attribute only if the provided value matches the current value, and otherwise ignore the whole object update. For example, if you pass an IncrementFrom value of 2 for the version attribute, but the current value of the attribute is 1, the engine ignores the update. If the object doesn’t exist, the engine only creates it if you pass an IncrementFrom value of 0. - Parameter attribute: Attribute name to update - Parameter value: Current value to increment */ static func incrementFrom(attribute: Attribute, value: Int) -> Self { .operation(attribute: attribute, operation: .incrementFrom, value: .init(value)) } /** Increment a numeric integer attribute only if the provided value is greater than the current value, and otherwise ignore the whole object update. For example, if you pass an IncrementSet value of 2 for the version attribute, and the current value of the attribute is 1, the engine updates the object. If the object doesn’t exist yet, the engine only creates it if you pass an IncrementSet value that’s greater than 0. - Parameter attribute: Attribute name to update - Parameter value: Value to set */ static func incrementSet(attribute: Attribute, value: Int) -> Self { .operation(attribute: attribute, operation: .incrementSet, value: .init(value)) } } public extension PartialUpdate { /// Decrement a numeric attribute /// - Parameter attribute: Attribute name to update /// - Parameter value: Value to decrement by static func decrement(attribute: Attribute, value: Int) -> Self { .operation(attribute: attribute, operation: .decrement, value: .init(value)) } /// Decrement a numeric attribute /// - Parameter attribute: Attribute name to update /// - Parameter value: Value to decrement by static func decrement(attribute: Attribute, value: Float) -> Self { .operation(attribute: attribute, operation: .decrement, value: .init(value)) } /// Decrement a numeric attribute /// - Parameter attribute: Attribute name to update /// - Parameter value: Value to decrement by static func decrement(attribute: Attribute, value: Double) -> Self { .operation(attribute: attribute, operation: .decrement, value: .init(value)) } } public extension PartialUpdate { /// Append a string element to an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to append /// - Parameter unique: If true, append an element only if it’s not already present static func add(attribute: Attribute, value: String, unique: Bool) -> Self { .operation(attribute: attribute, operation: unique ? .addUnique : .add, value: .init(value)) } /// Append a number element to an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to append /// - Parameter unique: If true, append an element only if it’s not already present static func add(attribute: Attribute, value: Int, unique: Bool) -> Self { .operation(attribute: attribute, operation: unique ? .addUnique : .add, value: .init(value)) } /// Append a number element to an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to append /// - Parameter unique: If true, append an element only if it’s not already present static func add(attribute: Attribute, value: Float, unique: Bool) -> Self { .operation(attribute: attribute, operation: unique ? .addUnique : .add, value: .init(value)) } /// Append a number element to an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to append /// - Parameter unique: If true, append an element only if it’s not already present static func add(attribute: Attribute, value: Double, unique: Bool) -> Self { .operation(attribute: attribute, operation: unique ? .addUnique : .add, value: .init(value)) } } public extension PartialUpdate { /// Remove all matching string elements from an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to remove static func remove(attribute: Attribute, value: String) -> Self { .operation(attribute: attribute, operation: .remove, value: .init(value)) } /// Remove all matching number elements from an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to remove static func remove(attribute: Attribute, value: Int) -> Self { .operation(attribute: attribute, operation: .remove, value: .init(value)) } /// Remove all matching number elements from an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to remove static func remove(attribute: Attribute, value: Float) -> Self { .operation(attribute: attribute, operation: .remove, value: .init(value)) } /// Remove all matching number elements from an array attribute /// - Parameter attribute: Attribute name of an array to update /// - Parameter value: Value to remove static func remove(attribute: Attribute, value: Double) -> Self { .operation(attribute: attribute, operation: .remove, value: .init(value)) } } extension PartialUpdate { static func operation(attribute: Attribute, operation: Operation.Kind, value: JSON) -> Self { return .init(storage: [attribute: .init(operation: operation, value: value)]) } } extension PartialUpdate: Codable { public init(from decoder: Decoder) throws { let rawStorage = try [String: Action](from: decoder) storage = rawStorage.mapKeys(Attribute.init) } public func encode(to encoder: Encoder) throws { try storage.mapKeys(\.rawValue).encode(to: encoder) } } extension PartialUpdate { struct Operation: Codable, Equatable { let kind: Kind let value: JSON enum CodingKeys: String, CodingKey { case value case kind = "_operation" } enum Kind: String, Codable { /// Increment a numeric attribute case increment = "Increment" /** Increment a numeric integer attribute only if the provided value matches the current value, and otherwise ignore the whole object update. For example, if you pass an IncrementFrom value of 2 for the version attribute, but the current value of the attribute is 1, the engine ignores the update. If the object doesn’t exist, the engine only creates it if you pass an IncrementFrom value of 0. */ case incrementFrom = "IncrementFrom" /** Increment a numeric integer attribute only if the provided value is greater than the current value, and otherwise ignore the whole object update. For example, if you pass an IncrementSet value of 2 for the version attribute, and the current value of the attribute is 1, the engine updates the object. If the object doesn’t exist yet, the engine only creates it if you pass an IncrementSet value that’s greater than 0. */ case incrementSet = "IncrementSet" /// Decrement a numeric attribute case decrement = "Decrement" /// Append a number or string element to an array attribute case add = "Add" /// Remove all matching number or string elements from an array attribute case remove = "Remove" /// Add a number or string element to an array attribute only if it’s not already present case addUnique = "AddUnique" } } }
mit
d3304638a900dcdf5dd5070b5ca21570
34.613027
123
0.705003
4.507759
false
false
false
false
iOSTestApps/SceneKitFrogger
4-Challenge/SCNFrogger-4/SCNFrogger/GameScene.swift
2
13096
// // GameScene.swift // SCNFrogger // // Created by Kim Pedersen on 02/12/14. // Copyright (c) 2014 RWDevCon. All rights reserved. // import SceneKit import SpriteKit class GameScene : SCNScene, SCNSceneRendererDelegate, SCNPhysicsContactDelegate, GameLevelSpawnDelegate { // MARK: Properties var sceneView: SCNView! var gameState = GameState.WaitingForFirstTap var camera: SCNNode! var cameraOrthographicScale = 0.5 var cameraOffsetFromPlayer = SCNVector3(x: 0.25, y: 1.25, z: 0.55) var levelData: GameLevel! let levelWidth: Int = 19 let levelHeight: Int = 50 var player: SCNNode! let playerScene = SCNScene(named: "assets.scnassets/Models/frog.dae") var playerGridCol = 7 var playerGridRow = 6 var playerChildNode: SCNNode! let carScene = SCNScene(named: "assets.scnassets/Models/car.dae") // MARK: Init init(view: SCNView) { sceneView = view super.init() initializeLevel() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func initializeLevel() { setupGestureRecognizersForView(sceneView) setupLights() setupLevel() setupPlayer() setupCamera() switchToWaitingForFirstTap() } func setupPlayer() { player = SCNNode() player.name = "Player" player.position = levelData.coordinatesForGridPosition(column: playerGridCol, row: playerGridRow) player.position.y = 0.2 let playerMaterial = SCNMaterial() playerMaterial.diffuse.contents = UIImage(named: "assets.scnassets/Textures/model_texture.tga") playerMaterial.locksAmbientWithDiffuse = false playerChildNode = playerScene!.rootNode.childNodeWithName("Frog", recursively: false)! playerChildNode.geometry!.firstMaterial = playerMaterial playerChildNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.075) player.addChildNode(playerChildNode) // Create a physicsbody for collision detection let playerPhysicsBodyShape = SCNPhysicsShape(geometry: SCNBox(width: 0.08, height: 0.08, length: 0.08, chamferRadius: 0.0), options: nil) playerChildNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Kinematic, shape: playerPhysicsBodyShape) playerChildNode.physicsBody!.categoryBitMask = PhysicsCategory.Player playerChildNode.physicsBody!.collisionBitMask = PhysicsCategory.Car rootNode.addChildNode(player) } func setupCamera() { camera = SCNNode() camera.name = "Camera" camera.position = cameraOffsetFromPlayer camera.camera = SCNCamera() camera.camera!.usesOrthographicProjection = true camera.camera!.orthographicScale = cameraOrthographicScale camera.camera!.zNear = 0.05 camera.camera!.zFar = 150.0 player.addChildNode(camera) camera.constraints = [SCNLookAtConstraint(target: player)] } func setupLevel() { levelData = GameLevel(width: levelWidth, height: levelHeight) levelData.setupLevelAtPosition(SCNVector3Zero, parentNode: rootNode) levelData.spawnDelegate = self } func setupGestureRecognizersForView(view: SCNView) { // Create tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") tapGesture.numberOfTapsRequired = 1 view.addGestureRecognizer(tapGesture) // Create swipe gesture recognizers let swipeUpGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:") swipeUpGesture.direction = UISwipeGestureRecognizerDirection.Up view.addGestureRecognizer(swipeUpGesture) let swipeDownGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:") swipeDownGesture.direction = UISwipeGestureRecognizerDirection.Down view.addGestureRecognizer(swipeDownGesture) let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:") swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.Left view.addGestureRecognizer(swipeLeftGesture) let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:") swipeRightGesture.direction = UISwipeGestureRecognizerDirection.Right view.addGestureRecognizer(swipeRightGesture) } func setupLights() { // Create ambient light let ambientLight = SCNLight() ambientLight.type = SCNLightTypeAmbient ambientLight.color = UIColor.whiteColor() let ambientLightNode = SCNNode() ambientLightNode.name = "AmbientLight" ambientLightNode.light = ambientLight rootNode.addChildNode(ambientLightNode) // Create an omni-directional light let omniLight = SCNLight() omniLight.type = SCNLightTypeOmni omniLight.color = UIColor.whiteColor() let omniLightNode = SCNNode() omniLightNode.name = "OmniLight" omniLightNode.light = omniLight omniLightNode.position = SCNVector3(x: -10.0, y: 20, z: 10.0) rootNode.addChildNode(omniLightNode) } // MARK: Game State func switchToWaitingForFirstTap() { gameState = GameState.WaitingForFirstTap // Fade in if let overlay = sceneView.overlaySKScene { overlay.enumerateChildNodesWithName("RestartLevel", usingBlock: { node, stop in node.runAction(SKAction.sequence( [SKAction.fadeOutWithDuration(0.5), SKAction.removeFromParent()])) }) // Tap to play animation icon let handNode = HandNode() handNode.position = CGPoint(x: sceneView.bounds.size.width * 0.5, y: sceneView.bounds.size.height * 0.2) overlay.addChild(handNode) } } func switchToPlaying() { gameState = GameState.Playing if let overlay = sceneView.overlaySKScene { // Remove tutorial overlay.enumerateChildNodesWithName("Tutorial", usingBlock: { node, stop in node.runAction(SKAction.sequence( [SKAction.fadeOutWithDuration(0.25), SKAction.removeFromParent()])) }) } } func switchToGameOver() { gameState = GameState.GameOver if let overlay = sceneView.overlaySKScene { let gameOverLabel = LabelNode( position: CGPoint(x: overlay.size.width/2.0, y: overlay.size.height/2.0), size: 24, color: .whiteColor(), text: "Game Over", name: "GameOver") overlay.addChild(gameOverLabel) let clickToRestartLabel = LabelNode( position: CGPoint(x: gameOverLabel.position.x, y: gameOverLabel.position.y - 24.0), size: 14, color: .whiteColor(), text: "Tap to restart", name: "GameOver") overlay.addChild(clickToRestartLabel) } physicsWorld.contactDelegate = nil } func switchToRestartLevel() { gameState = GameState.RestartLevel if let overlay = sceneView.overlaySKScene { // Fade out game over screen overlay.enumerateChildNodesWithName("GameOver", usingBlock: { node, stop in node.runAction(SKAction.sequence( [SKAction.fadeOutWithDuration(0.25), SKAction.removeFromParent()])) }) // Fade to black - and create a new level to play let blackNode = SKSpriteNode(color: UIColor.blackColor(), size: overlay.frame.size) blackNode.name = "RestartLevel" blackNode.alpha = 0.0 blackNode.position = CGPoint(x: sceneView.bounds.size.width/2.0, y: sceneView.bounds.size.height/2.0) overlay.addChild(blackNode) blackNode.runAction(SKAction.sequence([SKAction.fadeInWithDuration(0.5), SKAction.runBlock({ let newScene = GameScene(view: self.sceneView) newScene.physicsWorld.contactDelegate = newScene self.sceneView.scene = newScene self.sceneView.delegate = newScene })])) } } // MARK: Delegates func renderer(aRenderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: NSTimeInterval) { if gameState == GameState.Playing && playerGridRow == levelData.data.rowCount() - 6 { // player completed the level switchToGameOver() } } func physicsWorld(world: SCNPhysicsWorld, didBeginContact contact: SCNPhysicsContact) { if gameState == GameState.Playing { switchToGameOver() } } func spawnCarAtPosition(position: SCNVector3) { // Create a material using the model_texture.tga image let carMaterial = SCNMaterial() carMaterial.diffuse.contents = UIImage(named: "assets.scnassets/Textures/model_texture.tga") carMaterial.locksAmbientWithDiffuse = false // Create a clone of the Car node of the carScene - you need a clone because you need to add many cars let carNode = carScene!.rootNode.childNodeWithName("Car", recursively: false)!.clone() as SCNNode carNode.name = "Car" carNode.position = position // Set the material carNode.geometry!.firstMaterial = carMaterial // Create a physicsbody for collision detection let carPhysicsBodyShape = SCNPhysicsShape(geometry: SCNBox(width: 0.30, height: 0.20, length: 0.16, chamferRadius: 0.0), options: nil) carNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Kinematic, shape: carPhysicsBodyShape) carNode.physicsBody!.categoryBitMask = PhysicsCategory.Car carNode.physicsBody!.collisionBitMask = PhysicsCategory.Player rootNode.addChildNode(carNode) // Move the car let moveDirection: Float = position.x > 0.0 ? -1.0 : 1.0 let moveDistance = levelData.gameLevelWidth() let moveAction = SCNAction.moveBy(SCNVector3(x: moveDistance * moveDirection, y: 0.0, z: 0.0), duration: 10.0) let removeAction = SCNAction.runBlock { node -> Void in node.removeFromParentNode() } carNode.runAction(SCNAction.sequence([moveAction, removeAction])) // Rotate the car to move it in the right direction if moveDirection > 0.0 { carNode.rotation = SCNVector4(x: 0.0, y: 1.0, z: 0.0, w: 3.1415) } } // MARK: Touch Handling func handleTap(gesture: UIGestureRecognizer) { if let tapGesture = gesture as? UITapGestureRecognizer { movePlayerInDirection(.Forward) } } func handleSwipe(gesture: UIGestureRecognizer) { if let swipeGesture = gesture as? UISwipeGestureRecognizer { switch swipeGesture.direction { case UISwipeGestureRecognizerDirection.Up: movePlayerInDirection(.Forward) break case UISwipeGestureRecognizerDirection.Down: movePlayerInDirection(.Backward) break case UISwipeGestureRecognizerDirection.Left: movePlayerInDirection(.Left) break case UISwipeGestureRecognizerDirection.Right: movePlayerInDirection(.Right) break default: break } } } // MARK: Player movement func movePlayerInDirection(direction: MoveDirection) { switch gameState { case .WaitingForFirstTap: // Start playing switchToPlaying() movePlayerInDirection(direction) break case .Playing: // 1 - Check for player movement let gridColumnAndRowAfterMove = levelData.gridColumnAndRowAfterMoveInDirection(direction, currentGridColumn: playerGridCol, currentGridRow: playerGridRow) if gridColumnAndRowAfterMove.didMove == false { return } // 2 - Set the new player grid position playerGridCol = gridColumnAndRowAfterMove.newGridColumn playerGridRow = gridColumnAndRowAfterMove.newGridRow // 3 - Calculate the coordinates for the player after the move var newPlayerPosition = levelData.coordinatesForGridPosition(column: playerGridCol, row: playerGridRow) newPlayerPosition.y = 0.2 // 4 - Move player let moveAction = SCNAction.moveTo(newPlayerPosition, duration: 0.2) let jumpUpAction = SCNAction.moveBy(SCNVector3(x: 0.0, y: 0.2, z: 0.0), duration: 0.1) jumpUpAction.timingMode = SCNActionTimingMode.EaseOut let jumpDownAction = SCNAction.moveBy(SCNVector3(x: 0.0, y: -0.2, z: 0.0), duration: 0.1) jumpDownAction.timingMode = SCNActionTimingMode.EaseIn let jumpAction = SCNAction.sequence([jumpUpAction, jumpDownAction]) player.runAction(moveAction) playerChildNode.runAction(jumpAction) break case .GameOver: // Switch to tutorial switchToRestartLevel() break case .RestartLevel: // Switch to new level switchToWaitingForFirstTap() break } } func sizeOfBoundingBoxFromNode(node: SCNNode) -> (width: Float, height: Float, depth: Float) { var boundingBoxMin = SCNVector3Zero var boundingBoxMax = SCNVector3Zero let boundingBox = node.getBoundingBoxMin(&boundingBoxMin, max: &boundingBoxMax) let width = boundingBoxMax.x - boundingBoxMin.x let height = boundingBoxMax.y - boundingBoxMin.y let depth = boundingBoxMax.z - boundingBoxMin.z return (width, height, depth) } }
mit
fbbaaae5f410502e3400d1dfeb40260d
30.943902
160
0.68876
4.579021
false
false
false
false