repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Jnosh/swift
refs/heads/master
stdlib/public/core/AnyHashable.swift
apache-2.0
16
//===----------------------------------------------------------------------===// // // 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) /// } func _toCustomAnyHashable() -> AnyHashable? } internal protocol _AnyHashableBox { var _typeID: ObjectIdentifier { get } func _unbox<T : Hashable>() -> T? /// Determine whether values in the boxes are equivalent. /// /// - Returns: `nil` to indicate that the boxes store different types, so /// no comparison is possible. Otherwise, contains the result of `==`. func _isEqual(to: _AnyHashableBox) -> Bool? var _hashValue: Int { get } var _base: Any { get } func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool } internal struct _ConcreteHashableBox<Base : Hashable> : _AnyHashableBox { internal var _baseHashable: Base internal init(_ base: Base) { self._baseHashable = base } internal var _typeID: ObjectIdentifier { return ObjectIdentifier(type(of: self)) } 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 } 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 } } #if _runtime(_ObjC) // Retrieve the custom AnyHashable representation of the value after it // has been bridged to Objective-C. This mapping to Objective-C and back // turns a non-custom representation into a custom one, which is used as // the lowest-common-denominator for comparisons. func _getBridgedCustomAnyHashable<T>(_ value: T) -> AnyHashable? { let bridgedValue = _bridgeAnythingToObjectiveC(value) return (bridgedValue as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() } #endif /// 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" public struct AnyHashable { internal var _box: _AnyHashableBox internal var _usedCustomRepresentation: Bool /// 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 customRepresentation = (base as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() { self = customRepresentation self._usedCustomRepresentation = true return } self._box = _ConcreteHashableBox(0 as Int) self._usedCustomRepresentation = false _stdlib_makeAnyHashableUpcastingToHashableBaseType( base, storingResultInto: &self) } internal init<H : Hashable>(_usingDefaultRepresentationOf base: H) { self._box = _ConcreteHashableBox(base) self._usedCustomRepresentation = false } /// 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) // If we used a custom representation, bridge to Objective-C and then // attempt the cast from there. if _usedCustomRepresentation { 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 { // If they're equal, we're done. if let result = lhs._box._isEqual(to: rhs._box) { return result } #if _runtime(_ObjC) // If one used a custom representation but the other did not, bridge // the one that did *not* use the custom representation to Objective-C: // if the bridged result has a custom representation, compare those custom // custom representations. if lhs._usedCustomRepresentation != rhs._usedCustomRepresentation { // If the lhs used a custom representation, try comparing against the // custom representation of the bridged rhs (if there is one). if lhs._usedCustomRepresentation { if let customRHS = _getBridgedCustomAnyHashable(rhs._box._base) { return lhs._box._isEqual(to: customRHS._box) ?? false } return false } // Otherwise, try comparing the rhs against the custom representation of // the bridged lhs (if there is one). if let customLHS = _getBridgedCustomAnyHashable(lhs._box._base) { return customLHS._box._isEqual(to: rhs._box) ?? false } return false } #endif return false } } extension AnyHashable : Hashable { public var hashValue: Int { return _box._hashValue } } 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. @_silgen_name("_swift_stdlib_makeAnyHashableUsingDefaultRepresentation") public // COMPILER_INTRINSIC (actually, called from the runtime) func _stdlib_makeAnyHashableUsingDefaultRepresentation<H : Hashable>( of value: H, storingResultInto result: UnsafeMutablePointer<AnyHashable> ) { result.pointee = AnyHashable(_usingDefaultRepresentationOf: value) } @_silgen_name("_swift_stdlib_makeAnyHashableUpcastingToHashableBaseType") func _stdlib_makeAnyHashableUpcastingToHashableBaseType<H : Hashable>( _ value: H, storingResultInto result: UnsafeMutablePointer<AnyHashable> ) @_silgen_name("_swift_convertToAnyHashable") public // COMPILER_INTRINSIC func _convertToAnyHashable<H : Hashable>(_ value: H) -> AnyHashable { return AnyHashable(value) } @_silgen_name("_swift_convertToAnyHashableIndirect") public // COMPILER_INTRINSIC (actually, called from the runtime) func _convertToAnyHashableIndirect<H : Hashable>( _ value: H, _ target: UnsafeMutablePointer<AnyHashable> ) { target.initialize(to: AnyHashable(value)) } @_silgen_name("_swift_anyHashableDownCastConditionalIndirect") public // COMPILER_INTRINSIC (actually, called from the runtime) func _anyHashableDownCastConditionalIndirect<T>( _ value: UnsafePointer<AnyHashable>, _ target: UnsafeMutablePointer<T> ) -> Bool { return value.pointee._downCastConditional(into: target) }
1af8e28e17734de31aa12a1ac87f054e
33.598784
87
0.666345
false
false
false
false
SamirTalwar/advent-of-code
refs/heads/main
2018/AOC_23_1.swift
mit
1
let inputParser = try! RegExp(pattern: "^pos=<(-?\\d+),(-?\\d+),(-?\\d+)>, r=(\\d+)$") struct Position { let x: Int let y: Int let z: Int func distance(from other: Position) -> Int { return abs(x - other.x) + abs(y - other.y) + abs(z - other.z) } } struct Nanobot: CustomStringConvertible { let position: Position let signalRadius: Int var description: String { return "pos=<\(position.x),\(position.y),\(position.z)>, r=\(signalRadius)" } func isInRange(of bot: Nanobot) -> Bool { return position.distance(from: bot.position) <= bot.signalRadius } } func main() { let nanobots = StdIn().map(parseInput) let strongestNanobot = nanobots.max(by: comparing { bot in bot.signalRadius })! let inRange = nanobots.filter { bot in bot.isInRange(of: strongestNanobot) } print(inRange.count) } func parseInput(input: String) -> Nanobot { guard let match = inputParser.firstMatch(in: input) else { fatalError("Could not parse \"\(input)\".") } return Nanobot( position: Position( x: Int(match[1])!, y: Int(match[2])!, z: Int(match[3])! ), signalRadius: Int(match[4])! ) }
48b9f6f38b6f188d9f752894439798ff
26.466667
86
0.584951
false
false
false
false
ayking/tasty-imitation-keyboard
refs/heads/master
Keyboard/Catboard.swift
bsd-3-clause
3
// // Catboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 9/24/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit /* This is the demo keyboard. If you're implementing your own keyboard, simply follow the example here and then set the name of your KeyboardViewController subclass in the Info.plist file. */ let kCatTypeEnabled = "kCatTypeEnabled" class Catboard: KeyboardViewController { let takeDebugScreenshot: Bool = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { NSUserDefaults.standardUserDefaults().registerDefaults([kCatTypeEnabled: true]) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func keyPressed(key: Key) { if let textDocumentProxy = self.textDocumentProxy as? UITextDocumentProxy { let keyOutput = key.outputForCase(self.shiftState.uppercase()) if !NSUserDefaults.standardUserDefaults().boolForKey(kCatTypeEnabled) { textDocumentProxy.insertText(keyOutput) return } if key.type == .Character || key.type == .SpecialCharacter { let context = textDocumentProxy.documentContextBeforeInput if context != nil { if count(context) < 2 { textDocumentProxy.insertText(keyOutput) return } var index = context!.endIndex index = index.predecessor() if context[index] != " " { textDocumentProxy.insertText(keyOutput) return } index = index.predecessor() if context[index] == " " { textDocumentProxy.insertText(keyOutput) return } textDocumentProxy.insertText("\(randomCat())") textDocumentProxy.insertText(" ") textDocumentProxy.insertText(keyOutput) return } else { textDocumentProxy.insertText(keyOutput) return } } else { textDocumentProxy.insertText(keyOutput) return } } } override func setupKeys() { super.setupKeys() if takeDebugScreenshot { if self.layout == nil { return } for page in keyboard.pages { for rowKeys in page.rows { for key in rowKeys { if let keyView = self.layout!.viewForKey(key) { keyView.addTarget(self, action: "takeScreenshotDelay", forControlEvents: .TouchDown) } } } } } } override func createBanner() -> ExtraView? { return CatboardBanner(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode()) } func takeScreenshotDelay() { var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("takeScreenshot"), userInfo: nil, repeats: false) } func takeScreenshot() { if !CGRectIsEmpty(self.view.bounds) { UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() let oldViewColor = self.view.backgroundColor self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1) var rect = self.view.bounds UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) var context = UIGraphicsGetCurrentContext() self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true) var capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") var imagePath = "/Users/archagon/Documents/Programming/OSX/RussianPhoneticKeyboard/External/tasty-imitation-keyboard/\(name).png" UIImagePNGRepresentation(capturedImage).writeToFile(imagePath, atomically: true) self.view.backgroundColor = oldViewColor } } } func randomCat() -> String { let cats = "🐱😺😸😹😽😻😿😾😼🙀" let numCats = count(cats) let randomCat = arc4random() % UInt32(numCats) let index = advance(cats.startIndex, Int(randomCat)) let character = cats[index] return String(character) }
b1895f78a2f3b7e1f0dc5a32e50d6c01
35.302158
146
0.563218
false
false
false
false
mesosfer/Mesosfer-iOS
refs/heads/master
Sample-Swift/05-query-user/Mesosfer-Swift/QueryUserViewController.swift
bsd-3-clause
4
/** * Copyright (c) 2016, Mesosfer * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ import Foundation import UIKit import Mesosfer class QueryUserViewController: UITableViewController { var users: [MFUser]? override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 100 self.tableView.rowHeight = UITableViewAutomaticDimension } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.queryUser() } func queryUser(firstname: String? = nil) { let query = MFUser.query() if let firstname = firstname { query.whereKey("firstname", equalTo: firstname) } query.findAsync { (users, error) in if let e = error as? NSError { self.showError(title: "Query user failed", error: e) return } if let users = users as? [MFUser] { self.users = users self.tableView.reloadData() } } } } extension QueryUserViewController { override func numberOfSections(in tableView: UITableView) -> Int { if let users = self.users { return users.count } return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let users = self.users { return users[section].objectId } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellUser", for: indexPath) if let users = self.users { let user = users[indexPath.section] if let dict = user.dictionary() as? [String:AnyObject] { cell.textLabel?.text = "\(dict)" } } return cell } } extension QueryUserViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true self.queryUser(firstname: searchBar.text) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false searchBar.text = nil self.queryUser() } }
5cd4986afee8afbbc461c450cd1ce027
27.468085
109
0.599028
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/SlidingContainerPresentable.swift
mit
1
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit public enum SlidingContainerPresentedState { case collapsed case expanded } fileprivate let velocityThreshold: CGFloat = 200.0 public protocol SlidingContainerPresentable: class { var modalContainer: UIView! { get } var blurEffectView: UIVisualEffectView? { get } var blurEffect: UIBlurEffect? { get } var anchorEdge: UIRectEdge { get } var minMargin: CGFloat { get } var maxSize: CGFloat? { get } var cornerRadius: CGFloat { get } var shouldAnimateCornerRadius: Bool { get } var progressWhenInterrupted: CGFloat { get set } @available(iOSApplicationExtension 10.0, *) var runningAnimators: [UIViewPropertyAnimator] { get set } } @available(iOSApplicationExtension 10.0, *) public extension SlidingContainerPresentable where Self: UIViewController { public var blurEffectView: UIVisualEffectView? { return nil } public var blurEffect: UIBlurEffect? { return nil } public var minMargin: CGFloat { return 64.0 } public var maxSize: CGFloat? { return nil } public var cornerRadius: CGFloat { return 12.0 } public var shouldAnimateCornerRadius: Bool { return false } var targetContainerState: SlidingContainerPresentedState { if self.anchorEdge == .top { return modalContainer.frame.origin.y == 0 ? .collapsed : .expanded } else if self.anchorEdge == .bottom { return modalContainer.frame.origin.y == view.frame.height ? .expanded : .collapsed } else if self.anchorEdge == .left { return modalContainer.frame.origin.x == 0 ? .collapsed : .expanded } else if self.anchorEdge == .right { return modalContainer.frame.origin.x == view.frame.width ? .expanded : .collapsed } else { fatalError("status=invalid-anchor-edge actual=\(self.anchorEdge)") } } public func animateTransitionIfNeeded(state: SlidingContainerPresentedState, duration: TimeInterval) { guard runningAnimators.isEmpty else { return } let frameAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) { let viewFrame = self.view.frame let maximumSize = self.maxSize ?? 0 let height: CGFloat let width: CGFloat if self.anchorEdge == .left || self.anchorEdge == .right { height = viewFrame.height width = self.maxSize ?? viewFrame.width - self.minMargin } else { height = max(viewFrame.height - self.minMargin, maximumSize) width = viewFrame.width } let x: CGFloat let y: CGFloat if self.anchorEdge == .top { x = 0 switch state { case .expanded: y = 0 case .collapsed: y = -height } } else if self.anchorEdge == .bottom { x = 0 switch state { case .expanded: y = self.maxSize == nil ? self.minMargin : viewFrame.height - maximumSize case .collapsed: y = viewFrame.height } } else if self.anchorEdge == .left { switch state { case .expanded: x = 0 case .collapsed: x = -width } y = 0 } else if self.anchorEdge == .right { switch state { case .expanded: x = self.maxSize == nil ? self.minMargin : viewFrame.width - maximumSize case .collapsed: x = viewFrame.width } y = 0 } else { fatalError("status=invalid-anchor-edge actual=\(self.anchorEdge)") } self.modalContainer.frame = CGRect(x: x, y: y, width: width, height: height) } frameAnimator.addCompletion { [weak self] _ in guard let `self` = self, let index = self.runningAnimators.index(of: frameAnimator) else { return } self.runningAnimators.remove(at: index) } frameAnimator.startAnimation() runningAnimators.append(frameAnimator) if let blurEffectView = blurEffectView { let blurAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) { switch state { case .expanded: blurEffectView.effect = self.blurEffect ?? UIBlurEffect(style: .dark) case .collapsed: blurEffectView.effect = nil } } blurAnimator.addCompletion { [weak self] position in guard let `self` = self, let index = self.runningAnimators.index(of: blurAnimator) else { return } self.runningAnimators.remove(at: index) let isShowing: Bool switch state { case .expanded: isShowing = position == .end case .collapsed: isShowing = position == .start } blurEffectView.isUserInteractionEnabled = isShowing blurEffectView.effect = isShowing ? self.blurEffect ?? UIBlurEffect(style: .dark) : nil if self.shouldAnimateCornerRadius { self.modalContainer.layer.cornerRadius = isShowing ? self.cornerRadius : 0 } } blurAnimator.startAnimation() runningAnimators.append(blurAnimator) } if shouldAnimateCornerRadius { let cornerAnimator = UIViewPropertyAnimator(duration: duration, curve: .linear) { switch state { case .expanded: // if #available(iOSApplicationExtension 11.0, *) { // self.modalContainer.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] // } self.modalContainer.layer.cornerRadius = self.cornerRadius case .collapsed: self.modalContainer.layer.cornerRadius = 0 } } cornerAnimator.addCompletion { [weak self] position in guard let `self` = self, let index = self.runningAnimators.index(of: cornerAnimator) else { return } self.runningAnimators.remove(at: index) } cornerAnimator.startAnimation() runningAnimators.append(cornerAnimator) } } public func animateOrReverseRunningTransition(state: SlidingContainerPresentedState? = nil, duration: TimeInterval) { let targetState = state ?? targetContainerState if runningAnimators.isEmpty { animateTransitionIfNeeded(state: targetState, duration: duration) } else { for animator in runningAnimators { animator.isReversed = !animator.isReversed } } } func percent(for recognizer: UIPanGestureRecognizer) -> CGFloat { let locationInSourceView = recognizer.location(in: view) let delta = recognizer.translation(in: view) let originalLocation = CGPoint(x: locationInSourceView.x - delta.x, y: locationInSourceView.y - delta.y) let width = view.bounds.width let height = view.bounds.height if anchorEdge == .top { let possibleHeight = originalLocation.y return abs(delta.y) / possibleHeight } else if anchorEdge == .bottom { let possibleHeight = height - originalLocation.y return delta.y / possibleHeight } else if anchorEdge == .left { let possibleWidth = originalLocation.x return abs(delta.x) / possibleWidth } else if anchorEdge == .right { let possibleWidth = width - originalLocation.x return delta.x / possibleWidth } else { fatalError("edge must be .top, .bottom, .left, or .right. actual=\(anchorEdge)") } } public func handlePan(with recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: animateTransitionIfNeeded(state: targetContainerState, duration: 1.0) runningAnimators.forEach { $0.pauseAnimation() } let fractionsComplete = runningAnimators.map { $0.fractionComplete } progressWhenInterrupted = fractionsComplete.max() ?? 0 case .changed: runningAnimators.forEach { animator in animator.fractionComplete = percent(for: recognizer) + progressWhenInterrupted } case .ended: let timing = UICubicTimingParameters(animationCurve: .easeOut) let velocity = recognizer.velocity(in: view) var swiped = false if anchorEdge == .top { swiped = velocity.y < -velocityThreshold } else if anchorEdge == .bottom { swiped = velocity.y > velocityThreshold } else if anchorEdge == .left { swiped = velocity.x < -velocityThreshold } else if anchorEdge == .right { swiped = velocity.x > velocityThreshold } let shouldReverse = !swiped && percent(for: recognizer) < 0.5 runningAnimators.forEach { animator in animator.isReversed = shouldReverse animator.continueAnimation(withTimingParameters: timing, durationFactor: 0) } case .possible, .failed, .cancelled: break } } }
e8b8d33715af813b24eed8382cd402db
40.2125
121
0.566272
false
false
false
false
powerytg/Accented
refs/heads/master
Accented/UI/Details/Components/DetailBackgroundView.swift
mit
1
// // DetailBackgroundView.swift // Accented // // Created by Tiangong You on 8/1/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit class DetailBackgroundView: UIImageView { // Minimal scroll distance required before the perspective effect would be applied private let minDist : CGFloat = 40 // Maximum scroll distance required for perspective effect to be fully applied private let maxDist : CGFloat = 160 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(frame: CGRect) { super.init(frame: frame) initialize() } private func initialize() { backgroundColor = ThemeManager.sharedInstance.currentTheme.rootViewBackgroundColor self.clipsToBounds = true self.image = ThemeManager.sharedInstance.currentTheme.backgroundDecorImage self.contentMode = .scaleAspectFill } func applyScrollingAnimation(_ offset : CGFloat) { let pos = max(0, offset - minDist) let percentage = pos / maxDist self.alpha = 1 - percentage } }
96c5b32a6e62041a96ee87c4bd415045
27.170732
90
0.667532
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/边缘侧滑/MedalCount Completed/MedalCount/Controllers/MainViewController.swift
mit
1
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit final class MainViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var yearLabel: UILabel! @IBOutlet weak var hostLabel: UILabel! @IBOutlet weak var medalCountButton: UIButton! @IBOutlet weak var logoImageView: UIImageView! // MARK: - Properties lazy var slideInTransitioningDelegate = SlideInPresentationManager() private let dataStore = GamesDataStore() fileprivate var presentedGames: Games? { didSet { configurePresentedGames() } } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() presentedGames = nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? GamesTableViewController { if segue.identifier == "SummerSegue" { controller.gamesArray = dataStore.summer slideInTransitioningDelegate.direction = .left } else if segue.identifier == "WinterSegue" { controller.gamesArray = dataStore.winter slideInTransitioningDelegate.direction = .right } controller.delegate = self slideInTransitioningDelegate.disableCompactHeight = false controller.transitioningDelegate = slideInTransitioningDelegate controller.modalPresentationStyle = .custom } else if let controller = segue.destination as? MedalCountViewController { controller.medalCount = presentedGames?.medalCount slideInTransitioningDelegate.direction = .bottom slideInTransitioningDelegate.disableCompactHeight = true controller.transitioningDelegate = slideInTransitioningDelegate controller.modalPresentationStyle = .custom } } } // MARK: - Private private extension MainViewController { func configurePresentedGames() { guard let presentedGames = presentedGames else { logoImageView.image = UIImage(named: "medals") hostLabel.text = nil yearLabel.text = nil medalCountButton.isHidden = true return } logoImageView.image = UIImage(named: presentedGames.flagImageName) hostLabel.text = presentedGames.host yearLabel.text = presentedGames.seasonYear medalCountButton.isHidden = false } } // MARK: - GamesTableViewControllerDelegate extension MainViewController: GamesTableViewControllerDelegate { func gamesTableViewController(controller: GamesTableViewController, didSelectGames selectedGames: Games) { presentedGames = selectedGames dismiss(animated: true) } }
f8df88869746461d9e1291390af59c59
35.846939
108
0.746885
false
false
false
false
JGiola/swift
refs/heads/main
test/stdlib/FloatConstants.swift
apache-2.0
9
// RUN: %target-typecheck-verify-swift #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #elseif os(WASI) import WASILibc #elseif os(Windows) import CRT #else #error("Unsupported platform") #endif _ = FLT_RADIX // expected-warning {{is deprecated}} _ = FLT_MANT_DIG // expected-warning {{is deprecated}} _ = FLT_MIN_EXP // expected-warning {{is deprecated}} _ = FLT_MAX_EXP // expected-warning {{is deprecated}} _ = FLT_MAX // expected-warning {{is deprecated}} _ = FLT_EPSILON // expected-warning {{is deprecated}} _ = FLT_MIN // expected-warning {{is deprecated}} _ = FLT_TRUE_MIN // expected-warning {{is deprecated}} _ = DBL_MANT_DIG // expected-warning {{is deprecated}} _ = DBL_MIN_EXP // expected-warning {{is deprecated}} _ = DBL_MAX_EXP // expected-warning {{is deprecated}} _ = DBL_MAX // expected-warning {{is deprecated}} _ = DBL_EPSILON // expected-warning {{is deprecated}} _ = DBL_MIN // expected-warning {{is deprecated}} _ = DBL_TRUE_MIN // expected-warning {{is deprecated}}
1bbd77a87ce416e421ade1f260e75a53
32.193548
54
0.685131
false
false
false
false
yunzixun/V2ex-Swift
refs/heads/master
View/V2PhotoBrowser/V2PhotoBrowser.swift
mit
1
// // V2PhotoBrowser.swift // V2ex-Swift // // Created by huangfeng on 2/22/16. // Copyright © 2016 Fin. All rights reserved. // //此部分代码实现参考了 //https://github.com/mwaterfall/MWPhotoBrowser import UIKit //import INSImageView @objc protocol V2PhotoBrowserDelegate { func numberOfPhotosInPhotoBrowser(_ photoBrowser:V2PhotoBrowser) -> Int func photoAtIndexInPhotoBrowser(_ photoBrowser:V2PhotoBrowser, index:Int) -> V2Photo /** 引导动画的Image */ func guideImageInPhotoBrowser(_ photoBrowser:V2PhotoBrowser, index:Int) -> UIImage? /** 引导动画的ContentMode */ func guideContentModeInPhotoBrowser(_ photoBrowser:V2PhotoBrowser, index:Int) -> UIViewContentMode /** 引导动画在window上的位置 */ func guideFrameInPhotoBrowser(_ photoBrowser:V2PhotoBrowser, index:Int) -> CGRect } class V2PhotoBrowser: UIViewController ,UIScrollViewDelegate ,UIViewControllerTransitioningDelegate { static let PADDING:CGFloat = 10 /// 引导guideImageView,用于引导进入动画和退出动画 var guideImageView:INSImageView = INSImageView() weak var delegate:V2PhotoBrowserDelegate? fileprivate var photoCount = NSNotFound fileprivate var photos:[NSObject] = [] fileprivate var _currentPageIndex = 0 var currentPageIndex:Int { get { return _currentPageIndex } set { if _currentPageIndex == newValue || newValue < 0 || newValue >= self.numberOfPhotos() { return } _currentPageIndex = newValue self.jumpPageAtIndex(_currentPageIndex) } } fileprivate var visiblePages:NSMutableSet = [] fileprivate var recycledPages:NSMutableSet = [] var pagingScrollView = UIScrollView() var transitionController = V2PhotoBrowserSwipeInteractiveTransition() init(delegate:V2PhotoBrowserDelegate){ self.delegate = delegate super.init(nibName: nil, bundle: nil) self.setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(){ self.view.backgroundColor = UIColor(white: 0, alpha: 0) self.transitioningDelegate = self self.pagingScrollView.isPagingEnabled = true self.pagingScrollView.delegate = self self.pagingScrollView.showsHorizontalScrollIndicator = false self.pagingScrollView.showsVerticalScrollIndicator = false self.pagingScrollView.contentSize = self.contentSizeForPagingScrollView() self.view.addSubview(self.pagingScrollView) var frame = self.view.bounds frame.origin.x -= V2PhotoBrowser.PADDING frame.size.width += 2 * V2PhotoBrowser.PADDING self.pagingScrollView.frame = frame self.pagingScrollView.contentSize = self.contentSizeForPagingScrollView() /// 一进来时,是隐藏,等引导动画结束时再显示 self.pagingScrollView.isHidden = true self.guideImageView.clipsToBounds = true self.view.addSubview(self.guideImageView) self.reloadData() self.jumpPageAtIndex(self.currentPageIndex) } override func viewDidLoad() { self.transitionController.browser = self self.transitionController.prepareGestureRecognizerInView(self.view) } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.transitionController.interacting ? self.transitionController : nil } override func viewDidAppear(_ animated: Bool) { UIApplication.shared.setStatusBarHidden(true, with: .fade) } override func viewWillDisappear(_ animated: Bool) { UIApplication.shared.setStatusBarHidden(false, with: .none) } func dismiss(){ self.dismiss(animated: true, completion: nil) } func jumpPageAtIndex(_ index:Int){ if self.isViewLoaded { let pageFrame = self.frameForPageAtIndex(_currentPageIndex) self.pagingScrollView.setContentOffset(CGPoint(x: pageFrame.origin.x - V2PhotoBrowser.PADDING, y: 0), animated: false) } } func guideImageViewHidden(_ hidden:Bool){ if hidden { self.guideImageView.isHidden = true self.pagingScrollView.isHidden = false } else { if self.guideImageView.originalImage != nil{ //隐藏引导动画图 self.guideImageView.isHidden = false //隐藏真正的图片浏览器,等引导动画完后再显示 self.pagingScrollView.isHidden = true } else { //如果没有图片,则直接显示真正的图片浏览器 self.guideImageViewHidden(true) } } } //MARK: Frame Calculations func contentSizeForPagingScrollView() -> CGSize { let bounds = self.pagingScrollView.bounds return CGSize(width: bounds.size.width * CGFloat(self.numberOfPhotos()), height: bounds.size.height) } func frameForPageAtIndex(_ index:Int) -> CGRect{ let bounds = self.pagingScrollView.bounds var pageFrame = bounds pageFrame.size.width -= (2 * V2PhotoBrowser.PADDING); pageFrame.origin.x = (bounds.size.width * CGFloat(index) ) + V2PhotoBrowser.PADDING; return pageFrame.integral; } //MARK: Data func numberOfPhotos() -> Int { if self.photoCount == NSNotFound { if let delegate = self.delegate { self.photoCount = delegate.numberOfPhotosInPhotoBrowser(self) } } if self.photoCount == NSNotFound { self.photoCount = 0 } return self.photoCount } func photoAtIndex(_ index:Int) -> V2Photo? { if index < self.photos.count { if self.photos[index].isKind(of: NSNull.self) { if let delegate = self.delegate { let photo = delegate.photoAtIndexInPhotoBrowser(self, index: index) self.photos[index] = photo return photo } } else { return self.photos[index] as? V2Photo } } return nil } func reloadData(){ self.photoCount = NSNotFound let numberOfPhotos = self.numberOfPhotos() self.photos = [] for _ in 0 ..< numberOfPhotos { self.photos.append(NSNull()) } // Update current page index if (numberOfPhotos > 0) { self._currentPageIndex = max(0, min(self._currentPageIndex, numberOfPhotos - 1)); } else { self._currentPageIndex = 0; } while self.pagingScrollView.subviews.count > 0 { self.pagingScrollView.subviews.last?.removeFromSuperview() } self.tilePages() } //MARK: Perform func tilePages(){ let visibleBounds = self.pagingScrollView.bounds var iFirstIndex = Int( floorf( Float( (visibleBounds.minX + V2PhotoBrowser.PADDING * 2) / visibleBounds.width ) ) ); var iLastIndex = Int( floorf( Float( (visibleBounds.maxX - V2PhotoBrowser.PADDING * 2 - 1) / visibleBounds.width ) ) ); iFirstIndex = max(0,iFirstIndex) iFirstIndex = min (self.numberOfPhotos() - 1,iFirstIndex) iLastIndex = max(0,iLastIndex) iLastIndex = min (self.numberOfPhotos() - 1,iLastIndex) var pageIndex = 0 for page in self.visiblePages { if let page = page as? V2ZoomingScrollView { pageIndex = page.index if pageIndex < iFirstIndex || pageIndex > iLastIndex { self.recycledPages.add(page) page.prepareForReuse() page.removeFromSuperview() } } } self.visiblePages.minus(self.recycledPages as Set<NSObject>) while self.recycledPages.count > 2 { self.recycledPages.remove(self.recycledPages.anyObject()!) } for index in iFirstIndex ... iLastIndex { if !self.isDisplayingPageForIndex(index) { var page = self.dequeueRecycledPage() if page == nil { page = V2ZoomingScrollView(browser: self) } self.configurePage(page!, index: index) self.visiblePages.add(page!) self.pagingScrollView.addSubview(page!) } } } func isDisplayingPageForIndex(_ index:Int) -> Bool { for page in self.visiblePages { if let page = page as? V2ZoomingScrollView { if page.index == index { return true } } } return false } func dequeueRecycledPage() -> V2ZoomingScrollView? { if let page = self.recycledPages.anyObject() as? V2ZoomingScrollView { self.recycledPages.remove(page) return page } return nil } func configurePage(_ page:V2ZoomingScrollView,index:Int){ page.frame = self.frameForPageAtIndex(index) page.index = index page.photo = self.photoAtIndex(index) } //MARK: UIScrollView Delegate func scrollViewDidScroll(_ scrollView: UIScrollView) { self.tilePages() let visibleBounds = self.pagingScrollView.bounds var index = Int ( floorf( Float(visibleBounds.midX / visibleBounds.width) ) ) index = max (0,index) index = min(self.numberOfPhotos() - 1 , index) self._currentPageIndex = index } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return V2PhotoBrowserTransionPresent() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return V2PhotoBrowserTransionDismiss() } }
dc22ce8156384c4c5b67b41013c436ac
32.252427
170
0.607202
false
false
false
false
TZLike/GiftShow
refs/heads/master
GiftShow/GiftShow/Classes/CategoryPage/Model/LeeSingleModel.swift
apache-2.0
1
// // LeeSingleModel.swift // GiftShow // // Created by admin on 16/10/27. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit class LeeSingleModel: LeeBaseModel { var icon_url:String? var id:NSNumber = 0 var name:String? var order:NSNumber = 0 var subcategories:[[String:NSObject]]?{ didSet { guard let subcategories = subcategories else {return } for dd in subcategories { let model = LeeSingleCateModel(dict:dd) cates.append(model) } } } var cates:[LeeSingleCateModel] = [LeeSingleCateModel]() init(dict:[String:NSObject]) { super.init() setValuesForKeys(dict) } }
c05d6653d90848653d9719c8d95c7c36
21.205882
66
0.572185
false
false
false
false
IBM-Swift/Kitura-net
refs/heads/master
Sources/KituraNet/IncomingSocketHandler.swift
apache-2.0
1
/* * Copyright IBM Corporation 2016, 2017 * * 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 Dispatch import Foundation import LoggerAPI import Socket /** This class handles incoming sockets to the HTTPServer. The data sent by the client is read and passed to the current `IncomingDataProcessor`. - Note: The IncomingDataProcessor can change due to an Upgrade request. - Note: This class uses different underlying technologies depending on: 1. On Linux, if no special compile time options are specified, epoll is used 2. On OSX, DispatchSource is used 3. On Linux, if the compile time option -Xswiftc -DGCD_ASYNCH is specified, DispatchSource is used, as it is used on OSX. ### Usage Example: ### ````swift func upgrade(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) -> (IncomingSocketProcessor?, Data?, String?) { let (processor, responseText) = upgrade(handler: handler, request: request, response: response) if let responseText = responseText { return (processor, responseText.data(using: .utf8), "text/plain") } return (processor, nil, nil) } ```` */ public class IncomingSocketHandler { static let socketWriterQueue = DispatchQueue(label: "Socket Writer") // This variable is unused. It is a temporary workaround for a rare crash under load // (see: https://github.com/IBM-Swift/Kitura/issues/1034) while a proper fix is // investigated. var superfluousOptional:String? = String(repeating: "x", count: 2) #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH static let socketReaderQueues = [DispatchQueue(label: "Socket Reader A"), DispatchQueue(label: "Socket Reader B")] // Note: This var is optional to enable it to be constructed in the init function var readerSource: DispatchSourceRead! var writerSource: DispatchSourceWrite? private let numberOfSocketReaderQueues = IncomingSocketHandler.socketReaderQueues.count private let socketReaderQueue: DispatchQueue #endif let socket: Socket /** The `IncomingSocketProcessor` instance that processes data read from the underlying socket. ### Usage Example: ### ````swift processor?.inProgress = false ```` */ public var processor: IncomingSocketProcessor? private let readBuffer = NSMutableData() private let writeBuffer = NSMutableData() private var writeBufferPosition = 0 /// Provides an ability to limit the maximum amount of data that can be read from a socket before rejecting a request and closing /// the connection. /// This is to protect against accidental or malicious requests from exhausting available memory. let options: ServerOptions /// preparingToClose is set when prepareToClose() gets called or anytime we detect the socket has errored or was closed, /// so we try to close and cleanup as long as there is no data waiting to be written and a socket read/write is not in progress. private var preparingToClose = false /// isOpen is set to false when: /// - close() is invoked AND /// - it is safe to close the socket (there is no data waiting to be written and a socket read/write is not in progress). /// This lets other threads know to not start reads/writes on this socket anymore, which could cause a crash. private var isOpen = true /// write() sets this when it starts and unsets it when finished so other threads do not close `socket` during that time, /// which could cause a crash. If any other threads tried to close during that time, write() re-attempts close when it's done private var writeInProgress = false /// handleWrite() sets this when it starts and unsets it when finished so other threads do not close `socket` during that time, /// which could cause a crash. If any other threads tried to close during that time, handleWrite() re-attempts close when it's done private var handleWriteInProgress = false /// handleRead() sets this when it starts and unsets it when finished so other threads do not close `socket` during that time, /// which could cause a crash. If any other threads tried to close during that time, handleRead() re-attempts close when it's done private var handleReadInProgress = false /// The file descriptor of the incoming socket var fileDescriptor: Int32 { return socket.socketfd } init(socket: Socket, using: IncomingSocketProcessor, options: ServerOptions) { self.socket = socket processor = using #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH socketReaderQueue = IncomingSocketHandler.socketReaderQueues[Int(socket.socketfd) % numberOfSocketReaderQueues] readerSource = DispatchSource.makeReadSource(fileDescriptor: socket.socketfd, queue: socketReaderQueue) #endif self.options = options processor?.handler = self #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH readerSource.setEventHandler() { _ = self.handleRead() } readerSource.setCancelHandler(handler: self.handleCancel) readerSource.resume() #endif } /// Read in the available data and hand off to common processing code /// /// - Returns: true if the data read in was processed func handleRead() -> Bool { handleReadInProgress = true defer { handleReadInProgress = false // needs to be unset before calling close() as it is part of the guard in close() if preparingToClose { close() } } // Set handleReadInProgress flag to true before the guard below to avoid another thread // invoking close() in between us clearing the guard and setting the flag. guard isOpen && socket.socketfd > -1 else { preparingToClose = true // flag the function defer clause to cleanup if needed return true } var result = true do { var length = 1 while length > 0 { length = try socket.read(into: readBuffer) } if readBuffer.length > 0 { result = handleReadHelper() } else { if socket.remoteConnectionClosed { Log.debug("socket remoteConnectionClosed in handleRead()") processor?.socketClosed() preparingToClose = true } } } catch let error as Socket.Error { if error.errorCode == Int32(Socket.SOCKET_ERR_CONNECTION_RESET) { Log.debug("Read from socket (file descriptor \(socket.socketfd)) reset. Error = \(error).") } else { Log.error("Read from socket (file descriptor \(socket.socketfd)) failed. Error = \(error).") } preparingToClose = true } catch { Log.error("Unexpected error...") preparingToClose = true } return result } private func handleReadHelper() -> Bool { guard let processor = processor else { return true } let processed = processor.process(readBuffer) if processed { readBuffer.length = 0 } return processed } /// Helper function for handling data read in while the processor couldn't /// process it, if there is any func handleBufferedReadDataHelper() -> Bool { let result : Bool if readBuffer.length > 0 { result = handleReadHelper() } else { result = true } return result } /** Handle data read in while the processor couldn't process it, if there is any - Note: On Linux, the `IncomingSocketManager` should call `handleBufferedReadDataHelper` directly. ### Usage Example: ### ````swift handler?.handleBufferedReadData() ```` */ public func handleBufferedReadData() { #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH if socket.socketfd != Socket.SOCKET_INVALID_DESCRIPTOR { socketReaderQueue.sync() { [weak self] in if let strongSelf = self { _ = strongSelf.handleBufferedReadDataHelper() } } } #endif } /// Handle the situation where we have received data that exceeds the configured requestSizeLimit. func handleOversizedRead(_ limit: Int) { let clientSource = "\(socket.remoteHostname):\(socket.remotePort)" if let (httpStatus, response) = self.options.requestSizeResponseGenerator(limit, clientSource) { let statusCode = httpStatus.rawValue let statusDescription = HTTP.statusCodes[statusCode] ?? "" let contentLength = response.utf8.count let httpResponse = "HTTP/1.1 \(statusCode) \(statusDescription)\r\nConnection: Close\r\nContent-Length: \(contentLength)\r\n\r\n".appending(response) _ = try? socket.write(from: httpResponse) } preparingToClose = true } /// Write out any buffered data now that the socket can accept more data func handleWrite() { #if !GCD_ASYNCH && os(Linux) IncomingSocketHandler.socketWriterQueue.sync() { [unowned self] in self.handleWriteHelper() } #endif } /// Inner function to write out any buffered data now that the socket can accept more data, /// invoked in serial queue. private func handleWriteHelper() { handleWriteInProgress = true defer { handleWriteInProgress = false // needs to be unset before calling close() as it is part of the guard in close() if preparingToClose { close() } } if writeBuffer.length != 0 { defer { #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH if writeBuffer.length == 0, let writerSource = writerSource { writerSource.cancel() } #endif } // Set handleWriteInProgress flag to true before the guard below to avoid another thread // invoking close() in between us clearing the guard and setting the flag. guard isOpen && socket.socketfd > -1 else { Log.warning("Socket closed with \(writeBuffer.length - writeBufferPosition) bytes still to be written") writeBuffer.length = 0 writeBufferPosition = 0 preparingToClose = true // flag the function defer clause to cleanup if needed return } do { let amountToWrite = writeBuffer.length - writeBufferPosition let written: Int if amountToWrite > 0 { written = try socket.write(from: writeBuffer.bytes + writeBufferPosition, bufSize: amountToWrite) } else { if amountToWrite < 0 { Log.error("Amount of bytes to write to file descriptor \(socket.socketfd) was negative \(amountToWrite)") } written = amountToWrite } if written != amountToWrite { writeBufferPosition += written } else { writeBuffer.length = 0 writeBufferPosition = 0 } } catch let error { if let error = error as? Socket.Error, error.errorCode == Int32(Socket.SOCKET_ERR_CONNECTION_RESET) { Log.debug("Write to socket (file descriptor \(socket.socketfd)) failed. Error = \(error).") } else { Log.error("Write to socket (file descriptor \(socket.socketfd)) failed. Error = \(error).") } // There was an error writing to the socket, close the socket writeBuffer.length = 0 writeBufferPosition = 0 preparingToClose = true } } } /// Create the writer source private func createWriterSource() { #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH writerSource = DispatchSource.makeWriteSource(fileDescriptor: socket.socketfd, queue: IncomingSocketHandler.socketWriterQueue) writerSource!.setEventHandler(handler: self.handleWriteHelper) writerSource!.setCancelHandler() { self.writerSource = nil } writerSource!.resume() #endif } /** Write as much data to the socket as possible, buffering the rest - Parameter data: The NSData object containing the bytes to write to the socket. ### Usage Example: ### ````swift try response.write(from: "No protocol specified in the Upgrade header") ```` */ public func write(from data: NSData) { write(from: data.bytes, length: data.length) } /** Write a sequence of bytes in an array to the socket - Parameter from: An UnsafeRawPointer to the sequence of bytes to be written to the socket. - Parameter length: The number of bytes to write to the socket. ### Usage Example: ### ````swift processor.write(from: utf8, length: utf8Length) ```` */ public func write(from bytes: UnsafeRawPointer, length: Int) { writeInProgress = true defer { writeInProgress = false // needs to be unset before calling close() as it is part of the guard in close() if preparingToClose { close() } } // Set writeInProgress flag to true before the guard below to avoid another thread // invoking close() in between us clearing the guard and setting the flag. guard isOpen && socket.socketfd > -1 else { Log.warning("IncomingSocketHandler write() called after socket \(socket.socketfd) closed") preparingToClose = true // flag the function defer clause to cleanup if needed return } do { let written: Int if writeBuffer.length == 0 { written = try socket.write(from: bytes, bufSize: length) } else { written = 0 } if written != length { IncomingSocketHandler.socketWriterQueue.sync() { [unowned self] in self.writeBuffer.append(bytes + written, length: length - written) } #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH if writerSource == nil { createWriterSource() } #endif } } catch let error { if let error = error as? Socket.Error, error.errorCode == Int32(Socket.SOCKET_ERR_CONNECTION_RESET) { Log.debug("Write to socket (file descriptor \(socket.socketfd)) failed. Error = \(error).") } else { Log.error("Write to socket (file descriptor \(socket.socketfd)) failed. Error = \(error).") } } } /** If there is data waiting to be written, set a flag and the socket will be closed when all the buffered data has been written. Otherwise, immediately close the socket. ### Usage Example: ### ````swift handler?.prepareToClose() ```` */ public func prepareToClose() { preparingToClose = true close() } /// Close the socket and mark this handler as no longer in progress, if it is safe. /// (there is no data waiting to be written and a socket read/write is not in progress). /// /// - Note: On Linux closing the socket causes it to be dropped by epoll. /// - Note: On OSX the cancel handler will actually close the socket. private func close() { if isOpen { isOpen = false // Set isOpen to false before the guard below to avoid another thread invoking // a read/write function in between us clearing the guard and setting the flag. // Make sure to set it back to open if the guard fails and we don't actually close. // This guard needs to be here, not in handleCancel() as readerSource.cancel() // only invokes handleCancel() the first time it is called. guard !writeInProgress && !handleWriteInProgress && !handleReadInProgress && writeBuffer.length == writeBufferPosition else { isOpen = true return } #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH readerSource.cancel() #else handleCancel() #endif } } /// DispatchSource cancel handler private func handleCancel() { isOpen = false // just in case something besides close() calls handleCancel() if socket.socketfd > -1 { socket.close() } processor?.inProgress = false processor?.keepAliveUntil = 0.0 processor?.handler = nil processor?.close() processor = nil } }
22cf72e2797abd78a8e50f2d192e09f8
38.358051
161
0.589331
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/Model/ShapeItems/Merge.swift
apache-2.0
3
// // Merge.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation // MARK: - MergeMode enum MergeMode: Int, Codable { case none case merge case add case subtract case intersect case exclude } // MARK: - Merge final class Merge: ShapeItem { // MARK: Lifecycle required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Merge.CodingKeys.self) mode = try container.decode(MergeMode.self, forKey: .mode) try super.init(from: decoder) } required init(dictionary: [String: Any]) throws { let modeRawType: Int = try dictionary.value(for: CodingKeys.mode) guard let mode = MergeMode(rawValue: modeRawType) else { throw InitializableError.invalidInput } self.mode = mode try super.init(dictionary: dictionary) } // MARK: Internal /// The mode of the merge path let mode: MergeMode override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(mode, forKey: .mode) } // MARK: Private private enum CodingKeys: String, CodingKey { case mode = "mm" } }
7f374eebc0426cafd4cb141774b61838
19.948276
73
0.683951
false
false
false
false
remirobert/Dotzu
refs/heads/master
Framework/Dotzu/Dotzu/ManagerViewController.swift
mit
2
// // ManagerViewController.swift // exampleWindow // // Created by Remi Robert on 02/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit class ManagerViewController: UIViewController, LogHeadViewDelegate { var button = LogHeadView(frame: CGRect(origin: LogHeadView.originalPosition, size: LogHeadView.size)) override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.view.addSubview(self.button) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { self.button.updateOrientation(newSize: size) } override func viewDidLoad() { super.viewDidLoad() self.button.delegate = self self.view.backgroundColor = UIColor.clear let selector = #selector(ManagerViewController.panDidFire(panner:)) let panGesture = UIPanGestureRecognizer(target: self, action: selector) button.addGestureRecognizer(panGesture) } func didTapButton() { Dotzu.sharedManager.displayedList = true let storyboard = UIStoryboard(name: "Manager", bundle: Bundle(for: ManagerViewController.self)) guard let controller = storyboard.instantiateInitialViewController() else { return } self.present(controller, animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { Dotzu.sharedManager.displayedList = false } @objc func panDidFire(panner: UIPanGestureRecognizer) { if panner.state == .began { UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: { self.button.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }, completion: nil) } let offset = panner.translation(in: view) panner.setTranslation(CGPoint.zero, in: view) var center = button.center center.x += offset.x center.y += offset.y button.center = center if panner.state == .ended || panner.state == .cancelled { let location = panner.location(in: view) let velocity = panner.velocity(in: view) var finalX: Double = 30 var finalY: Double = Double(location.y) if location.x > UIScreen.main.bounds.size.width / 2 { finalX = Double(UIScreen.main.bounds.size.width) - 30.0 self.button.changeSideDisplay(left: false) } else { self.button.changeSideDisplay(left: true) } let horizentalVelocity = abs(velocity.x) let positionX = abs(finalX - Double(location.x)) let velocityForce = sqrt(pow(velocity.x, 2) * pow(velocity.y, 2)) let durationAnimation = (velocityForce > 1000.0) ? min(0.3, positionX / Double(horizentalVelocity)) : 0.3 if velocityForce > 1000.0 { finalY += Double(velocity.y) * durationAnimation } if finalY > Double(UIScreen.main.bounds.size.height) - 50 { finalY = Double(UIScreen.main.bounds.size.height) - 50 } else if finalY < 50 { finalY = 50 } UIView.animate(withDuration: durationAnimation * 5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 6, options: UIViewAnimationOptions.allowUserInteraction, animations: { self.button.center = CGPoint(x: finalX, y: finalY) self.button.transform = CGAffineTransform.identity }, completion: nil) } } func shouldReceive(point: CGPoint) -> Bool { if Dotzu.sharedManager.displayedList { return true } return self.button.frame.contains(point) } }
2dd5d110150919571ae1fed5e9572fa4
34.419643
117
0.601714
false
false
false
false
DrGo/LearningSwift
refs/heads/master
PLAYGROUNDS/LSB_009_Optionals.playground/section-2.swift
gpl-3.0
2
import UIKit /*---------------------/ // Optionals // Why use implicitly unwrapped and lazy properites: // http://www.scottlogic.com/blog/2014/11/20/swift-initialisation.html /---------------------*/ // var aVar: String = nil <-- Not allowed var anotherVar: String? = nil var word: String word = "sdkfj" var copied = word var anOptional: String? = "hi" var aCopy = anOptional! var anotherWord: String! = "hello" var anotherCopy: String = anotherWord anotherWord = nil // anotherCopy = anotherWord <--- Not allowed var myName: String? // = "Kyle" // to make it have a value if myName == nil { "no name here" } else { "my name is \(myName)" } let scores = ["kyle": 111, "newton": 80] let kylesScore : Int? = scores["kyle"] if kylesScore != nil { // Must use `!` to force unwrap to a non-optional type: "Kyle's score is \(kylesScore!)" } // Optional Binding... if let score = scores["newton"] { // So, `!` is not required: "Newton's score is \(score)" } else { "Score not found." } // SIDENOTE: ?? let maybeInt : Int? = nil let aNumber = maybeInt ?? 10 "Number is \(aNumber)." let defaultName : () -> String = { "Expensive Computation" return "Default Name" } let maybeName : String? = nil let aName = maybeName ?? defaultName() println("Number is \(aName).") defaultName() // Optional Chaining // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html // struct Address { var state: String? } struct Person { var address: Address? } struct Order { var person: Person? } var order = Order(person: Person(address: Address(state: "CA"))) let state = order.person?.address?.state if state != nil { "Order is from \(state!)." } if let orderState = order.person?.address?.state { "Order is from \(orderState)." }
a4a6f71f940e448d3df06989a215d78a
19.715909
122
0.653319
false
false
false
false
lauracpierre/FA_ReveaMenu
refs/heads/master
FA_RevealMenu/FA_RevealMenuController.swift
mit
1
// // FA_RevealMenuController.swift // FA_RevealMenu // // Created by Pierre LAURAC on 09/05/2015. // Copyright (c) 2015 Front. All rights reserved. // import UIKit enum SlideOutState { case Collapsed case LeftPanelExpanded } // MARK: - Back menu delegate protocol protocol FA_MenuSelectionProtocol { func shouldReplaceWithNewViewController() -> Bool func selectionWasMade() -> AnyObject } // MARK: - Minimum implementation for front menu protocol FA_FrontViewMinimalImplementation { func selectionChangedInMenu(object: AnyObject?) } // MARK: - That's where the magic starts to happen class FA_RevealMenuController: UIViewController { //var centerNavigationController: UINavigationController! var centerViewController: UIViewController! var leftViewController: UIViewController? let expandViewSizePercentage: CGFloat = 0.8 var maxExpandSize: CGFloat? = nil let panGestureXLocationStart: CGFloat = 70.0 var leftDelegate: FA_MenuSelectionProtocol? var currentState: SlideOutState = .Collapsed { didSet { let shouldShowShadow = currentState != .Collapsed showShadowForCenterViewController(shouldShowShadow) } } override func viewDidLoad() { super.viewDidLoad() self.performSegueWithIdentifier(FASegueFrontIdentifier, sender: nil) self.performSegueWithIdentifier(FASegueLeftIdentifier, sender: nil) if var left = leftViewController as? FA_MenuSelectionProtocol { self.leftDelegate = left } let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") panGestureRecognizer.delegate = self centerViewController.view.addGestureRecognizer(panGestureRecognizer) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:") tapGestureRecognizer.delegate = self centerViewController.view.addGestureRecognizer(tapGestureRecognizer) } } // MARK: - Front and back view animation management extension FA_RevealMenuController { func toggleLeftPanel() { animateLeftPanel(shouldExpand: (currentState != .LeftPanelExpanded)) } func collapseSidePanels() { toggleLeftPanel() } func animateLeftPanel(#shouldExpand: Bool) { if (shouldExpand) { self.currentState = .LeftPanelExpanded var viewSize = self.view.frame.size var smallestSize = min(viewSize.height, viewSize.width) let targetSize = maxExpandSize != nil ? maxExpandSize! : (smallestSize * self.expandViewSizePercentage) animateCenterPanelXPosition(targetPosition: targetSize) } else { animateCenterPanelXPosition(targetPosition: 0) { finished in self.currentState = .Collapsed } } } func animateCenterPanelXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: { self.centerViewController.view.frame.origin.x = targetPosition }, completion: completion) } func addChildSidePanelController(sidePanelController: UIViewController) { view.insertSubview(sidePanelController.view, atIndex: 0) addChildViewController(sidePanelController) } func addChildFrontPanelController(sidePanelController: UIViewController) { if let centerView = self.centerViewController?.view { sidePanelController.view.frame = centerView.frame } addChildViewController(sidePanelController) view.addSubview(sidePanelController.view) } func showShadowForCenterViewController(shouldShowShadow: Bool) { if (shouldShowShadow) { centerViewController.view.layer.shadowOpacity = 0.8 } else { centerViewController.view.layer.shadowOpacity = 0.0 } } } // MARK: - Gesture recognizer extension FA_RevealMenuController: UIGestureRecognizerDelegate { func handlePanGesture(recognizer: UIPanGestureRecognizer) { // Only want gesture from the side of the screen if currentState == .Collapsed && recognizer.locationInView(centerViewController.view).x > self.panGestureXLocationStart { return } // Checking if menu is closed and blocking any gesture beside left to right let gestureIsDraggingFromLeftToRight = (recognizer.velocityInView(centerViewController.view).x > 80) if currentState == .Collapsed && !gestureIsDraggingFromLeftToRight { return } // Checking if menu is open and blocking any gesting beside right to left let gestureIsDraggingFromRightToLeft = (recognizer.velocityInView(centerViewController.view).x < 10) if currentState == .LeftPanelExpanded && !gestureIsDraggingFromRightToLeft { return } // Simple gesture with no drag and drop switch(recognizer.state) { case .Changed: animateLeftPanel(shouldExpand: currentState == .Collapsed) break default: break } } func handleTapGesture(recognizer: UITapGestureRecognizer) { self.collapseSidePanels() } func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UITapGestureRecognizer { // We have to "disable" tap gesture when collapse otherwise we will prevent // the view to handle normal tap gesture (like on UITableView) if currentState == .Collapsed { return false } } return true } func passMessageToFrontViewController() { if let object:AnyObject = self.leftDelegate?.selectionWasMade() { // Trying to infomr the front view controller a selection was made based // on the type of the front view controller. // Could add support for more like TabViewController // Simple case where the centerViewController is the UIViewController if let front = centerViewController as? FA_FrontViewMinimalImplementation { front.selectionChangedInMenu(object) } // It could be a navigation controller. In that case, the rootViewController might implement the protocol? else if let nav = centerViewController as? UINavigationController, let root = nav.viewControllers[0] as? FA_FrontViewMinimalImplementation { root.selectionChangedInMenu(object) } } } func swapFrontControllers(destination: UIViewController) { if self.leftDelegate?.shouldReplaceWithNewViewController() ?? true { NSLog("new VC") self.addChildFrontPanelController(destination) if let center = self.centerViewController { center.view.removeFromSuperview() center.removeFromParentViewController() } self.centerViewController = destination self.passMessageToFrontViewController() } // Closing menu if self.currentState != .Collapsed { self.collapseSidePanels() } } } // MARK: - UIViewController extension extension UIViewController { func FA_RevealMenu() -> FA_RevealMenuController? { var parent: UIViewController = self while(!(parent is FA_RevealMenuController)) { if(parent.parentViewController == nil) { break } parent = parent.parentViewController! } return parent as? FA_RevealMenuController; } } let FASegueFrontIdentifier = "fa_front" let FASegueLeftIdentifier = "fa_left" // MARK: - Custom Segue class FA_ReavealMenuSegueSetController: UIStoryboardSegue { override func perform() { let identifier = self.identifier; if let container = self.sourceViewController as? FA_RevealMenuController, let destination = self.destinationViewController as? UIViewController { // Closing menu if container.currentState != .Collapsed { container.collapseSidePanels() } if identifier == FASegueFrontIdentifier { container.swapFrontControllers(destination) } else if identifier == FASegueLeftIdentifier { container.leftViewController = destination container.addChildSidePanelController(destination) } } } } // MARK: - Custom Segue class FA_ReavealMenuSeguePushController: UIStoryboardSegue { override func perform() { let identifier = self.identifier; if let container = self.sourceViewController.FA_RevealMenu(), let destination = self.destinationViewController as? UIViewController { if identifier == FASegueFrontIdentifier { container.swapFrontControllers(destination) } } } }
f007b4668de6f3612b244a34d53b39be
31.451505
144
0.630939
false
false
false
false
yanif/circator
refs/heads/master
MetabolicCompass/DataSources/RegisterModelDataSource.swift
apache-2.0
1
// // RegisterModelDataSource.swift // MetabolicCompass // // Created by Anna Tkach on 4/27/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit import MetabolicCompassKit let RegisterFont = UIFont(name: "GothamBook", size: 15.0)! let RegisterUnitsFont = UIFont(name: "GothamBook", size: 13.0)! class RegisterModelDataSource: BaseDataSource { let model = RegistrationModel() private let loadImageCellIdentifier = "loadImageCell" private let inputTextCellIdentifier = "inputTextCell" private let doubleCheckBoxCellIdentifier = "doubleCheckBoxCell" override func registerCells() { let loadImageCellNib = UINib(nibName: "LoadImageCollectionViewCell", bundle: nil) collectionView?.registerNib(loadImageCellNib, forCellWithReuseIdentifier: loadImageCellIdentifier) let inputTextCellNib = UINib(nibName: "InputCollectionViewCell", bundle: nil) collectionView?.registerNib(inputTextCellNib, forCellWithReuseIdentifier: inputTextCellIdentifier) let doubleCheckBoxCellNib = UINib(nibName: "DoubleCheckListCollectionViewCell", bundle: nil) collectionView?.registerNib(doubleCheckBoxCellNib, forCellWithReuseIdentifier: doubleCheckBoxCellIdentifier) } // MARK: - CollectionView Delegate & DataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return model.items.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let field = model.itemAtIndexPath(indexPath) var cell: BaseCollectionViewCell? let cellType = field.type switch (cellType) { case .Email, .Password, .FirstName, .LastName, .Weight, .Height, .HeightInches, .Age, .Other: cell = inputCellForIndex(indexPath, forField: field) case .Gender, .Units: cell = checkSelectionCellForIndex(indexPath, forField: field) case .Photo: cell = loadPhotoCellForIndex(indexPath, forField: field) } cell!.changesHandler = { (cell: UICollectionViewCell, newValue: AnyObject?) -> () in if let indexPath = self.collectionView!.indexPathForCell(cell) { self.model.setAtItem(itemIndex: indexPath.row, newValue: newValue) let field = self.model.itemAtIndexPath(indexPath) if field.type == .Units { /* let needsUpdateIndexPathes = self.model.unitsDependedItemsIndexes() collectionView.reloadItemsAtIndexPaths(needsUpdateIndexPathes) */ self.model.switchItemUnits() self.model.reloadItems() collectionView.reloadData() } } } return cell! } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let field = model.itemAtIndexPath(indexPath) if model.units == .Imperial && (field.type == .Weight || field.type == .Height || field.type == .HeightInches) { return field.type == .HeightInches ? smallHeightInchesCellSize() : (field.type == .Height ? smallHeightCellSize() : smallWeightCellSize()) } if field.type == .Weight || field.type == .Height { return smallCellSize() } if field.type == .Photo { return highCellSize() } return defaultCellSize() } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return spaceBetweenCellsInOneRow } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionFooter { let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "footerView", forIndexPath: indexPath) return footerView } return UICollectionReusableView() } // MARK: - Cells configuration private func inputCellForIndex(indexPath: NSIndexPath, forField field: ModelItem) -> BaseCollectionViewCell { let cell = collectionView!.dequeueReusableCellWithReuseIdentifier(inputTextCellIdentifier, forIndexPath: indexPath) as! InputCollectionViewCell cell.inputTxtField.textColor = selectedTextColor cell.inputTxtField.attributedPlaceholder = NSAttributedString(string: (field.type == .HeightInches ? "0-11 " : field.title), attributes: [NSForegroundColorAttributeName : unselectedTextColor, NSFontAttributeName: RegisterFont]) cell.inputTxtField.text = field.stringValue() cell.inputTxtField.font = ProfileFont cell.nameLbl.font = RegisterFont if field.type == .Password { cell.inputTxtField.secureTextEntry = true } else if field.type == .Email { cell.inputTxtField.keyboardType = UIKeyboardType.EmailAddress } else if field.type == .Age { cell.inputTxtField.keyboardType = UIKeyboardType.NumberPad } if let iconImageName = field.iconImageName { cell.cellImage?.image = UIImage(named: iconImageName) cell.imageLeadingConstraint?.constant = 16 cell.imageWidthConstraint?.constant = 21 cell.imageTxtSpacing?.constant = 16 cell.labelCellSpacing?.constant = 16 } if model.units == .Imperial { if field.type == .HeightInches { cell.imageLeadingConstraint?.constant = 0 cell.imageWidthConstraint?.constant = 0 cell.imageTxtSpacing?.constant = 0 cell.nameLbl.font = RegisterUnitsFont } else if field.type == .Height { cell.imageLeadingConstraint?.constant = 0 cell.imageTxtSpacing?.constant = 8 cell.labelCellSpacing?.constant = 8 cell.nameLbl.font = RegisterUnitsFont cell.inputTxtField.attributedPlaceholder = NSAttributedString(string: field.title, attributes: [NSForegroundColorAttributeName : unselectedTextColor, NSFontAttributeName: RegisterUnitsFont]) } else if field.type == .Weight { //cell.imageTxtSpacing?.constant = 8 cell.labelCellSpacing?.constant = 8 cell.nameLbl.font = RegisterUnitsFont cell.inputTxtField.attributedPlaceholder = NSAttributedString(string: field.title, attributes: [NSForegroundColorAttributeName : unselectedTextColor, NSFontAttributeName: RegisterUnitsFont]) } } if field.type == .Weight { cell.nameLbl.text = model.units.weightTitle cell.inputTxtField.keyboardType = UIKeyboardType.NumberPad } else if field.type == .Height { cell.nameLbl.text = model.units.heightTitle cell.inputTxtField.keyboardType = UIKeyboardType.NumberPad } else if field.type == .HeightInches { cell.nameLbl.text = model.units.heightInchesTitle ?? "" cell.inputTxtField.keyboardType = UIKeyboardType.NumberPad } cell.nameLbl.textColor = selectedTextColor return cell } private func checkSelectionCellForIndex(indexPath: NSIndexPath, forField field: ModelItem) -> BaseCollectionViewCell { let cell = collectionView!.dequeueReusableCellWithReuseIdentifier(doubleCheckBoxCellIdentifier, forIndexPath: indexPath) as! DoubleCheckListCollectionViewCell if field.type == .Gender { cell.setFirstTitle(Gender.Male.title) cell.setSecondTitle(Gender.Female.title) cell.setSelectedItem(selectedItemIndex: model.gender.rawValue) } else if field.type == .Units { cell.setFirstTitle(UnitsSystem.Imperial.title) cell.setSecondTitle(UnitsSystem.Metric.title) cell.setSelectedItem(selectedItemIndex: model.units.rawValue) } cell.selectedTextColor = selectedTextColor cell.unselectedTextColor = unselectedTextColor cell.cellImage?.image = UIImage(named: field.iconImageName!) return cell } private func loadPhotoCellForIndex(indexPath: NSIndexPath, forField field: ModelItem) -> BaseCollectionViewCell { let cell = collectionView!.dequeueReusableCellWithReuseIdentifier(loadImageCellIdentifier, forIndexPath: indexPath) as! LoadImageCollectionViewCell cell.presentingViewController = viewController!.navigationController return cell } // MARK: - Cells sizes private let spaceBetweenCellsInOneRow: CGFloat = 0 // 26 private let cellHeight: CGFloat = 45 private let cellHighHeight: CGFloat = 160 private func highCellSize() -> CGSize { let size = CGSizeMake(self.collectionView!.bounds.width, cellHighHeight) return size } private func defaultCellSize() -> CGSize { let size = CGSizeMake(self.collectionView!.bounds.width, cellHeight) return size } private func smallCellSize() -> CGSize { let size = CGSizeMake((self.collectionView!.bounds.width - spaceBetweenCellsInOneRow) / 2.0, cellHeight) return size } private func smallWeightCellSize() -> CGSize { let size = CGSizeMake(4.5*(self.collectionView!.bounds.width - spaceBetweenCellsInOneRow) / 10.0, cellHeight) return size } private func smallHeightCellSize() -> CGSize { let size = CGSizeMake(3.5*(self.collectionView!.bounds.width - spaceBetweenCellsInOneRow) / 10.0, cellHeight) return size } private func smallHeightInchesCellSize() -> CGSize { let size = CGSizeMake(2*(self.collectionView!.bounds.width - spaceBetweenCellsInOneRow) / 10.0, cellHeight) return size } }
a26169e44e8c3f69e79dfa00b0bf32ae
41.256198
235
0.677195
false
false
false
false
gtranchedone/AlgorithmsSwift
refs/heads/master
Algorithms.playground/Pages/Challenge - Position of Element.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) /*: ### Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. There won't be duplicate values in the array. For example: - [1, 3, 5, 6] with target value 5 should return 2. - [1, 3, 5, 6] with target value 2 should return 1. - [1, 3, 5, 6] with target value 7 should return 4. - [1, 3, 5, 6] with target value 0 should return 0. */ import Foundation var sampleData = [1, 3, 5, 6] func positionOfElement<T where T: Comparable>(element: T, array: [T]) -> Int { /*: The array is supposed to be sorted, so searching a value in it using a binary search is the most efficient way to determine whether the element is present in the array or what's the lowest index it could go into. O(logN) */ return modifiedBinarySearch(array, target: element) } //: This binary search returns the last lowest index the element was supposed to be found into instead of the classic -1 or Int? in Swift func modifiedBinarySearch<T where T: Comparable>(array: [T], target: T) -> Int { var min = 0 var max = array.count - 1 var guess = 0 while (min <= max) { guess = min + ((max - min) / 2) let guessedElement = array[guess] if guessedElement == target { return guess } else if (target > guessedElement) { min = guess + 1 } else { max = guess - 1 } } /*: If the element wasn't found, it might be that the returned index is occupied by an element greater then the target. In this case the element must be smaller then the next element (otherwise the binary search would have returned that index instead) and therefore it would fit in between the elements at guess and guess + 1, hence it would push the element at guess + 1, and occupy that position itself. In our case min == guess + 1 as it's set to that value by the while loop above before returning, therefore we can simply return min. */ return min } assert(positionOfElement(5, array: sampleData) == 2) assert(positionOfElement(2, array: sampleData) == 1) assert(positionOfElement(7, array: sampleData) == 4) assert(positionOfElement(0, array: sampleData) == 0) //: [Next](@next)
bc37ef23b64d7a18eb279c4f04728212
37.163934
204
0.664519
false
false
false
false
koscida/Kos_AMAD_Spring2015
refs/heads/master
Spring_16/IGNORE_work/projects/BreakoutSpriteKitTutorial/BreakoutSpriteKitTutorial/GameViewController.swift
gpl-3.0
1
// // GameViewController.swift // BreakoutSpriteKitTutorial // // Created by Zouhair Mahieddine on 4/22/15. // Copyright (c) 2015 Zedenem. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { let sceneData = try! NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe) let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! SKScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameOverScene.unarchiveFromFile("GameOverScene") as? GameOverScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = false /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
1c2cc4146686597a900c3140e0af14c8
30.362319
96
0.631238
false
false
false
false
silt-lang/silt
refs/heads/master
Sources/SyntaxGen/SyntaxNodes.swift
mit
1
/// SyntaxNodes.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. let baseNodes = [ Node("Decl", kind: "Syntax", children: []), Node("Expr", kind: "Syntax", children: []), // typed-parameter ::= '(' <ascription> ')' // | '{' <ascription> '}' Node("TypedParameter", kind: "Syntax", children: []), // function-clause-decl ::= <basic-expr-list> with <expr> '|' <basic-expr-list>? '=' <expr> ';' // | <basic-expr-list> '=' <expr> ';' // | <basic-expr-list> '=' <expr> 'where' '{' <decl-list>? '}' ';' // | <basic-expr-list> ';' Node("FunctionClauseDecl", kind: "Decl", children: []), // fixity-decl ::= 'infix' <int> <id-list> // | 'infixl' <int> <id-list> // | 'infixr' <int> <id-list> Node("FixityDecl", kind: "Decl", children: []), Node("Binding", kind: "Syntax", children: []), Node("BasicExpr", kind: "Expr", children: []), ] let syntaxNodes = [ // MARK: Source Node("SourceFile", element: "Token"), // MARK: Identifiers Node("IdentifierList", element: "IdentifierToken"), // qualified-name ::= <id> | <id> '.' <qualified-name> Node("QualifiedName", element: "QualifiedNamePiece"), Node("QualifiedNamePiece", kind: "Syntax", children: [ Child("name", kind: "IdentifierToken"), Child("trailingPeriod", kind: "PeriodToken", isOptional: true) ]), // MARK: Modules // module-decl ::= 'module' <id> <typed-parameter-list>? 'where' <decl-list> // decl-list ::= <decl> // | <decl> <decl-list> Node("ModuleDecl", kind: "Decl", children: [ Child("moduleToken", kind: "ModuleToken"), Child("moduleIdentifier", kind: "QualifiedName"), Child("typedParameterList", kind: "TypedParameterList"), Child("whereToken", kind: "WhereToken"), Child("leftBraceToken", kind: "LeftBraceToken"), Child("declList", kind: "DeclList"), Child("rightBraceToken", kind: "RightBraceToken"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("DeclList", element: "Decl"), // MARK: Imports // qualified-name ::= <id> | <id> '.' <qualified-name> // import-decl ::= 'open'? 'import' <qualified-name> Node("OpenImportDecl", kind: "Decl", children: [ Child("openToken", kind: "OpenToken", isOptional: true), Child("importToken", kind: "ImportToken"), Child("importIdentifier", kind: "QualifiedName"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("ImportDecl", kind: "Decl", children: [ Child("importToken", kind: "ImportToken"), Child("importIdentifier", kind: "QualifiedName"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // MARK: Data types // data-decl ::= 'data' <id> <typed-parameter-list>? <type-indices>? 'where'? '{' <constructor-list> '}' ';' Node("DataDecl", kind: "Decl", children: [ Child("dataToken", kind: "DataToken"), Child("dataIdentifier", kind: "IdentifierToken"), Child("typedParameterList", kind: "TypedParameterList"), Child("typeIndices", kind: "TypeIndices"), Child("whereToken", kind: "WhereToken"), Child("leftBraceToken", kind: "LeftBraceToken"), Child("constructorList", kind: "ConstructorList"), Child("rightBraceToken", kind: "RightBraceToken"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("EmptyDataDecl", kind: "Decl", children: [ Child("dataToken", kind: "DataToken"), Child("dataIdentifier", kind: "IdentifierToken"), Child("typedParameterList", kind: "TypedParameterList"), Child("typeIndices", kind: "TypeIndices"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // type-indices ::= ':' <expr> Node("TypeIndices", kind: "Syntax", children: [ Child("colonToken", kind: "ColonToken"), Child("indexExpr", kind: "Expr") ]), // typed-parameter-list ::= <typed-parameter> // | <typed-parameter> <typed-parameter-list> Node("TypedParameterList", element: "TypedParameter"), // ascription ::= <id-list> ':' <expr> Node("Ascription", kind: "Syntax", children: [ Child("boundNames", kind: "IdentifierList"), Child("colonToken", kind: "ColonToken"), Child("typeExpr", kind: "Expr") ]), Node("ExplicitTypedParameter", kind: "TypedParameter", children: [ Child("leftParenToken", kind: "LeftParenToken"), Child("ascription", kind: "Ascription"), Child("rightParenToken", kind: "RightParenToken") ]), Node("ImplicitTypedParameter", kind: "TypedParameter", children: [ Child("leftBraceToken", kind: "LeftBraceToken"), Child("ascription", kind: "Ascription"), Child("rightBraceToken", kind: "RightBraceToken") ]), // constructor-list ::= <constructor-decl> // | <constructor-decl> ';' <constructor-decl-list> Node("ConstructorList", element: "ConstructorDecl"), // constructor-decl ::= '|' <ascription> Node("ConstructorDecl", kind: "Decl", children: [ Child("ascription", kind: "Ascription"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // MARK: Records // record-decl ::= 'record' <id> <typed-parameter-list>? <type-indices>? 'where' '{' <record-element-list>? '}' ';' Node("RecordDecl", kind: "Decl", children: [ Child("recordToken", kind: "RecordToken"), Child("recordName", kind: "IdentifierToken"), Child("parameterList", kind: "TypedParameterList"), Child("typeIndices", kind: "TypeIndices"), Child("whereToken", kind: "WhereToken"), Child("leftParenToken", kind: "LeftParenToken"), Child("recordElementList", kind: "DeclList"), Child("rightParenToken", kind: "RightParenToken"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // record-element ::= <field-decl> // | <function-decl> // | <record-constructor-decl> // field-decl ::= 'field' <ascription> Node("FieldDecl", kind: "Decl", children: [ Child("fieldToken", kind: "FieldToken"), Child("ascription", kind: "Ascription"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // record-constructor-decl ::= 'constructor' <id> Node("RecordConstructorDecl", kind: "Decl", children: [ Child("constructorToken", kind: "ConstructorToken"), Child("constructorName", kind: "IdentifierToken"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // record-field-assignment-list ::= <record-field-assignment> // | <record-field-assignment> ';' <record-field-assignment-list> Node("RecordFieldAssignmentList", element: "RecordFieldAssignment"), // record-field-assignment ::= <id> '=' <expr> Node("RecordFieldAssignment", kind: "Syntax", children: [ Child("fieldName", kind: "IdentifierToken"), Child("equalsToken", kind: "EqualsToken"), Child("fieldInitExpr", kind: "Expr"), Child("trailingSemicolon", kind: "SemicolonToken", isOptional: true) ]), // MARK: Functions // function-decl ::= <ascription> Node("FunctionDecl", kind: "Decl", children: [ Child("ascription", kind: "Ascription"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("WithRuleFunctionClauseDecl", kind: "FunctionClauseDecl", children: [ Child("basicExprList", kind: "BasicExprList"), Child("withToken", kind: "WithToken"), Child("withExpr", kind: "Expr"), Child("withPatternClause", kind: "BasicExprList", isOptional: true), Child("equalsToken", kind: "EqualsToken"), Child("rhsExpr", kind: "Expr"), Child("whereClause", kind: "FunctionWhereClauseDecl", isOptional: true), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("NormalFunctionClauseDecl", kind: "FunctionClauseDecl", children: [ Child("basicExprList", kind: "BasicExprList"), Child("equalsToken", kind: "EqualsToken"), Child("rhsExpr", kind: "Expr"), Child("whereClause", kind: "FunctionWhereClauseDecl", isOptional: true), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("AbsurdFunctionClauseDecl", kind: "FunctionClauseDecl", children: [ Child("basicExprList", kind: "BasicExprList"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("FunctionWhereClauseDecl", kind: "Decl", children: [ Child("whereToken", kind: "WhereToken"), Child("leftBraceToken", kind: "LeftBraceToken"), Child("declList", kind: "DeclList"), Child("rightBraceToken", kind: "RightBraceToken"), ]), Node("LetBindingDecl", kind: "Decl", children: [ Child("head", kind: "NamedBasicExpr"), Child("basicExprList", kind: "BasicExprList"), Child("equalsToken", kind: "EqualsToken"), Child("boundExpr", kind: "Expr"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // MARK: Fixity Node("NonFixDecl", kind: "FixityDecl", children: [ Child("infixToken", kind: "InfixToken"), Child("precedence", kind: "IdentifierToken"), Child("names", kind: "IdentifierList"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("LeftFixDecl", kind: "FixityDecl", children: [ Child("infixlToken", kind: "InfixlToken"), Child("precedence", kind: "IdentifierToken"), Child("names", kind: "IdentifierList"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), Node("RightFixDecl", kind: "FixityDecl", children: [ Child("infixrToken", kind: "InfixrToken"), Child("precedence", kind: "IdentifierToken"), Child("names", kind: "IdentifierList"), Child("trailingSemicolon", kind: "SemicolonToken"), ]), // MARK: Patterns // pattern-clause-list ::= <pattern-clause> // | <pattern-clause> <patter-clause-list> // pattern-clause ::= <expr> Node("PatternClauseList", element: "Expr"), // Expressions // expr ::= <basic-expr-list> '->' <expr> // | '\' <binding-list> <expr> // | 'forall' <typed-parameter-list> '->' <expr> // | 'let' <decl-list> 'in' <expr> // | <application> // | <basic-expr> Node("LambdaExpr", kind: "Expr", children: [ Child("slashToken", kind: "ForwardSlashToken"), Child("bindingList", kind: "BindingList"), Child("arrowToken", kind: "ArrowToken"), Child("bodyExpr", kind: "Expr") ]), Node("QuantifiedExpr", kind: "Expr", children: [ Child("forallToken", kind: "ForallToken"), Child("bindingList", kind: "TypedParameterList"), Child("arrowToken", kind: "ArrowToken"), Child("outputExpr", kind: "Expr") ]), Node("LetExpr", kind: "Expr", children: [ Child("letToken", kind: "LetToken"), Child("leftBraceToken", kind: "LeftBraceToken"), Child("declList", kind: "DeclList"), Child("rightBraceToken", kind: "RightBraceToken"), Child("inToken", kind: "InToken"), Child("outputExpr", kind: "Expr") ]), Node("ApplicationExpr", kind: "Expr", children: [ Child("exprs", kind: "BasicExprList") ]), // application ::= <basic-expr> <application> // binding-list ::= '_' // | <id> // | <typed-parameter> // | '_' <binding-list> // | <id> <binding-list> // | <typed-parameter> <binding-list> Node("BindingList", element: "Binding"), Node("NamedBinding", kind: "Binding", children: [ Child("name", kind: "QualifiedName") ]), Node("TypedBinding", kind: "Binding", children: [ Child("parameter", kind: "TypedParameter") ]), Node("AnonymousBinding", kind: "Binding", children: [ Child("underscoreToken", kind: "UnderscoreToken") ]), // basic-expr-list ::= <basic-expr> // | <basic-expr> <basic-expr-list> Node("BasicExprList", element: "BasicExpr"), // basic-expr ::= <qualified-name> // | '_' // | '()' // | 'Type' // | <typed-parameter-list> // | '(' <expr> ')' // | 'record' <basic-expr>? '{' <record-field-assignment-list>? '}' Node("NamedBasicExpr", kind: "BasicExpr", children: [ Child("name", kind: "QualifiedName") ]), Node("UnderscoreExpr", kind: "BasicExpr", children: [ Child("underscoreToken", kind: "UnderscoreToken") ]), Node("AbsurdExpr", kind: "BasicExpr", children: [ Child("leftParenToken", kind: "LeftParenToken"), Child("rightParenToken", kind: "RightParenToken"), ]), Node("TypeBasicExpr", kind: "BasicExpr", children: [ Child("typeToken", kind: "TypeToken") ]), Node("ParenthesizedExpr", kind: "BasicExpr", children: [ Child("leftParenToken", kind: "LeftParenToken"), Child("expr", kind: "Expr"), Child("rightParenToken", kind: "RightParenToken") ]), Node("TypedParameterGroupExpr", kind: "BasicExpr", children: [ Child("parameters", kind: "TypedParameterList"), ]), Node("RecordExpr", kind: "BasicExpr", children: [ Child("recordToken", kind: "recordToken"), Child("parameterExpr", kind: "BasicExpr", isOptional: true), Child("leftBraceToken", kind: "LeftBraceToken"), Child("fieldAssignments", kind: "RecordFieldAssignmentList"), Child("rightBraceToken", kind: "RightBraceToken") ]), // MARK: Reparsing Node("FunctionClauseList", element: "FunctionClauseDecl"), Node("ReparsedApplicationExpr", kind: "BasicExpr", children: [ Child("head", kind: "NamedBasicExpr"), Child("exprs", kind: "BasicExprList"), ]), ]
b71349719ecff9a7650797f7d04de3c1
33.191919
117
0.618021
false
false
false
false
temoki/TortoiseGraphics
refs/heads/master
PlaygroundBook/Sources/Core/TortoiseState.swift
mit
1
import Foundation struct TortoiseState: Equatable, Codable { var position: Vec2D = Vec2D() var heading: Angle = Angle(0, .degree) var pen: Pen = Pen() var shape: Shape = .tortoise var isVisible: Bool = true var speed: Speed = .normal var strokePath: [Vec2D] = [] var fillPath: [Vec2D]? }
0b799919d1b46ff8d1ffc1ca3a40be2b
14.714286
42
0.621212
false
false
false
false
timfuqua/Bourgeoisie
refs/heads/master
Bourgeoisie/Bourgeoisie/View Controller/TitleViewController.swift
mit
1
// // TitleViewController.swift // Bourgeoisie // // Created by Tim Fuqua on 9/25/15. // Copyright (c) 2015 FuquaProductions. All rights reserved. // import UIKit // MARK: TitleViewController: UIViewController /** */ class TitleViewController: UIViewController { // MARK: class vars // MARK: private lets // MARK: private vars (computed) // MARK: private vars // MARK: private(set) vars // MARK: lets // MARK: vars (computed) // MARK: vars var numberOfOpponents: Int = 1 // MARK: @IBOutlets @IBOutlet weak var paddingView: UIView! @IBOutlet weak var titleView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var numPlayersLabelView: UIView! @IBOutlet weak var numPlayersLabel: UILabel! @IBOutlet weak var numPlayersControlView: UIView! @IBOutlet weak var numPlayersControl: UISegmentedControl! @IBOutlet weak var newGameView: UIView! @IBOutlet weak var newGameButton: UIButton! @IBOutlet weak var tutorialView: UIView! @IBOutlet weak var tutorialButton: UIButton! @IBOutlet weak var loadGameView: UIView! @IBOutlet weak var loadGameButton: UIButton! @IBOutlet weak var settingsView: UIView! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var helpView: UIView! @IBOutlet weak var helpButton: UIButton! // MARK: init // MARK: vc lifecycle override func viewDidLoad() { super.viewDidLoad() numPlayersControl.selectedSegmentIndex = numberOfOpponents-1 } // MARK: @IBActions @IBAction func unwindToTitleSegue(segue: UIStoryboardSegue) { if let sourceVC = segue.sourceViewController as? GameplayViewController { print("Unwinding from GameplayViewController") } else { fatalError("Should only be unwinding to this VC through one of the previous segues") } } @IBAction func numberOfOpponentsSelectionMade(sender: UISegmentedControl) { print("Selection changed to \(sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)!)") numberOfOpponents = sender.selectedSegmentIndex+1 print("numberOfOpponents: \(numberOfOpponents)") } @IBAction func newGameButtonPressed(sender: UIButton) { performSegueWithIdentifier("Title_New_to_Gameplay", sender: self) } @IBAction func tutorialButtonPressed(sender: UIButton) { performSegueWithIdentifier("Title_Tutorial_to_Gameplay", sender: self) } @IBAction func loadGameButtonPressed(sender: UIButton) { performSegueWithIdentifier("Title_Load_to_Gameplay", sender: self) } // MARK: public funcs override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "Title_New_to_Gameplay" { if let gameplayVC = segue.destinationViewController as? GameplayViewController { gameplayVC.gameMode = GameplayMode.New gameplayVC.numOpponentsSelected = numberOfOpponents } } else if segue.identifier == "Title_Tutorial_to_Gameplay" { if let gameplayVC = segue.destinationViewController as? GameplayViewController { gameplayVC.gameMode = GameplayMode.Tutorial gameplayVC.numOpponentsSelected = numberOfOpponents } } else if segue.identifier == "Title_Load_to_Gameplay" { if let gameplayVC = segue.destinationViewController as? GameplayViewController { gameplayVC.gameMode = GameplayMode.Load gameplayVC.numOpponentsSelected = numberOfOpponents } } else { fatalError("Shouldn't be segueing unless it's one of the previous segues") } } // MARK: private funcs }
266138c8486a3a587d9637b55d1c4772
28.661157
96
0.716634
false
false
false
false
RaviDesai/RSDRestServices
refs/heads/master
Example/Pods/RSDRESTServices/Pod/Classes/APIRequest.swift
mit
2
// // APIRequest.swift // // Created by Ravi Desai on 6/10/15. // Copyright (c) 2015 RSD. All rights reserved. // import Foundation public class APIRequest<U: APIResponseParserProtocol> { private var baseURL: NSURL? private var endpoint: APIEndpoint private var bodyEncoder: APIBodyEncoderProtocol? private var additionalHeaders: [String: String]? public private(set) var responseParser: U public init(baseURL: NSURL?, endpoint: APIEndpoint, bodyEncoder: APIBodyEncoderProtocol?, responseParser: U, additionalHeaders: [String: String]?) { self.baseURL = baseURL self.endpoint = endpoint self.bodyEncoder = bodyEncoder self.additionalHeaders = additionalHeaders self.responseParser = responseParser } public func URL() -> NSURL? { return self.endpoint.URL(self.baseURL) } public func acceptTypes() -> String? { return self.responseParser.acceptTypes?.joinWithSeparator(", ") } public func method() -> String { return self.endpoint.method() } public func contentType() -> String? { return self.bodyEncoder?.contentType() } public func body() -> NSData? { return self.bodyEncoder?.body() } public func makeRequest() -> NSMutableURLRequest? { var result: NSMutableURLRequest? if let url = self.URL() { let mutableRequest = NSMutableURLRequest(URL: url) mutableRequest.HTTPMethod = self.method() if let data = body() { mutableRequest.HTTPBody = data; NSURLProtocol.setProperty(data.copy(), forKey: "PostedData", inRequest: mutableRequest) } if let headers = self.additionalHeaders { for header in headers { mutableRequest.setValue(header.1, forHTTPHeaderField: header.0); } } if let acceptTypes = self.acceptTypes() { mutableRequest.setValue(acceptTypes, forHTTPHeaderField: "Accept") } if let contentType = self.contentType() { mutableRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") } result = mutableRequest } return result } }
8bdd60864dcd3d1e69a26f3fe8a35729
31.638889
152
0.605364
false
false
false
false
leoru/Brainstorage
refs/heads/master
Brainstorage-iOS/Classes/Models/JobFilter.swift
mit
1
// // JobFilter.swift // Brainstorage // // Created by Kirill Kunst on 10.02.15. // Copyright (c) 2015 Kirill Kunst. All rights reserved. // import UIKit class JobFilter: NSObject { var categories : [JobCategory] = JobCategory.allCategories() var query : String = "" var freelance : Bool = false var fulltime : Bool = false var contract : Bool = false var page : Int = 1 class var sharedInstance : JobFilter { struct Static { static var instance: JobFilter? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = JobFilter() } return Static.instance! } func selectedCategories() -> [JobCategory] { return self.categories.filter({ (job : JobCategory) -> Bool in return job.selected }) } func requestParams() -> [String : AnyObject] { var params = [String : AnyObject]() if (self.freelance) { params["freelance"] = "1" } if (self.fulltime) { params["fulltime"] = "1" } if (self.freelance) { params["contract"] = "1" } if (self.query != "") { params["q"] = self.query } var categories = [String]() for job in self.selectedCategories() { categories.append(job.id) } params["category_ids"] = categories params["page"] = "\(self.page)" self.page++ return params } }
5bc1cab452b04e6b9b52f63c6bd1433c
22.735294
70
0.51425
false
false
false
false
huangboju/Moots
refs/heads/master
算法学习/LeetCode/LeetCode/kthSmallest.swift
mit
1
// // kthSmallest.swift // LeetCode // // Created by 黄伯驹 on 2019/6/4. // Copyright © 2019 伯驹 黄. All rights reserved. // import Foundation // https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/266/heap-stack-queue/1156/ //有序矩阵中第K小的元素 //给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 //请注意,它是排序后的第k小元素,而不是第k个元素。 // //示例: // //matrix = [ //[ 1, 5, 9], //[10, 11, 13], //[12, 13, 15] //], //k = 8, // //返回 13。 //说明: //你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。 func kthSmallest(_ matrix: [[Int]], _ k: Int) -> Int { if matrix.count == 1 { return matrix[0][k-1] } var result = matrix[0] for arr in matrix.dropFirst() { result = mergeSortArr(result, arr) } return result[k-1] } func mergeSortArr(_ arr1: [Int], _ arr2: [Int]) -> [Int] { var result = Array(repeating: 0, count: arr1.count + arr2.count) var i = arr1.count - 1, j = arr2.count - 1 result.replaceSubrange(0...i, with: arr1) while i >= 0 || j >= 0 { if j < 0 || (i >= 0 && result[i] > arr2[j]) { result[i + j + 1] = result[i] i -= 1 } else { result[i + j + 1] = arr2[j] j -= 1 } } return result }
b28f9d4ba55848a2f3c832d4333decb3
21.036364
108
0.535479
false
false
false
false
Ramesh-P/virtual-tourist
refs/heads/master
Virtual Tourist/TravelLocationsMapViewController.swift
mit
1
// // TravelLocationsMapViewController.swift // Virtual Tourist // // Created by Ramesh Parthasarathy on 2/20/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // /** * Credits/Attributions: * Map tiles are property of OpenStreetMap Foundation and their contributors. * * OpenStreetMap Attribution * ------------------------- * OpenStreetMap® is open data, licensed under the Open Data Commons Open Database License (ODbL) by the OpenStreetMap Foundation (OSMF). * https://www.openstreetmap.org/copyright * * CARTO Attribution * ----------------- * https://carto.com/attribution * * Stamen Attribution * ------------------ * Except otherwise noted, each of these map tile sets are © Stamen Design, under a Creative Commons Attribution (CC BY 3.0) license. * http://maps.stamen.com/#terrain/12/37.7706/-122.3782 * * For Toner and Terrain: Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL. * Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href=“http://www.openstreetmap.org/copyright">ODbL</a>. * * For Watercolor: Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA. * Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>. * */ import Foundation import UIKit import MapKit import CoreData // MARK: TravelLocationsMapViewController class TravelLocationsMapViewController: UIViewController, UINavigationControllerDelegate { // MARK: Properties let appDelegate = UIApplication.shared.delegate as! AppDelegate let navigationControllerDelegate = AppNavigationControllerDelegate() var annotation: Annotation? var preset: Preset? var pin: Pin? var canLoadPins: Bool = Bool() var canDeletePins: Bool = Bool() var isEditingPins: Bool = Bool() // MARK: Outlets @IBOutlet weak var map: MKMapView! @IBOutlet weak var banner: UIImageView! @IBOutlet weak var hint: UILabel! @IBOutlet weak var pinAction: UIBarButtonItem! @IBOutlet var barButtons: [UIBarButtonItem]! // MARK: Actions @IBAction func deletePin(_ sender: UIBarButtonItem) { // Set actions isEditingPins = !isEditingPins canLoadPins = !isEditingPins canDeletePins = false displayEditStatus() } @IBAction func resetMapSize(_ sender: UIBarButtonItem) { // Reset and save map zoom to normal level resetSpan() } @IBAction func deleteAllPins(_ sender: UIBarButtonItem) { // Set actions canDeletePins = true canLoadPins = false isEditingPins = false // Delete all pins from map and data store fetchPins() } // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() // Initialize canLoadPins = true canDeletePins = false isEditingPins = false navigationControllerDelegate.setAppTitleImage(self) banner.image = UIImage(named: appDelegate.bannerImage) // Layout setMapTileOverlay() addGestureReconizer() displayEditStatus() fetchRegion() fetchPins() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Layout for barButton in barButtons { barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Lato-Bold", size: appDelegate.barButtonFontSize) as Any], for: .normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: TravelLocationsMapViewController+MKMapViewDelegate extension TravelLocationsMapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { // Render overlay tiles on the map view guard let tileOverlay = overlay as? MKTileOverlay else { return MKOverlayRenderer() } return MKTileOverlayRenderer(tileOverlay: tileOverlay) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // Add custom pin to the map let Identifier = "LocationPin" var annotationView: MKAnnotationView? annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: Identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: Identifier) annotationView?.image = UIImage(named: "Pin") annotationView?.canShowCallout = false annotationView?.centerOffset = CGPoint(x: 0.0, y: -(annotationView?.image?.size.height)!/2) } else { annotationView?.annotation = annotation } return annotationView } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { // Set and save location and zoom level when map region is changed setSpan() } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { mapView.deselectAnnotation(view.annotation, animated: false) // Fetch selected location pin from data store let latitude = view.annotation?.coordinate.latitude let longitude = view.annotation?.coordinate.longitude let predicate = NSPredicate(format: "latitude = %@ AND longitude = %@", argumentArray: [latitude!, longitude!]) let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Pin") fetchRequest.predicate = predicate if let results = try? appDelegate.stack.context.fetch(fetchRequest) { for pin in results { if (isEditingPins) { // Delete selected location pin from map and data store appDelegate.stack.context.delete(pin as! NSManagedObject) appDelegate.stack.saveContext() map.removeAnnotation(view.annotation!) fetchPins() } else if (!isEditingPins) { // Show photos from selected pin location let controller = self.storyboard!.instantiateViewController(withIdentifier: "PhotoAlbumViewController") as! PhotoAlbumViewController controller.pin = pin as? Pin navigationController?.pushViewController(controller, animated: true) } } } } }
2f1ce4b73788a9ea9704ea6e8fdd6e70
35.287179
274
0.635811
false
false
false
false
nosrak113/ZLSwipeableViewSwift
refs/heads/master
ZLSwipeableViewSwift/ZLSwipeableView.swift
mit
1
// // ZLSwipeableView.swift // ZLSwipeableViewSwiftDemo // // Created by Zhixuan Lai on 4/27/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit class ZLPanGestureRecognizer: UIPanGestureRecognizer { } public func ==(lhs: ZLSwipeableViewDirection, rhs: ZLSwipeableViewDirection) -> Bool { return lhs.rawValue == rhs.rawValue } public struct ZLSwipeableViewDirection : OptionSetType, CustomStringConvertible { public var rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } // MARK: NilLiteralConvertible public init(nilLiteral: ()) { self.rawValue = 0 } // MARK: BitwiseOperationsType public static var allZeros: ZLSwipeableViewDirection { return self.init(rawValue: 0) } public static var None: ZLSwipeableViewDirection { return self.init(rawValue: 0b0000) } public static var Left: ZLSwipeableViewDirection { return self.init(rawValue: 0b0001) } public static var Right: ZLSwipeableViewDirection { return self.init(rawValue: 0b0010) } public static var Up: ZLSwipeableViewDirection { return self.init(rawValue: 0b0100) } public static var Down: ZLSwipeableViewDirection { return self.init(rawValue: 0b1000) } public static var Horizontal: ZLSwipeableViewDirection { return [Left, Right] } public static var Vertical: ZLSwipeableViewDirection { return [Up , Down] } public static var All: ZLSwipeableViewDirection { return [Horizontal , Vertical] } public static func fromPoint(point: CGPoint) -> ZLSwipeableViewDirection { switch (point.x, point.y) { case let (x, y) where abs(x)>=abs(y) && x>=0: return .Right case let (x, y) where abs(x)>=abs(y) && x<0: return .Left case let (x, y) where abs(x)<abs(y) && y<=0: return .Up case let (x, y) where abs(x)<abs(y) && y>0: return .Down case (_, _): return .None } } public var description: String { switch self { case ZLSwipeableViewDirection.None: return "None" case ZLSwipeableViewDirection.Left: return "Left" case ZLSwipeableViewDirection.Right: return "Right" case ZLSwipeableViewDirection.Up: return "Up" case ZLSwipeableViewDirection.Down: return "Down" case ZLSwipeableViewDirection.Horizontal: return "Horizontal" case ZLSwipeableViewDirection.Vertical: return "Vertical" case ZLSwipeableViewDirection.All: return "All" default: return "Unknown" } } } public class ZLSwipeableView: UIView { // MARK: - Public // MARK: Data Source public var numPrefetchedViews = 3 public var nextView: (() -> UIView?)? // MARK: Animation public var animateView: (view: UIView, index: Int, views: [UIView], swipeableView: ZLSwipeableView) -> () = { func toRadian(degree: CGFloat) -> CGFloat { return degree * CGFloat(M_PI/100) } func rotateView(view: UIView, forDegree degree: CGFloat, duration: NSTimeInterval, offsetFromCenter offset: CGPoint, swipeableView: ZLSwipeableView) { UIView.animateWithDuration(duration, delay: 0, options: .AllowUserInteraction, animations: { view.center = swipeableView.convertPoint(swipeableView.center, fromView: swipeableView.superview) var transform = CGAffineTransformMakeTranslation(offset.x, offset.y) transform = CGAffineTransformRotate(transform, toRadian(degree)) transform = CGAffineTransformTranslate(transform, -offset.x, -offset.y) view.transform = transform }, completion: nil) } return {(view: UIView, index: Int, views: [UIView], swipeableView: ZLSwipeableView) in let degree = CGFloat(1), offset = CGPoint(x: 0, y: CGRectGetHeight(swipeableView.bounds)*0.3) switch index { case 0: rotateView(view, forDegree: 0, duration: 0.4, offsetFromCenter: offset, swipeableView: swipeableView) case 1: rotateView(view, forDegree: degree, duration: 0.4, offsetFromCenter: offset, swipeableView: swipeableView) case 2: rotateView(view, forDegree: -degree, duration: 0.4, offsetFromCenter: offset, swipeableView: swipeableView) default: rotateView(view, forDegree: 0, duration: 0.4, offsetFromCenter: offset, swipeableView: swipeableView) } } }() // MARK: Delegate public var didStart: ((view: UIView, atLocation: CGPoint) -> ())? public var swiping: ((view: UIView, atLocation: CGPoint, translation: CGPoint) -> ())? public var didEnd: ((view: UIView, atLocation: CGPoint) -> ())? public var didSwipe: ((view: UIView, inDirection: ZLSwipeableViewDirection, directionVector: CGVector) -> ())? public var didCancel: ((view: UIView, translation: CGPoint) -> (Bool))? public var didTap: ((view: UIView) -> ())? // MARK: Swipe Control /// in percent public var translationThreshold = CGFloat(0.25) public var velocityThreshold = CGFloat(750) public var direction = ZLSwipeableViewDirection.Horizontal public var interpretDirection: (topView: UIView, direction: ZLSwipeableViewDirection, views: [UIView], swipeableView: ZLSwipeableView) -> (CGPoint, CGVector) = {(topView: UIView, direction: ZLSwipeableViewDirection, views: [UIView], swipeableView: ZLSwipeableView) in let programmaticSwipeVelocity = CGFloat(1500) let location = CGPoint(x: topView.center.x, y: topView.center.y*0.7) var directionVector: CGVector? switch direction { case ZLSwipeableViewDirection.Left: directionVector = CGVector(dx: -programmaticSwipeVelocity, dy: 0) case ZLSwipeableViewDirection.Right: directionVector = CGVector(dx: programmaticSwipeVelocity, dy: 0) case ZLSwipeableViewDirection.Up: directionVector = CGVector(dx: 0, dy: -programmaticSwipeVelocity) case ZLSwipeableViewDirection.Down: directionVector = CGVector(dx: 0, dy: programmaticSwipeVelocity) default: directionVector = CGVector(dx: 0, dy: 0) } return (location, directionVector!) } public func swipeTopView(inDirection direction: ZLSwipeableViewDirection) { if let topView = topView() { let (location, directionVector) = interpretDirection(topView: topView, direction: direction, views: views, swipeableView: self) swipeTopView(topView, direction: direction, location: location, directionVector: directionVector) } } public func swipeTopView(fromPoint location: CGPoint, inDirection directionVector: CGVector) { if let topView = topView() { let direction = ZLSwipeableViewDirection.fromPoint(CGPoint(x: directionVector.dx, y: directionVector.dy)) swipeTopView(topView, direction: direction, location: location, directionVector: directionVector) } } private func swipeTopView(topView: UIView, direction: ZLSwipeableViewDirection, location: CGPoint, directionVector: CGVector) { unsnapView() pushView(topView, fromPoint: location, inDirection: directionVector) removeFromViews(topView) loadViews() didSwipe?(view: topView, inDirection: direction, directionVector: directionVector) } // MARK: View Management private var views = [UIView]() public func topView() -> UIView? { return views.first } public func loadViews() { if views.count<numPrefetchedViews { for _ in (views.count..<numPrefetchedViews) { if let nextView = nextView?() { nextView.addGestureRecognizer(ZLPanGestureRecognizer(target: self, action: Selector("handlePan:"))) nextView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("handleTap:"))) views.append(nextView) containerView.addSubview(nextView) containerView.sendSubviewToBack(nextView) } } } if let _ = topView() { animateViews() } } // point: in the swipeableView's coordinate public func insertTopView(view: UIView, fromPoint point: CGPoint) { if views.contains(view) { print("Error: trying to insert a view that has been added") } else { if cleanUpWithPredicate({ aView in aView == view }).count == 0 { view.center = point } view.addGestureRecognizer(ZLPanGestureRecognizer(target: self, action: Selector("handlePan:"))) view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("handleTap:"))) views.insert(view, atIndex: 0) containerView.addSubview(view) snapView(view, toPoint: convertPoint(center, fromView: superview)) animateViews() } } private func animateViews() { if let topView = topView() { for gestureRecognizer in topView.gestureRecognizers! { if gestureRecognizer.state != .Possible { return } } } for i in (0..<views.count) { let view = views[i] view.userInteractionEnabled = i == 0 animateView(view: view, index: i, views: views, swipeableView: self) } } public func discardViews() { unsnapView() detachView() animator.removeAllBehaviors() for aView in views { removeFromContainerView(aView) } views.removeAll(keepCapacity: false) } private func removeFromViews(view: UIView) { for i in 0..<views.count { if views[i] == view { view.userInteractionEnabled = false views.removeAtIndex(i) return } } } private func removeFromContainerView(aView: UIView) { for gestureRecognizer in aView.gestureRecognizers! { if gestureRecognizer.isKindOfClass(ZLPanGestureRecognizer.classForCoder()) { aView.removeGestureRecognizer(gestureRecognizer) } } aView.removeFromSuperview() } // MARK: - Private properties private var containerView = UIView() override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { animator = UIDynamicAnimator(referenceView: self) pushAnimator = UIDynamicAnimator(referenceView: self) addSubview(containerView) addSubview(anchorContainerView) } deinit { timer?.invalidate() animator.removeAllBehaviors() pushAnimator.removeAllBehaviors() views.removeAll() pushBehaviors.removeAll() } override public func layoutSubviews() { super.layoutSubviews() containerView.frame = bounds } // MARK: Animator private var animator: UIDynamicAnimator! static private let anchorViewWidth = CGFloat(1000) private var anchorView = UIView(frame: CGRect(x: 0, y: 0, width: anchorViewWidth, height: anchorViewWidth)) private var anchorContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) func handleTap(recognizer: UITapGestureRecognizer) { let topView = recognizer.view! didTap?(view: topView) } func handlePan(recognizer: UIPanGestureRecognizer) { let translation = recognizer.translationInView(self) let location = recognizer.locationInView(self) let topView = recognizer.view! switch recognizer.state { case .Began: unsnapView() attachView(topView, toPoint: location) didStart?(view: topView, atLocation: location) case .Changed: unsnapView() attachView(topView, toPoint: location) swiping?(view: topView, atLocation: location, translation: translation) case .Ended,.Cancelled: detachView() let velocity = recognizer.velocityInView(self) let velocityMag = velocity.magnitude let directionSwiped = ZLSwipeableViewDirection.fromPoint(translation) let directionChecked = directionSwiped.intersect(direction) != .None let signChecked = CGPoint.areInSameTheDirection(translation, p2: velocity) let translationChecked = abs(translation.x) > translationThreshold * bounds.width || abs(translation.y) > translationThreshold * bounds.height let velocityChecked = velocityMag > velocityThreshold if directionChecked && signChecked && (translationChecked || velocityChecked){ let normalizedTrans = translation.normalized let throwVelocity = max(velocityMag, velocityThreshold) let directionVector = CGVector(dx: normalizedTrans.x*throwVelocity, dy: normalizedTrans.y*throwVelocity) swipeTopView(topView, direction: directionSwiped, location: location, directionVector: directionVector) // pushView(topView, fromPoint: location, inDirection: directionVector) // removeFromViews(topView) // didSwipe?(view: topView, inDirection: ZLSwipeableViewDirection.fromPoint(translation)) // loadViews() }else { let shouldSnapBack = didCancel?(view: topView, translation: translation) if (shouldSnapBack!){ snapView(topView, toPoint: convertPoint(center, fromView: superview)) } } didEnd?(view: topView, atLocation: location) default: break } } private var snapBehavior: UISnapBehavior? private func snapView(aView: UIView, toPoint point: CGPoint) { unsnapView() snapBehavior = UISnapBehavior(item: aView, snapToPoint: point) snapBehavior!.damping = 0.75 animator.addBehavior(snapBehavior!) } private func unsnapView() { if snapBehavior != nil{ animator.removeBehavior(snapBehavior!) snapBehavior = nil } } private var touchOffset = CGPointZero private var attachmentViewToAnchorView: UIAttachmentBehavior? private var attachmentAnchorViewToPoint: UIAttachmentBehavior? private func attachView(aView: UIView, toPoint point: CGPoint) { if let _ = attachmentViewToAnchorView, attachmentAnchorViewToPoint = attachmentAnchorViewToPoint { var p = point p.x = point.x + touchOffset.x p.y = point.y + touchOffset.y attachmentAnchorViewToPoint.anchorPoint = p } else { let center = aView.center let offset : CGFloat = 22 touchOffset.x = center.x - point.x touchOffset.y = center.y - point.y - offset var newp = point newp.x = point.x + touchOffset.x newp.y = point.y + touchOffset.y anchorView.center = newp anchorView.backgroundColor = UIColor.blueColor() anchorView.hidden = true anchorContainerView.addSubview(anchorView) // attach aView to anchorView attachmentViewToAnchorView = UIAttachmentBehavior(item: aView, offsetFromCenter: UIOffset(horizontal: -(center.x - newp.x), vertical: -(center.y - newp.y + offset)), attachedToItem: anchorView, offsetFromCenter: UIOffsetZero) attachmentViewToAnchorView!.length = 0 // attach anchorView to point attachmentAnchorViewToPoint = UIAttachmentBehavior(item: anchorView, offsetFromCenter: UIOffsetMake(0, offset), attachedToAnchor: newp) attachmentAnchorViewToPoint!.damping = 5 attachmentAnchorViewToPoint!.length = 0 animator.addBehavior(attachmentViewToAnchorView!) animator.addBehavior(attachmentAnchorViewToPoint!) } } private func detachView() { if attachmentViewToAnchorView != nil{ animator.removeBehavior(attachmentViewToAnchorView!) animator.removeBehavior(attachmentAnchorViewToPoint!) } attachmentViewToAnchorView = nil attachmentAnchorViewToPoint = nil } // MARK: pushAnimator private var pushAnimator: UIDynamicAnimator! private var timer: NSTimer? private var pushBehaviors = [(UIView, UIView, UIAttachmentBehavior, UIPushBehavior)]() func cleanUp(timer: NSTimer) { cleanUpWithPredicate() { aView in !CGRectIntersectsRect(self.convertRect(aView.frame, toView: nil), UIScreen.mainScreen().bounds) } if pushBehaviors.count == 0 { timer.invalidate() self.timer = nil } } private func cleanUpWithPredicate(predicate: (UIView) -> Bool) -> [Int] { var indexes = [Int]() for i in 0..<pushBehaviors.count { let (anchorView, aView, attachment, push) = pushBehaviors[i] if predicate(aView) { anchorView.removeFromSuperview() removeFromContainerView(aView) pushAnimator.removeBehavior(attachment) pushAnimator.removeBehavior(push) indexes.append(i) } } for index in indexes.reverse() { pushBehaviors.removeAtIndex(index) } return indexes } private func pushView(aView: UIView, fromPoint point: CGPoint, inDirection direction: CGVector) { let anchorView = UIView(frame: CGRect(x: 0, y: 0, width: ZLSwipeableView.anchorViewWidth, height: ZLSwipeableView.anchorViewWidth)) anchorView.center = point anchorView.backgroundColor = UIColor.greenColor() anchorView.hidden = true anchorContainerView.addSubview(anchorView) let p = aView.convertPoint(aView.center, fromView: aView.superview) let point = aView.convertPoint(point, fromView: aView.superview) let attachmentViewToAnchorView = UIAttachmentBehavior(item: aView, offsetFromCenter: UIOffset(horizontal: -(p.x - point.x), vertical: -(p.y - point.y)), attachedToItem: anchorView, offsetFromCenter: UIOffsetZero) attachmentViewToAnchorView.length = 0 let pushBehavior = UIPushBehavior(items: [anchorView], mode: .Instantaneous) pushBehavior.pushDirection = direction pushAnimator.addBehavior(attachmentViewToAnchorView) pushAnimator.addBehavior(pushBehavior) pushBehaviors.append((anchorView, aView, attachmentViewToAnchorView, pushBehavior)) if timer == nil { timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "cleanUp:", userInfo: nil, repeats: true) } } // MARK: - () } extension CGPoint { var normalized: CGPoint { return CGPoint(x: x/magnitude, y: y/magnitude) } var magnitude: CGFloat { return CGFloat(sqrtf(powf(Float(x), 2) + powf(Float(y), 2))) } static func areInSameTheDirection(p1: CGPoint, p2: CGPoint) -> Bool { func signNum(n: CGFloat) -> Int { return (n < 0.0) ? -1 : (n > 0.0) ? +1 : 0 } return signNum(p1.x) == signNum(p2.x) && signNum(p1.y) == signNum(p2.y) } }
9962ec3631e15579e15e6ac8e99a0d40
40.165984
271
0.626711
false
false
false
false
pixlwave/Countout
refs/heads/main
Sources/Models/Length.swift
mpl-2.0
1
import Foundation struct Length: Codable, Equatable { var minutes: Int var seconds: Int { didSet { if seconds > 59 { let total = timeInterval minutes = Int((total / 60).rounded(.down)) seconds = Int(total.truncatingRemainder(dividingBy: 60)) } } } init(timeInterval: TimeInterval) { minutes = Int((timeInterval / 60).rounded(.down)) seconds = Int(timeInterval.truncatingRemainder(dividingBy: 60)) } var timeInterval: TimeInterval { TimeInterval((minutes * 60) + seconds) } }
095a29d86176b6ec05835a82d7fbe5a4
28.238095
77
0.57329
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
OmniKitTests/PodCommsSessionTests.swift
mit
1
// // PodCommsSessionTests.swift // OmniKitTests // // Created by Pete Schwamb on 3/25/19. // Copyright © 2019 Pete Schwamb. All rights reserved. // import Foundation import XCTest @testable import OmniKit class PodCommsSessionTests: XCTestCase { let address: UInt32 = 521580830 var podState: PodState! var mockTransport: MockMessageTransport! var lastPodStateUpdate: PodState? override func setUp() { podState = PodState(address: address, pmVersion: "2.7.0", piVersion: "2.7.0", lot: 43620, tid: 560313, insulinType: .novolog) mockTransport = MockMessageTransport(address: podState.address, messageNumber: 5) } func testNonceResync() { // From https://raw.githubusercontent.com/wiki/openaps/openomni/Full-life-of-a-pod-(omni-flo).md // 2018-05-25T13:03:51.765792 pod Message(ffffffff seq:01 [OmniKitPacketParser.VersionResponse(blockType: OmniKitPacketParser.MessageBlockType.versionResponse, lot: 43620, tid: 560313, address: Optional(521580830), pmVersion: 2.7.0, piVersion: 2.7.0, data: 23 bytes)]) do { // 2018-05-26T09:11:08.580347 pod Message(1f16b11e seq:06 [OmniKitPacketParser.ErrorResponse(blockType: OmniKitPacketParser.MessageBlockType.errorResponse, errorReponseType: OmniKitPacketParser.ErrorResponse.ErrorReponseType.badNonce, nonceSearchKey: 43492, data: 5 bytes)]) mockTransport.addResponse(try ErrorResponse(encodedData: Data(hexadecimalString: "060314a9e403f5")!)) mockTransport.addResponse(try StatusResponse(encodedData: Data(hexadecimalString: "1d5800d1a8140012e3ff8018")!)) } catch (let error) { XCTFail("message decoding threw error: \(error)") return } let session = PodCommsSession(podState: podState, transport: mockTransport, delegate: self) // 2018-05-26T09:11:07.984983 pdm Message(1f16b11e seq:05 [SetInsulinScheduleCommand(nonce:2232447658, bolus(units: 1.0, timeBetweenPulses: 2.0)), OmniKitPacketParser.BolusExtraCommand(blockType: OmniKitPacketParser.MessageBlockType.bolusExtra, completionBeep: false, programReminderInterval: 0.0, units: 1.0, timeBetweenPulses: 2.0, squareWaveUnits: 0.0, squareWaveDuration: 0.0)]) let bolusDelivery = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: 1.0, timeBetweenPulses: 2.0) let sentCommand = SetInsulinScheduleCommand(nonce: 2232447658, deliverySchedule: bolusDelivery) do { let status: StatusResponse = try session.send([sentCommand]) XCTAssertEqual(2, mockTransport.sentMessages.count) let bolusTry1 = mockTransport.sentMessages[0].messageBlocks[0] as! SetInsulinScheduleCommand XCTAssertEqual(2232447658, bolusTry1.nonce) let bolusTry2 = mockTransport.sentMessages[1].messageBlocks[0] as! SetInsulinScheduleCommand XCTAssertEqual(1521036535, bolusTry2.nonce) XCTAssert(status.deliveryStatus.bolusing) } catch (let error) { XCTFail("message sending error: \(error)") } // Try sending another bolus command: nonce should be 676940027 XCTAssertEqual(545302454, lastPodStateUpdate!.currentNonce) let _ = session.bolus(units: 2, automatic: false) let bolusTry3 = mockTransport.sentMessages[2].messageBlocks[0] as! SetInsulinScheduleCommand XCTAssertEqual(545302454, bolusTry3.nonce) } func testUnacknowledgedBolus() { let session = PodCommsSession(podState: podState, transport: mockTransport, delegate: self) mockTransport.throwSendMessageError = PodCommsError.unacknowledgedMessage(sequenceNumber: 5, error: PodCommsError.noResponse) let _ = session.bolus(units: 3) XCTAssertNotNil(lastPodStateUpdate?.unacknowledgedCommand) } func testSuccessfulBolus() { let session = PodCommsSession(podState: podState, transport: mockTransport, delegate: self) let statusResponse = StatusResponse( deliveryStatus: .bolusInProgress, podProgressStatus: .aboveFiftyUnits, timeActive: .minutes(10), reservoirLevel: Pod.reservoirLevelAboveThresholdMagicNumber, insulinDelivered: 25, bolusNotDelivered: 0, lastProgrammingMessageSeqNum: 5, alerts: AlertSet(slots: [])) mockTransport.addResponse(statusResponse) let _ = session.bolus(units: 3) XCTAssertNil(lastPodStateUpdate?.unacknowledgedCommand) XCTAssertNotNil(lastPodStateUpdate?.unfinalizedBolus) } } extension PodCommsSessionTests: PodCommsSessionDelegate { func podCommsSession(_ podCommsSession: PodCommsSession, didChange state: PodState) { lastPodStateUpdate = state } } class MockMessageTransport: MessageTransport { var delegate: MessageTransportDelegate? var messageNumber: Int var responseMessageBlocks = [MessageBlock]() public var sentMessages = [Message]() var throwSendMessageError: Error? var address: UInt32 var sentMessageHandler: ((Message) -> Void)? init(address: UInt32, messageNumber: Int) { self.address = address self.messageNumber = messageNumber } func sendMessage(_ message: Message) throws -> Message { sentMessages.append(message) if let error = throwSendMessageError { throw error } if responseMessageBlocks.isEmpty { throw PodCommsError.noResponse } return Message(address: address, messageBlocks: [responseMessageBlocks.removeFirst()], sequenceNum: messageNumber) } func addResponse(_ messageBlock: MessageBlock) { responseMessageBlocks.append(messageBlock) } func assertOnSessionQueue() { // Do nothing in tests } }
ef7efe7b7169761e8410503d8f1df623
36.384615
390
0.705761
false
true
false
false
oklasoftLLC/OKSGutteredCodeView
refs/heads/master
OKSGutteredCodeView/OKSGutteredCodeView.swift
mit
1
// // OKSGutteredCodeView.swift // OKSGutteredCodeView // // Created by Justin Oakes on 5/12/16. // Copyright © 2016 Oklasoft LLC. All rights reserved. // import UIKit open class OKSGutteredCodeView: UIView, UITextViewDelegate, UIScrollViewDelegate { @IBOutlet weak var gutterView: UIScrollView! @IBOutlet weak var textView: UITextView! open var delegate: CodeViewDelegate? //Properties set by users var viewFont: UIFont? var fontColor: UIColor? // initalization fileprivate var numberOfLines = 1 fileprivate var gutterSubViews: [UILabel] = [] func xibSetUp() { let xibView: UIView = loadFromXib() xibView.frame = bounds xibView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] addSubview(xibView) } func loadFromXib() -> UIView { let bundle: Bundle = Bundle(for: type(of: self)) let xib: UINib = UINib(nibName: "OKSGutteredCodeView", bundle: bundle) let view: UIView = xib.instantiate(withOwner: self, options: nil)[0] as! UIView return view } override init(frame: CGRect) { super.init(frame: frame) xibSetUp() addObserver(self, forKeyPath: "bounds", options: .initial, context: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) textViewDidChange(textView) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetUp() addObserver(self, forKeyPath: "bounds", options: .initial, context: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) textViewDidChange(textView) } //MARK: custimization methods @objc open func setGutterBackgroundColor(_ color: UIColor) { gutterView.backgroundColor = color } @objc open func setfont(_ font: UIFont) { viewFont = font textView.font = font } @objc open func setText(_ text: String) { textView.text = text } @objc open func getText() -> String { return textView.text } @objc open func getFont() -> UIFont? { return viewFont } @objc open func addTextViewAccessoryView(_ toolbar: UIToolbar) { toolbar.sizeToFit() textView.inputAccessoryView = toolbar } @objc open func insertTextAtCurser(_ text: String) { textView.replace(textView.selectedTextRange ?? UITextRange() , withText: text) } @objc open func appendText(_ text: String) { textView.text = "\(textView.text)\(text)" } @objc open func setAttributedText(_ text: NSAttributedString) { let curserPosition: NSRange = textView.selectedRange textView.attributedText = text textView.selectedRange = curserPosition } @objc open func addFontColor(_ color: UIColor) { fontColor = color textView.textColor = color } @objc open func setTextViewBackgroundColor(_ color: UIColor) { textView.backgroundColor = color } //MARK: UITextView Delegate Methods @objc open func textViewDidChange(_ textView: UITextView) { for label in gutterSubViews { label.removeFromSuperview() } numberOfLines = countNumberOfLines() addNumberToGutter() delegate?.textUpdated(textView.text) } @objc func keyboardWillShow(_ notification: Notification) { delegate?.keyboardWillAppear(notification) } @objc func keyboardWillHide(_ notification: Notification) { delegate?.keyboardWillHide(notification) } //MARK: UIScrollView Delegate Mathods @objc open func scrollViewDidScroll(_ scrollView: UIScrollView) { let yOffSet = textView.contentOffset.y gutterView.scrollRectToVisible(CGRect(x: 0, y: yOffSet, width: gutterView.frame.width, height: gutterView.frame.height), animated: false) } //MARK: sorting out number and location of lines func countNumberOfLines() -> Int { let text = textView.text let seperatedLines = text?.components(separatedBy: "\n") let newLines = seperatedLines?.count ?? 0 return newLines > 0 ? newLines - 1 : newLines } func addNumberToGutter() { let curserPosition = textView.caretRect(for: textView.selectedTextRange?.start ?? UITextRange().start).origin let text: String = textView.text let seperatedLines: [String] = text.components(separatedBy: "\n") var numberInsertionPoint: CGFloat = 8 gutterView.contentSize = gutterView.frame.size var counter: Int = 1 for line in seperatedLines { let label: UILabel = UILabel(frame: CGRect(x: 0, y: numberInsertionPoint, width: 35, height: (textView.font ?? UIFont.preferredFont(forTextStyle: .body)).lineHeight)) label.font = viewFont ?? UIFont(name: "Courier New", size: 17.0) label.textAlignment = .right label.text = "\(counter)" label.textColor = fontColor ?? UIColor.black gutterView.addSubview(label) gutterSubViews.append(label) counter += 1 numberInsertionPoint += heightOfLine(line) if numberInsertionPoint > gutterView.contentSize.height { let contentHeight = gutterView.contentSize.height let contentWidth = gutterView.contentSize.width gutterView.contentSize = CGSize(width: contentWidth, height: contentHeight + heightOfLine(line)) } } textView.scrollRectToVisible(CGRect(x: 0, y: curserPosition.y, width: textView.bounds.width, height: textView.bounds.height), animated: false) gutterView.scrollRectToVisible(CGRect(x: 0, y: curserPosition.y, width: textView.bounds.width, height: textView.bounds.height), animated: false) } func heightOfLine(_ line: String) -> CGFloat { let font: UIFont = textView.font ?? UIFont.preferredFont(forTextStyle: .body) let textViewWidth: CGFloat = textView.bounds.width let lineHeight = line.boundingRect(with: CGSize(width: textViewWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : font], context: nil).height return lineHeight } //MARK: KVO methods // recalcualtes and redraws everything relavent to where text is positioned on the screen when the bounds of the view chnges // (rotation, splitview, priview window sliding over etc...) override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath != nil && keyPath == "bounds" && ((object as AnyObject).isEqual(self)) { perform(#selector(textViewDidChange), with: textView, afterDelay: 0.51) } } }
58bde5abcd7d7bd9d52a306a449bc534
38.426316
223
0.662261
false
false
false
false
sashohadz/swift
refs/heads/master
exam/exam/exam/RegisterViewController.swift
mit
1
// // RegisterViewController.swift // exam // // Created by Sasho Hadzhiev on 2/18/17. // Copyright © 2017 Sasho Hadzhiev. All rights reserved. // import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var verifyPasswordTextField: UITextField! @IBOutlet weak var gsmNumberTextField: UITextField! @IBOutlet weak var registerButton: UIButton! var dataDictionary:[String:Any?] = [String:Any?]() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func registerButtonPressed(_ sender: UIButton) { let name = nameTextField.text let username = userNameTextField.text let password = passwordTextField.text let gsmNumber = gsmNumberTextField.text self.dataDictionary[UserDefaultKeys.username.rawValue] = username self.dataDictionary[UserDefaultKeys.name.rawValue] = name self.dataDictionary[UserDefaultKeys.password.rawValue] = password self.dataDictionary[UserDefaultKeys.gsmNumber.rawValue] = gsmNumber DataCommunication.instance.registerUser(info: self.dataDictionary) UserDefaults.standard.set(true, forKey: UserDefaultKeys.autoLoginEnabled.rawValue) UserDefaults.standard.set(username, forKey: UserDefaultKeys.username.rawValue) UserDefaults.standard.set(password, forKey: UserDefaultKeys.password.rawValue) self.modalTransitionStyle = .crossDissolve self.present(UIStoryboard.init(name: "Main", bundle: nil).instantiateInitialViewController()!, animated: true, completion: nil) } }
56b37a1ab0690b88c84b970432f4c8b5
38.340426
135
0.72742
false
false
false
false
wyszo/TWCommonLib
refs/heads/master
TWCommonLib/TWCommonLib/TWTableViewScrollHandlingDelegate.swift
mit
1
import UIKit enum ScrollHandlingDelegateError : Error { case tableViewFooterMissingError } /** Sets the tableView delegate to itself and then notifies when tableView footer becomes visible or is scrolled out of a visible area */ open class TWTableViewScrollHandlingDelegate: NSObject, UITableViewDelegate { fileprivate var footerVisibleValue : Bool fileprivate var tableView : UITableView fileprivate var tableViewDelegates : LBDelegateMatrioska? open var didScrollToFooter: (()->Void)? open var didScrollAboveFooter: (()->Void)? public init(tableView : UITableView, fallbackDelegate : UITableViewDelegate) throws { self.tableView = tableView self.footerVisibleValue = false super.init() self.tableViewDelegates = LBDelegateMatrioska.init(delegates: [fallbackDelegate, self]) self.tableView.delegate = self.tableViewDelegates as? UITableViewDelegate guard let _ = tableView.tableFooterView else { throw ScrollHandlingDelegateError.tableViewFooterMissingError } } /** Forces updating internal state. You might want to call this for example from viewDidAppear if you need to ensure correct state before user did scroll */ open func updateFooterVisibleValue() { if let visible = try? isFooterViewVisible() { footerVisibleValue = visible } } // MARK: UITableViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { checkDidScrollToFooter() checkDidScrollAboveFooter() } // MARK: private fileprivate func checkDidScrollToFooter() { let footerVisible = try? isFooterViewVisible() if !footerVisibleValue && footerVisible == true { footerVisibleValue = true didScrollToFooter?() } } fileprivate func checkDidScrollAboveFooter() { let footerVisible = try? isFooterViewVisible() if footerVisibleValue && footerVisible == false { footerVisibleValue = false didScrollAboveFooter?() } } fileprivate func isFooterViewVisible() throws -> Bool { let currentBottomOffset = tableView.contentOffset.y + tableView.frame.size.height guard let footerView = tableView.tableFooterView else { throw ScrollHandlingDelegateError.tableViewFooterMissingError } let footerOffset = footerView.frame.origin.y return (currentBottomOffset >= footerOffset) } }
fd58812fdb164ff682362226377a32a1
29.21519
152
0.731043
false
false
false
false
Jnosh/swift
refs/heads/master
test/SILGen/generic_property_base_lifetime.swift
apache-2.0
14
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s protocol ProtocolA: class { var intProp: Int { get set } } protocol ProtocolB { var intProp: Int { get } } @objc protocol ProtocolO: class { var intProp: Int { get set } } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> Int { // CHECK: bb0([[ARG:%.*]] : $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!getter.1 : {{.*}}, [[PROJECTION]] // CHECK: [[RESULT:%.*]] = apply [[WITNESS_METHOD]]<@opened{{.*}}>([[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF' func getIntPropExistential(_ a: ProtocolA) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> () { // CHECK: bb0([[ARG:%.*]] : $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!setter.1 : {{.*}}, [[PROJECTION]] // CHECK: apply [[WITNESS_METHOD]]<@opened{{.*}}>({{%.*}}, [[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF' func setIntPropExistential(_ a: ProtocolA) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolA>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolA>(_ a: T) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolB_pF // CHECK: [[PROJECTION:%.*]] = open_existential_addr immutable_access %0 // CHECK: [[STACK:%[0-9]+]] = alloc_stack $@opened({{".*"}}) ProtocolB // CHECK: copy_addr [[PROJECTION]] to [initialization] [[STACK]] // CHECK: apply {{%.*}}([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropExistential(_ a: ProtocolB) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: apply {{%.*}}<T>([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropGeneric<T: ProtocolB>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> Int { // CHECK: bb0([[ARG:%.*]] : $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!getter.1.foreign : {{.*}}, [[PROJECTION]] // CHECK: apply [[METHOD]]<@opened{{.*}}>([[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF' func getIntPropExistential(_ a: ProtocolO) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> () { // CHECK: bb0([[ARG:%.*]] : $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!setter.1.foreign : {{.*}}, [[PROJECTION]] // CHECK: apply [[METHOD]]<@opened{{.*}}>({{.*}}, [[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF' func setIntPropExistential(_ a: ProtocolO) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolO>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolO>(_ a: T) { a.intProp = 0 }
9246e593b208db593a5637771d405292
46.768116
152
0.629703
false
false
false
false
mozilla-magnet/magnet-client
refs/heads/master
ios/ApiPreferences.swift
mpl-2.0
1
// // ApiPreferences.swift // magnet // // Created by sam on 11/7/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import SwiftyJSON class ApiPreferences: ApiBase { private let store: RequestStore private static let PATH = "content://preferences" private let lockQueue = dispatch_queue_create("com.mozilla.magnet.apipreferences", nil) override init() { store = RequestStore.getInstance() super.init() } private func mergeDefaults(inout json: JSON) { for pref in kDefaultPreferences { if !json[pref[0]].exists() { json[pref[0]].string = pref[1]; } } } override func get(path: String, callback: ApiCallback) { if var json = store.getJSON(ApiPreferences.PATH) { mergeDefaults(&json) callback.onSuccess(json) } else { var json = JSON(""); mergeDefaults(&json); callback.onSuccess(json) } } override func post(path: String, data: NSDictionary, callback: ApiCallback) { var json = JSON("{}"); // Lock this section to prevent any non-atomic updates to the JSON in // the RequestStore dispatch_sync(lockQueue) { if let storedJson = store.getJSON(ApiPreferences.PATH) { json = storedJson } // Coerce the value to a string with '.description' let value: String = data["value"]!.description let prefKey = data["pref_key"] as! String json[prefKey] = JSON(tryAsBooleanString(value)) store.setJSON(ApiPreferences.PATH, value: json) } callback.onSuccess(json) } override func delete(path: String, data: NSDictionary, callback: ApiCallback) { var json = JSON("{}"); // Lock this section to prevent any non-atomic updates to the JSON in // the RequestStore dispatch_sync(lockQueue) { if var storeJson = store.getJSON(ApiPreferences.PATH) { storeJson[data["pref_key"] as! String] = nil json = storeJson store.setJSON(ApiPreferences.PATH, value: storeJson) } } callback.onSuccess(json) } } // Given a string, try and alias it to 'true' or 'false' if. // If it cannot be aliased return the string as is. // We use this because the JavaScript at the moment expects only // booleans for preferences, but we want to support aribitrary types // in the future. func tryAsBooleanString(value: String) -> String { switch(value) { case "0": return "false" case "1": return "true" case "true": return "true" case "false": return "false" default: return value } }
039a4d29d3aca83fddc463b8190ad675
25.5625
89
0.65451
false
false
false
false
haitran2011/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Views/Loader/LoaderView.swift
mit
1
// // LoaderView.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 11/04/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit class LoaderView: UIView { var isAnimating = false public final func startAnimating() { isHidden = false isAnimating = true layer.speed = 1 layer.sublayers = nil setupLayersAndAnimation(in: self.layer, size: CGSize(width: 42, height: 42)) } public final func stopAnimating() { isHidden = true isAnimating = false layer.sublayers?.removeAll() } func setupLayersAndAnimation(in layer: CALayer, size: CGSize) { let circleSpacing: CGFloat = 4 let circleSize: CGFloat = 10 let circleRadius = circleSize / 2 let fillColor = UIColor.RCDarkBlue().cgColor let x: CGFloat = (layer.bounds.size.width - size.width) / 2 let y: CGFloat = (layer.bounds.size.height - circleSize) / 2 let duration: CFTimeInterval = 1.4 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, 0.16, 0.32] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let animation = CAKeyframeAnimation(keyPath: "transform.scale") // Animation animation.timingFunctions = [timingFunction, timingFunction] animation.values = [0, 1, 0] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 3 { let circleLayer: CAShapeLayer = CAShapeLayer() let path: UIBezierPath = UIBezierPath() path.addArc( withCenter: CGPoint(x: circleRadius, y: circleRadius), radius: circleRadius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false ) circleLayer.fillColor = fillColor circleLayer.backgroundColor = nil circleLayer.path = path.cgPath circleLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) let circle = circleLayer as CALayer let frame = CGRect( x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), y: y, width: circleSize, height: circleSize ) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } }
b57d2ca60753ecb985398738af78e07c
31.108434
93
0.591745
false
false
false
false
pfvernon2/swiftlets
refs/heads/master
iOSX/Platform.swift
apache-2.0
1
// // Platform.swift // swiftlets // // Created by Frank Vernon on 7/21/16. // Copyright © 2016 Frank Vernon. All rights reserved. // import Foundation public struct Platform { static var isSimulator: Bool { TARGET_OS_SIMULATOR != 0 } static var isIPhone: Bool { TARGET_OS_IPHONE != 0 } static var isIOS: Bool { TARGET_OS_IOS != 0 } static var isWatch: Bool { TARGET_OS_WATCH != 0 } static var isTV: Bool { TARGET_OS_TV != 0 } static var isMac: Bool { TARGET_OS_MAC != 0 } static var isUnix: Bool { TARGET_OS_UNIX != 0 } static var isCrap: Bool { TARGET_OS_WIN32 != 0 } }
ec54d4913d3079f9574964cb766b04c9
15.581395
55
0.548387
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/394-multidimensional-15.swift
apache-2.0
4
import assert; () f () { int A[][]; A = g(); // Check that this works ok with constant folding, etc assertEqual(A[0][0], 1, "[0][0]"); assertEqual(A[0][1], 2, "[0][1]"); assertEqual(A[1][1], 3, "[1][1]"); assertEqual(A[1][0], 3, "[1][0]"); } main { f(); } (int A[][]) g () { int x = 4; int y = 2; A[(0+2)*3 - 6][0] = 1; A[x - 2*y][1] = 2; A[1][1] = 3; A[1][0] = 3; trace(A[(0+2)*3 - 6][0], A[x - 2*y][1], A[1][1], A[1][0]); }
3d72a7f0a78b6a1b6677ca4aa3e8e212
17.185185
62
0.391039
false
false
false
false
noehou/myDouYuZB
refs/heads/master
DYZB/DYZB/Classes/Home/ViewModel/RecommendViewModel.swift
mit
1
// // RecommendViewModel.swift // DYZB // // Created by Tommaso on 2016/12/10. // Copyright © 2016年 Tommaso. All rights reserved. // import UIKit class RecommendViewModel : BaseViewModel { lazy var cycleModels : [CycleModel] = [CycleModel]() public lazy var bigDataGroup : AnchorGroup = AnchorGroup() public lazy var prettyGroup : AnchorGroup = AnchorGroup() } //MARK:-发送网络请求 extension RecommendViewModel { func requestData(finishCallback : @escaping () -> ()){ //0、定义参数 let parameters = ["limit" : "4","offset" : "0","time" : Date.getCurrentTime()] let dGroup = DispatchGroup() //1、请求第一部分推荐数据 dGroup.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime() as NSString], finishedCallback:{(result) in //1、将result转为字典类型 guard let resultDict = result as? [String : NSObject] else {return} //2、根据data的key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3、遍历数组,获取字典,并且字典转成模型对象 //3.2设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" //3.3获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } //3.4离开组 dGroup.leave() }) //2、请求第二部分颜值数据 dGroup.enter() NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters as [String : NSString]?, finishedCallback:{(result) in //1、将result转为字典类型 guard let resultDict = result as? [String : NSObject] else {return} //2、根据data的key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3、遍历数组,获取字典,并且字典转成模型对象 //3.2设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" //3.3获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } dGroup.leave() }) //3、请求后面部分游戏数据 dGroup.enter() loadAnchorData(URLString: "http://capi.douyucdn.cn/api/v1/getHotCate",parameters: parameters, finishedCallback:{(result) in dGroup.leave() }) // NetworkTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters as [String : NSString]?, finishedCallback:{(result) in // //1、将result转为字典类型 // guard let resultDict = result as? [String : NSObject] else {return} // // //2、根据data的key,获取数组 // guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} // // //3、遍历数组,获取字典,并且字典转成模型对象 // for dict in dataArray { // let group = AnchorGroup(dict: dict) // self.anchorGroups.append(group) // } // //3.2离开组 // dGroup.leave() // }) //6、所有的数据都请求到,之后进行排序 dGroup.notify(queue: DispatchQueue.main){ self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } //请求无限轮播的数据 func requestCycleData(finishCallback : @escaping () -> ()){ NetworkTools.requestData(type: .GET, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"], finishedCallback: { (result) in //1、获取整体字典数据 guard let resultDict = result as? [String : NSObject] else { return } //2、根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3、字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict : dict)) } finishCallback() }) } }
aaa35579c6ff86168877fbbb50dcc70d
35.418033
192
0.544902
false
false
false
false
PurpleSweetPotatoes/SwiftKit
refs/heads/master
SwiftKit/tool/BQImagePicker.swift
apache-2.0
1
// // BQImagePicker.swift // HaoJiLai // // Created by baiqiang on 16/11/7. // Copyright © 2016年 baiqiang. All rights reserved. // import UIKit enum ClipSizeType { case system case none case oneScaleOne case twoScaleOne case threeScaleTwo } /** 需要在info.plist 文件中添加字段 Privacy - Photo Library Usage Description //是否允许访问相册 Privacy - Camera Usage Description //是否允许是使用相机 */ class BQImagePicker: NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate { //MARK: - ***** Ivars ***** //单例写法 private static let sharedInstance = BQImagePicker() private var handle: ((UIImage) -> ())! private var moreHandle: (([UIImage]) ->())! private var imagePicker: UIImagePickerController! private var type:ClipSizeType! private override init() { super.init() self.imagePicker = UIImagePickerController() self.imagePicker.delegate = self; } //MARK: - ***** Class Method ***** class func showPicker(type:ClipSizeType = .none, handle:@escaping (UIImage) -> Void) -> Void { let picker = BQImagePicker.sharedInstance picker.type = type picker.handle = handle var strDatas:[String] = [] if UIImagePickerController.isSourceTypeAvailable(.camera) { strDatas.append("拍照") } strDatas.append("相册") BQSheetView.showSheetView(tableDatas: strDatas, title: "获取图像方式") { (index) in if strDatas[index] == "拍照" { picker.showImagePickVc(type: .camera) }else { picker.showImagePickVc(type: .photoLibrary) } } } class func showPicker( handle:@escaping ([UIImage]) -> ()) { let picker = BQImagePicker.sharedInstance picker.moreHandle = handle var strDatas:[String] = [] if UIImagePickerController.isSourceTypeAvailable(.camera) { strDatas.append("拍照") } strDatas.append("相册") BQSheetView.showSheetView(tableDatas: strDatas, title: "获取图像方式") { (index) in if strDatas[index] == "拍照" { picker.showImagePickVc(type: .camera) }else { picker.showImagePickVc(type: .photoLibrary) } } } //MARK: - ***** initialize Method ***** private func showImagePickVc(type:UIImagePickerController.SourceType) -> Void { self.imagePicker.sourceType = type self.imagePicker.allowsEditing = self.type == ClipSizeType.system UIViewController.currentVc()?.present(self.imagePicker, animated: true, completion: nil) } //MARK: - ***** Instance Method ***** //MARK: - ***** LoadData Method ***** //MARK: - ***** create Method ***** //MARK: - ***** respond event Method ***** //MARK: - ***** Protocol ***** func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard var image = info["UIImagePickerControllerOriginalImage"] as? UIImage else{ picker.dismiss(animated: true, completion: nil) return } if self.type == ClipSizeType.none { self.handle(image) picker.dismiss(animated: true, completion: nil) }else if self.type == ClipSizeType.system { image = info["UIImagePickerControllerEditedImage"] as! UIImage self.handle(image) picker.dismiss(animated: true, completion: nil) }else { picker.dismiss(animated: true, completion: { BQClipView.showClipView(image: image, type: self.type, handle: self.handle) }) } } } class BQClipView: UIView { //MARK: - ***** Ivars ***** var image: UIImage! var type: ClipSizeType var imageView: UIImageView! var clipLayer: CAShapeLayer! var handle:((UIImage) -> Void)? var startCenter: CGPoint = CGPoint(x: 0, y: 0) var startSacle: CGFloat = 0 //MARK: - ***** Lifecycle ***** //MARK: - ***** Class Method ***** class func showClipView(image:UIImage, type:ClipSizeType ,handle:((UIImage) -> Void)?) { let clipView = BQClipView.init(image: image, type: type) clipView.handle = handle UIApplication.shared.keyWindow?.addSubview(clipView) } //MARK: - ***** initialize Method ***** init(image:UIImage, type:ClipSizeType) { //调用父类的构造函数 self.image = image self.type = type super.init(frame: UIScreen.main.bounds) self.initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - ***** Instance Method ***** func initUI() { self.backgroundColor = UIColor.gray self.imageView = UIImageView(image: self.image) self.imageView.frame = CGRect(x: 0, y: 0, width: self.sizeW, height: self.image.size.height * self.sizeW / self.image.size.width) self.imageView.center = self.center self.imageView.isUserInteractionEnabled = true let pan = UIPanGestureRecognizer(target: self, action: #selector(gestureRecognizerChange(gesture:))) self.imageView.addGestureRecognizer(pan) let pinch = UIPinchGestureRecognizer(target: self, action: #selector(gestureRecognizerChange(gesture:))) self.imageView.addGestureRecognizer(pinch) self.addSubview(self.imageView) self.createLayer() self.createBtn(frame: CGRect(x: 40, y: self.sizeH - 70, width: 50, height: 30), title: "取消", tag: 100) self.createBtn(frame: CGRect(x: self.sizeW - 90, y: self.sizeH - 70, width: 50, height: 30), title: "裁剪", tag: 101) } func createLayer() { self.clipLayer = CAShapeLayer() var width = self.sizeW / 4.0 var height: CGFloat = 0 switch self.type { case ClipSizeType.oneScaleOne: width = self.sizeW / 3.0 height = width break case ClipSizeType.twoScaleOne: height = width; width *= 2; break case ClipSizeType.threeScaleTwo: height = width * 2; width *= 3; break default: break } self.clipLayer.frame = CGRect(x: 0, y: 0, width: width, height: height) self.clipLayer.position = self.center let length:CGFloat = 20 let path = UIBezierPath() //左上角 path.move(to: CGPoint(x: 0, y: length)) path.addLine(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: length, y: 0)) //右上角 path.move(to: CGPoint(x: width - length, y: 0)) path.addLine(to: CGPoint(x: width, y: 0)) path.addLine(to: CGPoint(x: width, y: length)) //右下角 path.move(to: CGPoint(x: width, y: height - length)) path.addLine(to: CGPoint(x: width, y: height)) path.addLine(to: CGPoint(x: width - 20, y: height)) //左下角 path.move(to: CGPoint(x: length, y: height)) path.addLine(to: CGPoint(x: 0, y: height)) path.addLine(to: CGPoint(x: 0, y: height - length)) self.clipLayer.path = path.cgPath self.clipLayer.lineWidth = 3.0 self.clipLayer.strokeColor = UIColor.green.cgColor self.clipLayer.fillColor = UIColor.clear.cgColor width = self.sizeW height = self.sizeH self.addMaskLayer(frame: CGRect(x: 0, y: 0, width: width, height: self.clipLayer.frame.origin.y)) self.addMaskLayer(frame: CGRect(x: 0, y: self.clipLayer.frame.origin.y, width: self.clipLayer.frame.origin.x, height: self.clipLayer.frame.size.height)) self.addMaskLayer(frame: CGRect(x: 0, y: self.clipLayer.frame.maxY, width: width, height: height - self.clipLayer.frame.maxY)) self.addMaskLayer(frame: CGRect(x: self.clipLayer.frame.maxX, y: self.clipLayer.frame.origin.y, width: width - self.clipLayer.frame.maxX, height: self.clipLayer.frame.size.height)) self.layer.addSublayer(self.clipLayer) } func addMaskLayer(frame: CGRect) { let maskLayer = CAShapeLayer() maskLayer.frame = frame maskLayer.backgroundColor = UIColor(white: 0.2, alpha: 0.7).cgColor self.layer.addSublayer(maskLayer) } //MARK: - ***** LoadData Method ***** //MARK: - ***** create Method ***** func createBtn(frame:CGRect, title:String?, tag:Int) { let btn = UIButton(type: .custom) btn.addTarget(self, action: #selector(self.btnAction), for: .touchUpInside) btn.frame = frame btn.tag = tag btn.setTitle(title, for: .normal) self.addSubview(btn) } //MARK: - ***** respond event Method ***** @objc func gestureRecognizerChange(gesture:UIGestureRecognizer){ if gesture.isKind(of: UIPanGestureRecognizer.self) { let pan = gesture as! UIPanGestureRecognizer switch pan.state { case .began: self.startCenter = self.imageView.center break case .changed: let translation = pan.translation(in: self) self.imageView.center = CGPoint(x: self.startCenter.x + translation.x, y: self.startCenter.y + translation.y) break case .ended: self.startCenter = CGPoint(x: 0, y: 0) if self.imageView.frame.origin.x > self.clipLayer.frame.origin.x { UIView.animate(withDuration: 0.1, animations: { var frame = self.imageView.frame; frame.origin.x = self.clipLayer.frame.origin.x; self.imageView.frame = frame; }) } if (self.imageView.frame.maxX < self.clipLayer.frame.maxX) { UIView.animate(withDuration: 0.1, animations: { var frame = self.imageView.frame; frame.origin.x = self.clipLayer.frame.maxX - frame.size.width; self.imageView.frame = frame; }) } if self.imageView.frame.origin.y > self.clipLayer.frame.origin.y { UIView.animate(withDuration: 0.1, animations: { var frame = self.imageView.frame; frame.origin.y = self.clipLayer.frame.origin.y; self.imageView.frame = frame; }) } if (self.imageView.frame.maxY < self.clipLayer.frame.maxY) { UIView.animate(withDuration: 0.1, animations: { var frame = self.imageView.frame; frame.origin.y = self.clipLayer.frame.maxY - frame.size.height; self.imageView.frame = frame; }) } break default: break } }else { let pinch = gesture as! UIPinchGestureRecognizer switch pinch.state { case .began: startSacle = pinch.scale break case .changed: let scale = (pinch.scale - startSacle) + 1 self.imageView.transform = self.imageView.transform.scaledBy(x: scale, y: scale) startSacle = pinch.scale break case .ended: startSacle = 1 if self.imageView.frame.size.width < self.clipLayer.bounds.size.width || self.imageView.frame.size.height < self.clipLayer.bounds.size.height { UIView.animate(withDuration: 0.1, animations: { self.imageView.frame = CGRect(x: 0,y: 0,width: self.bounds.size.width, height: self.image.size.height * self.sizeW / self.image.size.width); self.imageView.center = self.center; }) } break default: break } } } @objc func btnAction(btn:UIButton) { if btn.tag == 101 { self.clipLayer.isHidden = true let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, scale) self.layer.render(in: UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext()! let backImage = UIImage(cgImage: img.cgImage!.cropping(to: CGRect(x: self.clipLayer.frame.origin.x * scale, y: self.clipLayer.frame.origin.y * scale, width: self.clipLayer.frame.size.width * scale, height: self.clipLayer.frame.size.height * scale))!) UIGraphicsEndImageContext() if self.handle != nil { self.handle!(backImage) } } self.removeFromSuperview() } }
0f1130a50bd8b0151cfa2fbb9c619d75
40.235669
262
0.575224
false
false
false
false
DevZheng/LeetCode
refs/heads/master
Array/FirstMissingPositive.swift
mit
1
// // FirstMissingPositive.swift // A // // Created by zyx on 2017/6/29. // Copyright © 2017年 bluelive. All rights reserved. // import Foundation /** Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. */ class FirstMissingPositive { func firstMissingPositive(_ nums: [Int]) -> Int { var i = 0, nums = nums while i < nums.count { let num = nums[i] guard (num > 0 && num < nums.count) && nums[num - 1] != num else { i += 1 continue } let temp = nums[num - 1] nums[i] = temp nums[num - 1] = num } for (i, value) in nums.enumerated() { if i != value - 1 { return i + 1 } } return nums.count + 1 } }
4c7693a1f2b27acf46a9d5084dbbc777
19.568627
79
0.466158
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Settings/CellDescriptors/SettingsCopyButtonCellDescriptor.swift
gpl-3.0
1
// // Wire // Copyright (C) 2022 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 UIKit protocol IconActionCellDelegate: AnyObject { func updateLayout() } class SettingsCopyButtonCellDescriptor: SettingsCellDescriptorType { static let cellType: SettingsTableCellProtocol.Type = IconActionCell.self weak var delegate: IconActionCellDelegate? var copyInProgress = false { didSet { delegate?.updateLayout() } } // MARK: - Configuration func featureCell(_ cell: SettingsCellType) { if let iconActionCell = cell as? IconActionCell { delegate = iconActionCell iconActionCell.configure(with: copyInProgress ? copiedLink : copyLink, variant: .dark) } } // MARK: - Helpers typealias Actions = L10n.Localizable.Self.Settings.AccountSection.ProfileLink.Actions let copiedLink: CellConfiguration = .iconAction(title: Actions.copiedLink, icon: .checkmark, color: nil, action: {_ in } ) let copyLink: CellConfiguration = .iconAction(title: Actions.copyLink, icon: .copy, color: nil, action: {_ in } ) // MARK: - SettingsCellDescriptorType var visible: Bool { return true } var title: String { return URL.selfUserProfileLink?.absoluteString.removingPercentEncoding ?? "" } var identifier: String? weak var group: SettingsGroupCellDescriptorType? var previewGenerator: PreviewGeneratorType? func select(_ value: SettingsPropertyValue?) { UIPasteboard.general.string = title copyInProgress = true DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in self?.copyInProgress = false } } }
399fbbf4825dc17f993966fbb99b7364
31.409639
90
0.604833
false
false
false
false
february29/Learning
refs/heads/master
swift/Fch_Contact/Fch_Contact/AppClasses/Model/UserModel.swift
mit
1
// // UserModel.swift // Fch_Contact // // Created by bai on 2017/11/2. // Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved. // import UIKit import HandyJSON class UserModel : HandyJSON,NSCoding{ required init() { } var deleted : Int! var id : Int! var lastLoginTime : TimeInterval! var loginCount : Int! var loginName : String! var mobile : String! var password : String! var userType : Int! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ deleted = dictionary["deleted"] as? Int id = dictionary["id"] as? Int lastLoginTime = dictionary["lastLoginTime"] as? TimeInterval loginCount = dictionary["loginCount"] as? Int loginName = dictionary["loginName"] as? String mobile = dictionary["mobile"] as? String password = dictionary["password"] as? String userType = dictionary["userType"] as? Int } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if deleted != nil{ dictionary["deleted"] = deleted } if id != nil{ dictionary["id"] = id } if lastLoginTime != nil{ dictionary["lastLoginTime"] = lastLoginTime } if loginCount != nil{ dictionary["loginCount"] = loginCount } if loginName != nil{ dictionary["loginName"] = loginName } if mobile != nil{ dictionary["mobile"] = mobile } if password != nil{ dictionary["password"] = password } if userType != nil{ dictionary["userType"] = userType } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { deleted = aDecoder.decodeObject(forKey: "deleted") as? Int id = aDecoder.decodeObject(forKey: "id") as? Int lastLoginTime = aDecoder.decodeObject(forKey: "lastLoginTime") as? TimeInterval loginCount = aDecoder.decodeObject(forKey: "loginCount") as? Int loginName = aDecoder.decodeObject(forKey: "loginName") as? String mobile = aDecoder.decodeObject(forKey: "mobile") as? String password = aDecoder.decodeObject(forKey: "password") as? String userType = aDecoder.decodeObject(forKey: "userType") as? Int } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if deleted != nil{ aCoder.encode(deleted, forKey: "deleted") } if id != nil{ aCoder.encode(id, forKey: "id") } if lastLoginTime != nil{ aCoder.encode(lastLoginTime, forKey: "lastLoginTime") } if loginCount != nil{ aCoder.encode(loginCount, forKey: "loginCount") } if loginName != nil{ aCoder.encode(loginName, forKey: "loginName") } if mobile != nil{ aCoder.encode(mobile, forKey: "mobile") } if password != nil{ aCoder.encode(password, forKey: "password") } if userType != nil{ aCoder.encode(userType, forKey: "userType") } } }
7cbdfc78a551b24137f071d994b1561a
28.314961
183
0.571313
false
false
false
false
qualaroo/QualarooSDKiOS
refs/heads/master
Qualaroo/Network/UrlComposer.swift
mit
1
// // UrlComposer.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class UrlComposer { struct ParamName { static let identity = "i" static let deviceId = "au" static let surveyId = "id" static let sessionId = "u" } struct UrlPiece { static let scheme = "https" static let responsePath = "/r.js" static let impressionPath = "/c.js" } struct TrackingParams { static let sdkVersion = "sdk_version" static let appId = "app_id" static let deviceModel = "device_model" static let osVersion = "os_version" static let platform = "os" static let resolution = "resolution" static let deviceType = "device_type" static let language = "language" } let sessionInfo: SessionInfo let customProperties: CustomProperties let host: String let sdkSession: SdkSession init(sessionInfo: SessionInfo, customProperties: CustomProperties, environment: Qualaroo.Environment, sdkSession: SdkSession) { self.sessionInfo = sessionInfo self.customProperties = customProperties self.host = UrlComposer.turboHost(environment: environment) self.sdkSession = sdkSession } private static func turboHost(environment: Qualaroo.Environment) -> String { switch environment { case .production: return "turbo.qualaroo.com" case .staging: return "stage1.turbo.qualaroo.com" } } private func commonUrlComponents() -> URLComponents { var components = URLComponents() components.scheme = UrlPiece.scheme components.host = host return components } private func query(_ response: NodeResponse) -> [URLQueryItem] { switch response { case .question(let model): return query(model) case .leadGen(let model): return model.questionList.flatMap { query($0) } } } private func query(_ model: QuestionResponse) -> [URLQueryItem] { return model.answerList.map { queryItem(from: $0, with: model.id) }.removeNils() } private func queryItem(from model: AnswerResponse, with questionId: NodeId) -> URLQueryItem? { switch (model.id, model.text) { case (.some(let id), .none): return indexOnlyItem(index: id, with: questionId) case (.some(let id), .some(let text)): return indexAndTextItem(index: id, text: text, with: questionId) case (.none, .some(let text)): return textOnlyItem(text: text, with: questionId) case (.none, .none): return nil } } private func textOnlyItem(text: String, with questionId: NodeId) -> URLQueryItem? { return URLQueryItem(name: "r[\(questionId)][text]", value: text) } private func indexOnlyItem(index: AnswerId, with questionId: NodeId) -> URLQueryItem? { return URLQueryItem(name: "r[\(questionId)][]", value: "\(index)") } private func indexAndTextItem(index: AnswerId, text: String, with questionId: NodeId) -> URLQueryItem? { return URLQueryItem(name: "re[\(questionId)][\(index)]", value: text) } private func sessionInfoQuery() -> [URLQueryItem] { return [surveyIdItem(sessionInfo.surveyId), deviceIdItem(sessionInfo.deviceId), sessionIdItem(sessionInfo.sessionId), clientIdItem(sessionInfo.clientId)].removeNils() } private func surveyIdItem(_ surveyId: Int) -> URLQueryItem { return URLQueryItem(name: ParamName.surveyId, value: "\(surveyId)") } private func deviceIdItem(_ deviceId: String) -> URLQueryItem { return URLQueryItem(name: ParamName.deviceId, value: deviceId) } private func sessionIdItem(_ sessionId: String) -> URLQueryItem { return URLQueryItem(name: ParamName.sessionId, value: sessionId) } private func clientIdItem(_ clientId: String?) -> URLQueryItem? { guard let clientId = clientId else { return nil } return URLQueryItem(name: ParamName.identity, value: clientId) } private func customPropertiesQuery() -> [URLQueryItem] { return customProperties.dictionary.map { URLQueryItem(name: "rp[\($0)]", value: $1) } } private func sdkSessionParameters() -> [URLQueryItem] { var result = [URLQueryItem]() result.append(queryItem(TrackingParams.sdkVersion, sdkSession.sdkVersion)) result.append(queryItem(TrackingParams.appId, sdkSession.appId)) result.append(queryItem(TrackingParams.deviceModel, sdkSession.deviceModel)) result.append(queryItem(TrackingParams.osVersion, sdkSession.osVersion)) result.append(queryItem(TrackingParams.platform, sdkSession.platform)) result.append(queryItem(TrackingParams.resolution, sdkSession.resolution)) result.append(queryItem(TrackingParams.deviceType, sdkSession.deviceType)) result.append(queryItem(TrackingParams.language, sdkSession.language)) return result } private func queryItem(_ name: String, _ value: String) -> URLQueryItem { return URLQueryItem(name: name, value: value) } } extension UrlComposer: ReportUrlComposerProtocol { func responseUrl(with response: NodeResponse) -> URL? { var components = commonUrlComponents() components.path = UrlPiece.responsePath components.queryItems = responseQuery(response) return components.url } private func responseQuery(_ response: NodeResponse) -> [URLQueryItem] { return [sessionInfoQuery(), customPropertiesQuery(), sdkSessionParameters(), query(response)].flatMap { $0 } } func impressionUrl() -> URL? { var components = commonUrlComponents() components.path = UrlPiece.impressionPath components.queryItems = impressionQuery() return components.url } private func impressionQuery() -> [URLQueryItem] { return sessionInfoQuery() } }
32e3784f65e7183d57bd71c9bfc5f815
34.982036
107
0.682809
false
false
false
false
backslash112/YCRangeSlider
refs/heads/master
Example/YCRangeSlider/ViewController.swift
mit
1
// // ViewController.swift // YCRangeSlider // // Created by backslash112 on 09/11/2015. // Copyright (c) 2015 backslash112. All rights reserved. // import UIKit import YCRangeSlider class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.initRangeSlider() self.view.addSubview(self.slider) self.view.backgroundColor = UIColor.grayColor() } var slider: YCRangeSlider! func initRangeSlider() { self.slider = YCRangeSlider() self.slider.minimumValue = 0 self.slider.selectedMinimumValue = 0 self.slider.maximumValue = 500 self.slider.selectedMaximumValue = 500 self.slider.minimumRange = 1 self.slider.barBackground = UIImage(named: "tm_bar-background") self.slider.minHandle = UIImage(named: "tm_handle_start") self.slider.maxHandle = UIImage(named: "tm_handle_end") self.slider.popViewBackgroundImage = UIImage(named: "time-machine_popValue_bg") let height: CGFloat = 463 let width: CGFloat = 133 slider.initWithFrame2(frame: CGRectMake((self.view.frame.width-width)/2, (self.view.frame.height - height)/2, width, height)) } }
16c738c24525cafe9f69a0e138bad3e2
32.15
133
0.667421
false
false
false
false
meetkei/KxUI
refs/heads/master
KxUI/ViewController/KUVC+Responder.swift
mit
1
// // Copyright (c) 2016 Keun young Kim <[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. // public extension KUCommonViewController { func findFirstResponder(in v: UIView? = nil) -> UIView? { if let targetView = v { for item in targetView.subviews { if item.isFirstResponder { return item } if let v = findFirstResponder(in: item) { return v } } } else { for item in view.subviews { if item.isFirstResponder { return item } if let v = findFirstResponder(in: item) { return v } } } return nil } func findFirstResponderAndResign(in v: UIView? = nil) { if let targetView = v { for item in targetView.subviews { if item.isFirstResponder { item.resignFirstResponder() return } findFirstResponderAndResign(in: item) } } else { for item in view.subviews { if item.isFirstResponder { item.resignFirstResponder() return } findFirstResponderAndResign(in: item) } } } }
31e858520ae26bef17958d272ddf43f5
34.123288
81
0.560842
false
false
false
false
fitpay/fitpay-ios-sdk
refs/heads/develop
FitpaySDK/Logs/BaseOutput.swift
mit
1
import Foundation //TODO: Where does LogLevel live? @objc public enum LogLevel: Int { case verbose = 0 case debug case info case warning case error var string: String { switch self { case .verbose: return "VERBOSE" case .debug: return "DEBUG" case .info: return "INFO" case .warning: return "WARNING" case .error: return "ERROR" } } } @objc public protocol LogsOutputProtocol { func send(level: LogLevel, message: String, file: String, function: String, line: Int) } open class BaseLogsOutput: NSObject, LogsOutputProtocol { let formatter = DateFormatter() var date: String { return formatter.string(from: Date()) } public override init() { formatter.dateFormat = "HH:mm:ss.SSS" } open func send(level: LogLevel, message: String, file: String, function: String, line: Int) { _ = formMessage(level: level, message: message, file: file, function: function, line: line) // send somewhere } func formMessage(level: LogLevel, message: String, file: String, function: String, line: Int) -> String { let fileName = fileNameWithoutSuffix(file) var messageResult = message switch level { case .verbose, .debug, .info: messageResult = "\(date) \(message)" case .warning: messageResult = "\(date) ⚠️ \(level.string) - \(message) - \(fileName).\(function):\(line)" case .error: messageResult = "\(date) ❌ \(level.string) - \(message) - \(fileName).\(function):\(line)" } return messageResult } private func fileNameOfFile(_ file: String) -> String { let fileParts = file.components(separatedBy: "/") return fileParts.last ?? "" } private func fileNameWithoutSuffix(_ file: String) -> String { let fileName = fileNameOfFile(file) if !fileName.isEmpty { let fileNameParts = fileName.components(separatedBy: ".") return fileNameParts.first ?? "" } return "" } }
a95930012b2fdbc570a78a517b68b0e2
27.525641
109
0.568539
false
false
false
false
craiggrummitt/ActionSwift3
refs/heads/master
ActionSwift3/text/TextFormat.swift
mit
1
// // TextFormat.swift // ActionSwift // // Created by Craig on 27/07/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // import SpriteKit import UIKit /** Set up your text formatting here, add it to your text field with the `defaultTextFormat` property. Get a list of iOS fonts here: http://iosfonts.com Leave leading as -1 and it will be automatically made the same as the font size */ open class TextFormat:Object { open var font = "ArialMT" open var size:CGFloat = 12 open var color = UIColor.black open var leading:CGFloat = 12 open var align:SKLabelHorizontalAlignmentMode = .left public init(font:String = "ArialMT", size:CGFloat = 12, color:UIColor = UIColor.black,leading:CGFloat = -1,align:SKLabelHorizontalAlignmentMode = .left) { self.font = font self.size = size self.color = color if (self.leading == -1) { self.leading = self.size } else { self.leading = leading } self.align = align } }
86b3fe0b8e4cc5571d52d37ccc9796a0
28.361111
158
0.648061
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/LegalHoldDetails/LegalHoldDetailsViewController.swift
gpl-3.0
1
// // Wire // Copyright (C) 2019 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 UIKit import WireDataModel final class LegalHoldDetailsViewController: UIViewController { fileprivate let collectionView = UICollectionView(forGroupedSections: ()) fileprivate let collectionViewController: SectionCollectionViewController fileprivate let conversation: LegalHoldDetailsConversation convenience init?(user: UserType) { guard let conversation = user.oneToOneConversation else { return nil } self.init(conversation: conversation) } init(conversation: LegalHoldDetailsConversation) { self.conversation = conversation self.collectionViewController = SectionCollectionViewController() self.collectionViewController.collectionView = collectionView super.init(nibName: nil, bundle: nil) setupViews() createConstraints() collectionViewController.sections = computeVisibleSections() collectionView.accessibilityIdentifier = "list.legalhold" } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult static func present(in parentViewController: UIViewController, user: UserType) -> UINavigationController? { guard let legalHoldDetailsViewController = LegalHoldDetailsViewController(user: user) else { return nil } return legalHoldDetailsViewController.wrapInNavigationControllerAndPresent(from: parentViewController) } @discardableResult static func present(in parentViewController: UIViewController, conversation: ZMConversation) -> UINavigationController { let legalHoldDetailsViewController = LegalHoldDetailsViewController(conversation: conversation) return legalHoldDetailsViewController.wrapInNavigationControllerAndPresent(from: parentViewController) } override func viewDidLoad() { super.viewDidLoad() title = "legalhold.header.title".localized.localizedUppercase view.backgroundColor = SemanticColors.View.backgroundDefault } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.rightBarButtonItem = navigationController?.updatedCloseItem() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) (conversation as? ZMConversation)?.verifyLegalHoldSubjects() } fileprivate func setupViews() { view.addSubview(collectionView) collectionView.contentInsetAdjustmentBehavior = .never } fileprivate func createConstraints() { collectionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } fileprivate func computeVisibleSections() -> [CollectionViewSectionController] { let headerSection = SingleViewSectionController(view: LegalHoldHeaderView(frame: .zero)) let legalHoldParticipantsSection = LegalHoldParticipantsSectionController(conversation: conversation) legalHoldParticipantsSection.delegate = self return [headerSection, legalHoldParticipantsSection] } } extension LegalHoldDetailsViewController: LegalHoldParticipantsSectionControllerDelegate { func legalHoldParticipantsSectionWantsToPresentUserProfile(for user: UserType) { let profileViewController = ProfileViewController(user: user, viewer: SelfUser.current, context: .deviceList) show(profileViewController, sender: nil) } }
28e88ad0149b574a606a2965b9666dc8
37
124
0.749447
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Games/UberJump/UberJump/PlatformNode.swift
mit
3
import SpriteKit enum PlatformType:UInt32{ case PLATFORM_NORMAL = 0 case PLATFORM_BREAK = 1 } class PlatformNode: GameObjectNode { var platformType:PlatformType? override func collisionWithPlayer(player:SKNode) -> Bool{ if(player.physicsBody?.velocity.dy < 0){ // 2 player.physicsBody?.velocity = CGVectorMake(player.physicsBody!.velocity.dx, CGFloat(250)); // 3 // Remove if it is a Break type platform if (self.platformType! == PlatformType.PLATFORM_BREAK) { self.removeFromParent() } } return false } }
544bb023fe3c66098c6ca79ac28c120a
26.541667
103
0.588502
false
false
false
false
willhains/Kotoba
refs/heads/master
code/Kotoba/KotobaNavigationController.swift
mit
1
// // Created by Craig Hockenberry on 11/23/19. // Copyright © 2019 Will Hains. All rights reserved. // import UIKit class KotobaNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let titleFont = UIFont(name: "AmericanTypewriter-Semibold", size: 22) ?? UIFont.systemFont(ofSize: 22.0, weight: .bold) let barTextColor = UIColor(named: "appBarText") ?? UIColor.white let barTintColor = UIColor(named: "appBarTint") ?? UIColor.red let titleTextAttributes: [NSAttributedString.Key : Any] = [ .font: titleFont, .foregroundColor: barTextColor, ] if #available(iOS 15, *) { // NOTE: The following code is derived from David Duncan's post in the Apple Developer Forums: // https://developer.apple.com/forums/thread/682420 let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.backgroundColor = barTintColor appearance.titleTextAttributes = titleTextAttributes navigationBar.standardAppearance = appearance; navigationBar.scrollEdgeAppearance = navigationBar.standardAppearance } else { self.navigationBar.titleTextAttributes = titleTextAttributes self.navigationBar.barTintColor = barTintColor } } override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } }
187b61ad4f8931101ff68ee1aba94b30
29.953488
97
0.755071
false
false
false
false
aledustet/RNLoadingButton-Swift
refs/heads/master
RNLoadingButtonDemo/RNLoadingButton/RNLoadingButton.swift
mit
2
// // RNLoadingButton.swift // RNLoadingButton // // Created by Romilson Nunes on 06/06/14. // Copyright (c) 2014 Romilson Nunes. All rights reserved. // import UIKit public enum RNActivityIndicatorAlignment: Int { case Left case Center case Right static func Random() ->RNActivityIndicatorAlignment { let max = UInt32(RNActivityIndicatorAlignment.Right.rawValue) let randomValue = Int(arc4random_uniform(max + 1)) return RNActivityIndicatorAlignment(rawValue: randomValue)! } } public class RNLoadingButton: UIButton { /** Loading */ public var loading:Bool = false { didSet { configureControlState(currentControlState()); } } public var hideImageWhenLoading:Bool = true { didSet { configureControlState(currentControlState()); } } public var hideTextWhenLoading:Bool = true { didSet { configureControlState(currentControlState()); } } public var activityIndicatorEdgeInsets:UIEdgeInsets = UIEdgeInsetsZero /** Loading Alingment */ public var activityIndicatorAlignment:RNActivityIndicatorAlignment = RNActivityIndicatorAlignment.Center { didSet { self.setNeedsLayout() } } public let activityIndicatorView:UIActivityIndicatorView! = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) // Internal properties let imagens:NSMutableDictionary! = NSMutableDictionary() let texts:NSMutableDictionary! = NSMutableDictionary() let indicatorStyles : NSMutableDictionary! = NSMutableDictionary() // Static let defaultActivityStyle = UIActivityIndicatorViewStyle.Gray func setActivityIndicatorStyle( style:UIActivityIndicatorViewStyle, state:UIControlState) { var s:NSNumber = NSNumber(integer: style.rawValue); setControlState( s, dic: indicatorStyles, state: state) self.setNeedsLayout() } override init(frame: CGRect) { super.init(frame: frame) // Initialization code self.setupActivityIndicator() commonInit() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public func awakeFromNib() { super.awakeFromNib() setupActivityIndicator() // Images - Icons if (super.imageForState(UIControlState.Normal) != nil) { self.storeValue(super.imageForState(UIControlState.Normal), onDic: imagens, state: UIControlState.Normal) } if (super.imageForState(UIControlState.Highlighted) != nil) { self.storeValue(super.imageForState(UIControlState.Highlighted), onDic: imagens, state: UIControlState.Highlighted) } if (super.imageForState(UIControlState.Disabled) != nil) { self.storeValue(super.imageForState(UIControlState.Disabled), onDic: imagens, state: UIControlState.Disabled) } if (super.imageForState(UIControlState.Selected) != nil) { self.storeValue(super.imageForState(UIControlState.Selected), onDic: imagens, state: UIControlState.Selected) } // Title - Texts if let titleNormal = super.titleForState(.Normal) { self.storeValue(titleNormal, onDic: texts, state: .Normal) } if let titleHighlighted = super.titleForState(.Highlighted) { self.storeValue(titleHighlighted, onDic: texts, state: .Highlighted) } if let titleDisabled = super.titleForState(.Disabled) { self.storeValue(titleDisabled, onDic: texts, state: .Disabled) } if let titleSelected = super.titleForState(.Selected) { self.storeValue(titleSelected, onDic: texts, state: .Selected) } } override public func layoutSubviews() { super.layoutSubviews() var style=self.activityIndicatorStyleForState(self.currentControlState()) self.activityIndicatorView.activityIndicatorViewStyle = style self.activityIndicatorView.frame = self.frameForActivityIndicator() self.bringSubviewToFront(self.activityIndicatorView) } deinit { self.removeObserver(forKeyPath: "self.state") self.removeObserver(forKeyPath: "self.selected") self.removeObserver(forKeyPath: "self.highlighted") } //############################ // Setup e init // func setupActivityIndicator() { self.activityIndicatorView.hidesWhenStopped = true self.activityIndicatorView.startAnimating() self.addSubview(self.activityIndicatorView) var tap = UITapGestureRecognizer(target: self, action: Selector("activityIndicatorTapped:")) self.activityIndicatorView.addGestureRecognizer(tap) } func commonInit() { self.adjustsImageWhenHighlighted = true /** Title for States */ self.texts.setValue(super.titleForState(UIControlState.Normal), forKey: "\(UIControlState.Normal.rawValue)") self.texts.setValue(super.titleForState(UIControlState.Highlighted), forKey: "\(UIControlState.Highlighted.rawValue)") self.texts.setValue(super.titleForState(UIControlState.Disabled), forKey: "\(UIControlState.Disabled.rawValue)") self.texts.setValue(super.titleForState(UIControlState.Selected), forKey: "\(UIControlState.Selected.rawValue)") /** Images for States */ self.imagens.setValue(super.imageForState(UIControlState.Normal), forKey: "\(UIControlState.Normal.rawValue)") self.imagens.setValue(super.imageForState(UIControlState.Highlighted), forKey: "\(UIControlState.Highlighted.rawValue)") self.imagens.setValue(super.imageForState(UIControlState.Disabled), forKey: "\(UIControlState.Disabled.rawValue)") self.imagens.setValue(super.imageForState(UIControlState.Selected), forKey: "\(UIControlState.Selected.rawValue)") /** Indicator Styles for States */ var s:NSNumber = NSNumber(integer: defaultActivityStyle.rawValue) self.indicatorStyles.setValue(s, forKey: "\(UIControlState.Normal.rawValue)") self.indicatorStyles.setValue(s, forKey: "\(UIControlState.Highlighted.rawValue)") self.indicatorStyles.setValue(s, forKey: "\(UIControlState.Disabled.rawValue)") self.indicatorStyles.setValue(s, forKey: "\(UIControlState.Selected.rawValue)") self.addObserver(forKeyPath: "self.state") self.addObserver(forKeyPath: "self.selected") self.addObserver(forKeyPath: "self.highlighted") } func activityIndicatorTapped(sender:AnyObject) { self.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } func currentControlState() -> UIControlState { var controlState = UIControlState.Normal.rawValue if self.selected { controlState += UIControlState.Selected.rawValue } if self.highlighted { controlState += UIControlState.Highlighted.rawValue } if !self.enabled { controlState += UIControlState.Disabled.rawValue } return UIControlState(rawValue: controlState) } func setControlState(value:AnyObject ,dic:NSMutableDictionary, state:UIControlState) { dic["\(state.rawValue)"] = value configureControlState(currentControlState()) } func setImage(image:UIImage, state:UIControlState) { setControlState(image, dic: self.imagens, state: state) } // Activity Indicator Alignment func setActivityIndicatorAlignment(alignment: RNActivityIndicatorAlignment) { activityIndicatorAlignment = alignment; self.setNeedsLayout(); } func activityIndicatorStyleForState(state: UIControlState) -> UIActivityIndicatorViewStyle { var style:UIActivityIndicatorViewStyle = defaultActivityStyle if let styleObj: AnyObject = self.getValueForControlState(self.indicatorStyles, state: state) { // https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Enumerations.html style = UIActivityIndicatorViewStyle(rawValue: (styleObj as! NSNumber).integerValue)! } return style } //############################## // Setters & Getters override public func setTitle(title: String!, forState state: UIControlState) { println(self.texts) self.storeValue(title, onDic: self.texts, state: state) if super.titleForState(state) != title { super.setTitle(title, forState: state) } self.setNeedsLayout() } override public func titleForState(state: UIControlState) -> String? { println(self.getValueForControlState(self.texts, state: state) as? String) return self.getValueForControlState(self.texts, state: state) as? String } override public func setImage(image: UIImage!, forState state: UIControlState) { self.storeValue(image, onDic: self.imagens, state: state) if super.imageForState(state) != image { super.setImage(image, forState: state) } self.setNeedsLayout() } override public func imageForState(state: UIControlState) -> UIImage? { return self.getValueForControlState(self.imagens, state: state) as? UIImage } //############################## // Helper func addObserver(forKeyPath keyPath:String) { self.addObserver(self, forKeyPath:keyPath, options: (NSKeyValueObservingOptions.Initial|NSKeyValueObservingOptions.New), context: nil) } func removeObserver(forKeyPath keyPath: String!) { self.removeObserver(self, forKeyPath: keyPath) } func getValueForControlState(dic:NSMutableDictionary!, state:UIControlState) -> AnyObject? { var value:AnyObject? = dic.valueForKey("\(state.rawValue)");// dic["\(state)"]; if (value != nil) { return value; } // value = dic["\(UIControlState.Selected.rawValue)"]; // if ( (state & UIControlState.Selected) && value) { // return value; // } // // value = dic["\(UIControlState.Highlighted.rawValue)"]; // // if ( (state & UIControlState.Selected) && value != nil) { // return value; // } return dic["\(UIControlState.Normal.rawValue)"]; } private func configureControlState(state:UIControlState) { if self.loading { self.activityIndicatorView.startAnimating(); if self.hideImageWhenLoading { var imgTmp:UIImage? = nil if let img = self.imageForState(UIControlState.Normal) { imgTmp = self.clearImage(img.size, scale: img.scale) } super.setImage(imgTmp, forState: UIControlState.Normal) super.setImage(imgTmp, forState: UIControlState.Selected) super.setImage(imgTmp, forState: state) super.imageView?.image = imgTmp } else { super.setImage( self.imageForState(state), forState: state) } if (self.hideTextWhenLoading) { super.setTitle(nil, forState: state) super.titleLabel?.text = nil } else { super.setTitle( self.titleForState(state) , forState: state) super.titleLabel?.text = self.titleForState(state) } } else { self.activityIndicatorView.stopAnimating(); super.setImage(self.imageForState(state), forState: state) super.imageView?.image = self.imageForState(state) super.setTitle(self.titleForState(state), forState: state) super.titleLabel?.text = self.titleForState(state) } self.setNeedsLayout() } func frameForActivityIndicator() -> CGRect { var frame:CGRect = CGRectZero; frame.size = self.activityIndicatorView.frame.size; frame.origin.y = (self.frame.size.height - frame.size.height) / 2; switch self.activityIndicatorAlignment { case RNActivityIndicatorAlignment.Left: // top, left bottom right frame.origin.x += self.activityIndicatorEdgeInsets.left; frame.origin.y += self.activityIndicatorEdgeInsets.top; case RNActivityIndicatorAlignment.Center: frame.origin.x = (self.frame.size.width - frame.size.width) / 2; case RNActivityIndicatorAlignment.Right: var lengthOccupied:CFloat = 0; var x:CFloat = 0; var imageView:UIImageView = self.imageView!; var titleLabel:UILabel = self.titleLabel!; let xa = CGFloat(UInt(arc4random_uniform(UInt32(UInt(imageView.frame.size.width) * 5))))// - self.gameView.bounds.size.width * 2 if (imageView.image != nil && titleLabel.text != nil){ lengthOccupied = Float( imageView.frame.size.width + titleLabel.frame.size.width ); if (imageView.frame.origin.x > titleLabel.frame.origin.x){ lengthOccupied += Float( imageView.frame.origin.x ) } else { lengthOccupied += Float( titleLabel.frame.origin.x ) } } else if (imageView.image != nil){ lengthOccupied = Float( imageView.frame.size.width + imageView.frame.origin.x ) } else if (titleLabel.text != nil){ lengthOccupied = Float( titleLabel.frame.size.width + imageView.frame.origin.x ) } x = Float(lengthOccupied) + Float( self.activityIndicatorEdgeInsets.left ) if ( Float(x) + Float(frame.size.width) > Float(self.frame.size.width) ){ x = Float(self.frame.size.width) - Float(frame.size.width + self.activityIndicatorEdgeInsets.right); } else if ( Float(x + Float(frame.size.width) ) > Float(self.frame.size.width - self.activityIndicatorEdgeInsets.right)){ x = Float(self.frame.size.width) - ( Float(frame.size.width) + Float(self.activityIndicatorEdgeInsets.right) ); } frame.origin.x = CGFloat( x ); default: break } return frame; } // UIImage clear func clearImage(size:CGSize, scale:CGFloat) ->UIImage { UIGraphicsBeginImageContext(size) var context:CGContextRef = UIGraphicsGetCurrentContext(); UIGraphicsPushContext(context) CGContextSetFillColorWithColor(context, UIColor.clearColor().CGColor) CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)) UIGraphicsPopContext() var outputImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return UIImage(CGImage: outputImage.CGImage, scale: scale, orientation: UIImageOrientation.Up)! } /** Store values */ /** Value in Dictionary on ControlState*/ func storeValue(value:AnyObject?, onDic:NSMutableDictionary!, state:UIControlState) { if let _value: AnyObject = value { onDic.setValue(_value, forKey: "\(state.rawValue)") } else { onDic.removeObjectForKey("\(state.rawValue)") } self.configureControlState(self.currentControlState()) } /** KVO - Key-value Observer */ override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { println("KeyPath: \(keyPath)") configureControlState(currentControlState()); } }
25a3da266c41c27e2defa0fd6ae23d8a
37.278422
161
0.622621
false
false
false
false
omise/omise-ios
refs/heads/master
ExampleApp/Shared/Tools.swift
mit
1
import UIKit import OmiseSDK struct PaymentPreset { var paymentAmount: Int64 var paymentCurrency: Currency var allowedPaymentMethods: [OMSSourceTypeValue] static let thailandPreset = PaymentPreset( paymentAmount: 5_000_00, paymentCurrency: .thb, allowedPaymentMethods: PaymentCreatorController.thailandDefaultAvailableSourceMethods ) static let japanPreset = PaymentPreset( paymentAmount: 5_000, paymentCurrency: .jpy, allowedPaymentMethods: PaymentCreatorController.japanDefaultAvailableSourceMethods ) static let singaporePreset = PaymentPreset( paymentAmount: 5_000_00, paymentCurrency: .sgd, allowedPaymentMethods: PaymentCreatorController.singaporeDefaultAvailableSourceMethods ) static let malaysiaPreset = PaymentPreset( paymentAmount: 5_000_00, paymentCurrency: .myr, allowedPaymentMethods: PaymentCreatorController.malaysiaDefaultAvailableSourceMethods ) } @objc class Tool: NSObject { @objc static let thailandPaymentAmount: Int64 = PaymentPreset.thailandPreset.paymentAmount @objc static let thailandPaymentCurrency: String = PaymentPreset.thailandPreset.paymentCurrency.code @objc static let thailandAllowedPaymentMethods: [OMSSourceTypeValue] = PaymentPreset.thailandPreset.allowedPaymentMethods @objc static let japanPaymentAmount: Int64 = PaymentPreset.japanPreset.paymentAmount @objc static let japanPaymentCurrency: String = PaymentPreset.japanPreset.paymentCurrency.code @objc static let japanAllowedPaymentMethods: [OMSSourceTypeValue] = PaymentPreset.japanPreset.allowedPaymentMethods @objc static let singaporePaymentAmount: Int64 = PaymentPreset.singaporePreset.paymentAmount @objc static let singaporePaymentCurrency: String = PaymentPreset.singaporePreset.paymentCurrency.code @objc static let singaporeAllowedPaymentMethods: [OMSSourceTypeValue] = PaymentPreset.singaporePreset.allowedPaymentMethods @objc static let malaysiaPaymentAmount: Int64 = PaymentPreset.malaysiaPreset.paymentAmount @objc static let malaysiaPaymentCurrency: String = PaymentPreset.malaysiaPreset.paymentCurrency.code @objc static let malaysiaAllowedPaymentMethods: [OMSSourceTypeValue] = PaymentPreset.malaysiaPreset.allowedPaymentMethods @objc static func imageWith(size: CGSize, color: UIColor) -> UIImage? { return Tool.imageWith(size: size) { (context) in context.setFillColor(color.cgColor) context.fill(CGRect(origin: .zero, size: size)) } } @objc static func imageWith(size: CGSize, actions: (CGContext) -> Void) -> UIImage? { let renderer = UIGraphicsImageRenderer(size: size) return renderer.image { context in actions(context.cgContext) } } }
7380eca61a478a9231ca6bd09a77b98c
43.261538
127
0.751825
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
183. Core Image Video/CoreImageVideo/SimpleFilterViewController.swift
mit
1
// // ViewController.swift // CoreImageVideo // // Created by Chris Eidhof on 03/04/15. // Copyright (c) 2015 objc.io. All rights reserved. // import UIKit import AVFoundation class SimpleFilterViewController: UIViewController { var source: CaptureBufferSource? var coreImageView: CoreImageView? var angleForCurrentTime: Float { return Float(NSDate.timeIntervalSinceReferenceDate() % M_PI*2) } override func loadView() { coreImageView = CoreImageView(frame: CGRect()) self.view = coreImageView } override func viewDidAppear(animated: Bool) { setupCameraSource() } override func viewDidDisappear(animated: Bool) { source?.running = false } func setupCameraSource() { source = CaptureBufferSource(position: AVCaptureDevicePosition.Front) { [unowned self] (buffer, transform) in let input = CIImage(buffer: buffer).imageByApplyingTransform(transform) let filter = hueAdjust(self.angleForCurrentTime) self.coreImageView?.image = filter(input) } source?.running = true } }
9bf8b4f8d8e7e93eba141151e10b7a29
26.142857
117
0.666667
false
false
false
false
ppengotsu/AppInfo
refs/heads/master
Appinfo/ViewController.swift
mit
1
// // ViewController.swift // Appinfo // // Created by ppengotsu on 2015/03/30. // Copyright (c) 2015年 ppengotsu. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //ログ出力 var appInfo: AppInfo = AppInfo() NSLog("iOSバージョン=%@",appInfo.appVersion()) NSLog("iOS9以上か=%@",appInfo.isMoreThan900AppVersion()) NSLog("iOS8.2以上か=%@",appInfo.isMoreThan820AppVersion()) NSLog("iOS8以上か=%@",appInfo.isMoreThan800AppVersion()) NSLog("iPhoneSimulatorか=%@",appInfo.isIphoneSimulatorDevice()) NSLog("iPadか=%@",appInfo.isIpadDevice()) NSLog("iPhoneか=%@",appInfo.isIphoneDevice()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d79bea041064356afdb2dd23718b8055
22.8
80
0.593838
false
false
false
false
krevis/MIDIApps
refs/heads/main
Frameworks/SnoizeMIDI/PortOutputStream.swift
bsd-3-clause
1
/* Copyright (c) 2001-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Foundation import CoreAudio public class PortOutputStream: OutputStream { public override init(midiContext: MIDIContext) { outputPort = 0 _ = midiContext.interface.outputPortCreate(midiContext.client, "Output Port" as CFString, &outputPort) super.init(midiContext: midiContext) } deinit { NotificationCenter.default.removeObserver(self) _ = midiContext.interface.portDispose(outputPort) } public weak var delegate: PortOutputStreamDelegate? public var destinations: Set<Destination> = [] { didSet { // The closure-based notification observer API is still awkward to use without creating retain cycles. // Easier to use ObjC selectors. let center = NotificationCenter.default oldValue.subtracting(destinations).forEach { center.removeObserver(self, name: .midiObjectDisappeared, object: $0) center.removeObserver(self, name: .midiObjectWasReplaced, object: $0) } destinations.subtracting(oldValue).forEach { center.addObserver(self, selector: #selector(self.destinationDisappeared(notification:)), name: .midiObjectDisappeared, object: $0) center.addObserver(self, selector: #selector(self.destinationWasReplaced(notification:)), name: .midiObjectWasReplaced, object: $0) } } } public var sendsSysExAsynchronously: Bool = false public func cancelPendingSysExSendRequests() { sysExSendRequests.forEach { $0.cancel() } } public var pendingSysExSendRequests: [SysExSendRequest] { return Array(sysExSendRequests) } public var customSysExBufferSize: Int = 0 // MARK: OutputStream overrides public override func takeMIDIMessages(_ messages: [Message]) { if sendsSysExAsynchronously { // Find the messages which are sysex and which have timestamps which are <= now, // and send them using MIDISendSysex(). Other messages get sent normally. let (asyncSysexMessages, normalMessages) = splitMessagesByAsyncSysex(messages) sendSysExMessagesAsynchronously(asyncSysexMessages) super.takeMIDIMessages(normalMessages) } else { super.takeMIDIMessages(messages) } } // MARK: OutputStream subclass-implementation methods override func send(_ packetListPtr: UnsafePointer<MIDIPacketList>) { for destination in destinations { _ = midiContext.interface.send(outputPort, destination.endpointRef, packetListPtr) } } // MARK: Private private var outputPort: MIDIPortRef @objc private func destinationDisappeared(notification: Notification) { if let endpoint = notification.object as? Destination { destinationDisappeared(endpoint) } } private func destinationDisappeared(_ destination: Destination) { guard destinations.contains(destination) else { return } var newDestinations = destinations newDestinations.remove(destination) destinations = newDestinations delegate?.portOutputStreamDestinationDisappeared(self) } @objc private func destinationWasReplaced(notification: Notification) { if let destination = notification.object as? Destination, let replacement = notification.userInfo?[MIDIContext.objectReplacement] as? Destination { destinationWasReplaced(destination, replacement) } } private func destinationWasReplaced(_ destination: Destination, _ replacement: Destination) { guard destinations.contains(destination) else { return } var newDestinations = destinations newDestinations.remove(destination) newDestinations.insert(replacement) destinations = newDestinations } private func splitMessagesByAsyncSysex(_ messages: [Message]) -> ([SystemExclusiveMessage], [Message]) { // FUTURE: This should use `stablePartition`, when that gets added // to the Swift standard library. var asyncSysexMessages: [SystemExclusiveMessage] = [] var normalMessages: [Message] = [] let now = SMGetCurrentHostTime() for message in messages { if let sysexMessage = message as? SystemExclusiveMessage, sysexMessage.hostTimeStamp <= now { asyncSysexMessages.append(sysexMessage) } else { normalMessages.append(message) } } return (asyncSysexMessages, normalMessages) } private var sysExSendRequests = Set<SysExSendRequest>() private func sendSysExMessagesAsynchronously(_ messages: [SystemExclusiveMessage]) { for message in messages { for destination in destinations { if let request = SysExSendRequest(message: message, destination: destination, customSysExBufferSize: customSysExBufferSize) { sysExSendRequests.insert(request) request.delegate = self delegate?.portOutputStream(self, willBeginSendingSysEx: request) request.send() } } } } } extension PortOutputStream: SysExSendRequestDelegate { public func sysExSendRequestDidFinish(_ sysExSendRequest: SysExSendRequest) { sysExSendRequests.remove(sysExSendRequest) delegate?.portOutputStream(self, didEndSendingSysEx: sysExSendRequest) } } public protocol PortOutputStreamDelegate: NSObjectProtocol { // Sent when one of the stream's destination endpoints is removed by the system. func portOutputStreamDestinationDisappeared(_ stream: PortOutputStream) // Sent when sysex begins sending and ends sending. func portOutputStream(_ stream: PortOutputStream, willBeginSendingSysEx request: SysExSendRequest) func portOutputStream(_ stream: PortOutputStream, didEndSendingSysEx request: SysExSendRequest) }
3d5bc56ea04f7672834ddbad82a23181
36
147
0.681113
false
false
false
false
ben-ng/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSPredicate.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSPredicate { // + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...; public convenience init(format predicateFormat: String, _ args: CVarArg...) { let va_args = getVaList(args) self.init(format: predicateFormat, arguments: va_args) } }
1b60ef887a61921f23b10f177e4c2372
37.5
80
0.589138
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/SILGen/lifetime_unions.swift
apache-2.0
4
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s enum TrivialUnion { case Foo case Bar(Int) case Bas(Int, Int) } class C { init() {} } enum NonTrivialUnion1 { case Foo case Bar(Int) case Bas(Int, C) } enum NonTrivialUnion2 { case Foo case Bar(C) case Bas(Int, C) } enum NonTrivialUnion3 { case Bar(C) case Bas(Int, C) } /* TODO: Address-only unions enum AddressOnlyUnion<T> { case Foo case Bar(T) case Bas(Int, T) } */ func getTrivialUnion() -> TrivialUnion { return .Foo } func getNonTrivialUnion1() -> NonTrivialUnion1 { return .Foo } func getNonTrivialUnion2() -> NonTrivialUnion2 { return .Foo } func getNonTrivialUnion3() -> NonTrivialUnion3 { return .Bar(C()) } /* TODO: Address-only unions func getAddressOnlyUnion<T>(_: T.Type) -> AddressOnlyUnion<T> { return .Foo } */ // CHECK-LABEL: sil hidden @_T015lifetime_unions19destroyUnionRValuesyyF : $@convention(thin) () -> () { func destroyUnionRValues() { // CHECK: [[GET_TRIVIAL_UNION:%.*]] = function_ref @_T015lifetime_unions15getTrivialUnionAA0dE0OyF : $@convention(thin) () -> TrivialUnion // CHECK: [[TRIVIAL_UNION:%.*]] = apply [[GET_TRIVIAL_UNION]]() : $@convention(thin) () -> TrivialUnion // CHECK-NOT: [[TRIVIAL_UNION]] getTrivialUnion() // CHECK: [[GET_NON_TRIVIAL_UNION_1:%.*]] = function_ref @_T015lifetime_unions19getNonTrivialUnion1AA0deF0OyF : $@convention(thin) () -> @owned NonTrivialUnion1 // CHECK: [[NON_TRIVIAL_UNION_1:%.*]] = apply [[GET_NON_TRIVIAL_UNION_1]]() : $@convention(thin) () -> @owned NonTrivialUnion1 // CHECK: destroy_value [[NON_TRIVIAL_UNION_1]] : $NonTrivialUnion1 getNonTrivialUnion1() // CHECK: [[GET_NON_TRIVIAL_UNION_2:%.*]] = function_ref @_T015lifetime_unions19getNonTrivialUnion2AA0deF0OyF : $@convention(thin) () -> @owned NonTrivialUnion2 // CHECK: [[NON_TRIVIAL_UNION_2:%.*]] = apply [[GET_NON_TRIVIAL_UNION_2]]() : $@convention(thin) () -> @owned NonTrivialUnion2 // CHECK: destroy_value [[NON_TRIVIAL_UNION_2]] : $NonTrivialUnion2 getNonTrivialUnion2() // CHECK: [[GET_NON_TRIVIAL_UNION_3:%.*]] = function_ref @_T015lifetime_unions19getNonTrivialUnion3AA0deF0OyF : $@convention(thin) () -> @owned NonTrivialUnion3 // CHECK: [[NON_TRIVIAL_UNION_3:%.*]] = apply [[GET_NON_TRIVIAL_UNION_3]]() : $@convention(thin) () -> @owned NonTrivialUnion3 // CHECK: destroy_value [[NON_TRIVIAL_UNION_3]] : $NonTrivialUnion3 getNonTrivialUnion3() /* TODO: Address-only unions // C/HECK: [[GET_ADDRESS_ONLY_UNION:%.*]] = function_ref @_TF15lifetime_unions19getAddressOnlyUnionU__FMQ_GOS_16AddressOnlyUnionQ__ : $@convention(thin) <T> T.Type -> AddressOnlyUnion<T> // C/HECK: [[GET_ADDRESS_ONLY_UNION_SPEC:%.*]] = specialize [[GET_ADDRESS_ONLY_UNION]] : $@convention(thin) <T> T.Type -> AddressOnlyUnion<T>, $@thin Int64.Type -> AddressOnlyUnion<Int64>, T = Int // C/HECK: [[ADDRESS_ONLY_UNION_ADDR:%.*]] = alloc_stack $AddressOnlyUnion<Int64> // C/HECK: apply [[GET_ADDRESS_ONLY_UNION_SPEC]]([[ADDRESS_ONLY_UNION_ADDR]], {{%.*}}) : $@thin Int64.Type -> AddressOnlyUnion<Int64> // C/HECK: destroy_addr [[ADDRESS_ONLY_UNION_ADDR]] : $*AddressOnlyUnion<Int64> // C/HECK: dealloc_stack [[ADDRESS_ONLY_UNION_ADDR]] : $*AddressOnlyUnion<Int64> getAddressOnlyUnion(Int) */ }
d26dd7f3ef960a78ec63a72dfe2a0ef5
42.402597
200
0.676541
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Views/ActiveNetworkView.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import UIKit import TinyConstraints import SweetUIKit class ActiveNetworkView: UIView { static let height: CGFloat = 32.0 private let margin: CGFloat = 6.0 var heightConstraint: NSLayoutConstraint? private var isDefaultNetworkActive = NetworkSwitcher.shared.isDefaultNetworkActive private lazy var textLabel: UILabel = { let textLabel = UILabel(withAutoLayout: true) textLabel.font = Theme.regular(size: 14) textLabel.textColor = Theme.lightTextColor textLabel.textAlignment = .center textLabel.adjustsFontSizeToFitWidth = true textLabel.minimumScaleFactor = 0.8 return textLabel }() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { backgroundColor = Theme.mediumTextColor.withAlphaComponent(0.98) addSubview(textLabel) textLabel.edges(to: self, insets: UIEdgeInsets(top: margin, left: margin, bottom: -margin, right: -margin), priority: .defaultHigh) heightConstraint = heightAnchor.constraint(equalToConstant: 0) if !isDefaultNetworkActive { textLabel.text = String(format: Localized.active_network_format, NetworkSwitcher.shared.activeNetworkLabel) } heightConstraint?.isActive = true } }
b0a0b3c0e02e4c07620ed83ee96bcc79
31.333333
139
0.70478
false
false
false
false
shaps80/InkKit
refs/heads/master
Pod/Classes/Grid.swift
mit
1
/* Copyright © 13/05/2016 Shaps 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 /** * Defines the components that make up a grid -- used for constructing a path from a grid */ public struct GridComponents : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// Represents the outline of the grid public static var outline: GridComponents { return GridComponents(rawValue: 1 << 0) } /// Represents the column separators of a grid public static var columns: GridComponents { return GridComponents(rawValue: 1 << 1) } /// Represents the row separators of a grid public static var rows: GridComponents { return GridComponents(rawValue: 1 << 2) } /// Represents all components public static var all: GridComponents { return [ .outline, .columns, .rows ] } } /** * Represents an entire row in a table */ public struct Row { public let bounds: CGRect } /** * Represents an entire column in a table */ public struct Column { public let rows: [Row] public let bounds: CGRect } /** * Represents columns and rows that make up a table */ public struct Grid { /// Returns the columns associated with this table public let columns: [Column] /// Returns the bounds for this table public let bounds: CGRect /** Creates a new table with the specified col/row counts - parameter colCount: The number of columns - parameter rowCount: The number of rows - parameter bounds: The bounds for this table - returns: A new table */ public init(colCount: Int, rowCount: Int, bounds: CGRect) { self.bounds = bounds var columns = [Column]() guard colCount > 0 || rowCount > 0 else { self.columns = columns return } for col in 0..<colCount { var rows = [Row]() let colWidth = self.bounds.width / CGFloat(colCount) let colRect = CGRect(x: self.bounds.minX + colWidth * CGFloat(col), y: self.bounds.minY, width: colWidth, height: self.bounds.height) for row in 0..<rowCount { let rowHeight = self.bounds.height / CGFloat(rowCount) let rowRect = CGRect(x: self.bounds.minX, y: self.bounds.minY + rowHeight * CGFloat(row), width: self.bounds.width, height: rowHeight) let row = Row(bounds: rowRect) rows.append(row) } let column = Column(rows: rows, bounds: colRect) columns.append(column) } self.columns = columns } /** Returns the column/row position for the specified cell index in the table - parameter index: The index of the cell to query - returns: The column and row representing this index */ public func positionForCell(atIndex index: Int) -> (col: Int, row: Int) { let row = Int(ceil(CGFloat(index) / CGFloat(columns.count))) let col = Int(CGFloat(index % columns.count)) return (col, row) } /** Returns the bounding rectangle for the cell at the specified index - parameter index: The index of the cell - returns: The bounding rectangle */ public func boundsForCell(atIndex index: Int) -> CGRect { let (col, row) = positionForCell(atIndex: index) return boundsForCell(col: col, row: row) } /** Returns a bounding rectangle that contains both the source and destination cells - parameter sourceColumn: The source column - parameter sourceRow: The source row - parameter destinationColumn: The destination column - parameter destinationRow: The destination row - returns: The bounding rectangle */ public func boundsForRange(sourceColumn: Int, sourceRow: Int, destinationColumn: Int, destinationRow: Int) -> CGRect { let rect1 = boundsForCell(col: sourceColumn, row: sourceRow) let rect2 = boundsForCell(col: destinationColumn, row: destinationRow) return rect1.union(rect2) } /** Returns the bounding rectangle for a specific cell - parameter col: The column - parameter row: The row - returns: The bounding rectangle */ public func boundsForCell(col: Int, row: Int) -> CGRect { guard col < columns.count else { return CGRect.zero } let colWidth = bounds.width / CGFloat(columns.count) let column = columns[col] guard row < column.rows.count else { return CGRect.zero } let row = column.rows[row] var rect = column.bounds rect.origin.y = row.bounds.minY rect.size.width = colWidth rect.size.height = bounds.height / CGFloat(column.rows.count) return rect } /** Enumerates all cells in the grid - parameter enumerator: The enumerator to execute for each cell -- returns the index, column, row and bounding rectangle representing this cell */ public func enumerateCells(_ enumerator: (_ index: Int, _ col: Int, _ row: Int, _ bounds: CGRect) -> Void) { guard let column = columns.first else { return } let rowCount = column.rows.count var index = 0 for rowIndex in 0..<rowCount { for colIndex in 0..<columns.count { let rect = boundsForCell(col: colIndex, row: rowIndex) enumerator(index, colIndex, rowIndex, rect) index += 1 } } } } extension Grid { /** Returns a Bezier Path representation of the grid -- you can use this to stroke the path using one of InkKit's other methods - parameter components: The components to draw -- Outline, Columns, Rows - returns: A bezier path representation */ public func path(include components: GridComponents) -> BezierPath { let path = CGMutablePath() if components.contains(.columns) { for (index, column) in self.columns.enumerated() { if index == 0 { continue } var origin = column.bounds.origin origin.y = column.bounds.maxY path.move(to: CGPoint(x: column.bounds.origin.x, y: column.bounds.origin.y)) path.addLine(to: CGPoint(x: origin.x, y: origin.y)) } } if components.contains(.rows) { if let column = self.columns.first { for (index, row) in column.rows.enumerated() { if index == 0 { continue } var origin = row.bounds.origin origin.x = row.bounds.maxX path.move(to: CGPoint(x: column.bounds.origin.x, y: row.bounds.origin.y)) path.addLine(to: CGPoint(x: origin.x, y: origin.y)) } } } if components.contains(.outline) { path.addRect(bounds) } return BezierPath(cgPath: path) } }
063e80387232f604efeb16147dc4a195
28.980469
146
0.660717
false
false
false
false
livioso/cpib
refs/heads/master
Compiler/Compiler/scanner/scanner.swift
mit
1
import Foundation class Scanner: KeywordProvider { enum ScannerState { case IdleState // just waiting case InitialState case LiteralState case IdentState case SymbolState case ErrorState(description: String) } struct Line { var number: Int = 0 var index: String.CharacterView.Index var content: String = "" { didSet { // reset index when the content changes index = content.startIndex } } init(content: String, number: Int) { self.content = content self.number = number self.index = self.content.startIndex } mutating func next() -> Character?{ if(index == content.characters.endIndex) { return nil } let i = index index = index.successor() return content[i]; } mutating func back(){ if(index != content.characters.startIndex) {index = index.predecessor()} } func previous() -> Character?{ if(index >= content.characters.startIndex) {return nil} else { return content[index] } } } // the current token range "under construction" once an entire // token is found this is reset to its initial value (0, 0) var currentTokenRange: Range<Int> = Range<Int>(start: 0, end: 0) // the current line (we read the file line wise) var currentLine: Line = Line(content: "", number: 0) // the current state: as long as it is in remains in .IdleState // it will not do anything. Once we have transition <to> any other // state it will start processing currentLine till it will // eventually end up in .IdleState again. var currentState: ScannerState = .IdleState { didSet { if currentLine.content != "" { stateChangeHandler(from: oldValue, to: currentState) } } } // the most important thing here var tokenlist: [Token] = [] /////////////////////////////////////////////////////////// // Scanner Scan Functions /////////////////////////////////////////////////////////// // Reads the file line wise and returns the tokenlist // for the token list func scan (fromPath: String) -> [Token] { tokenlist = [] // reset old tokenlist if let lines = getContentByLine(fromPath) { for line in lines { prepareNewLine(line) processNewLine() } } // make sure we have at least the SENTINEL tokenlist.append(Token(terminal: Terminal.SENTINEL)) print("\n✅ Scan finished: Tokenlist is:") for token in tokenlist { print("🔘\(token.terminal)") if let attr = token.attribute { print("➡️\(attr)") } } return tokenlist } /////////////////////////////////////////////////////////// // Scanner Token Functions /////////////////////////////////////////////////////////// private func buildTokenFrom(aRange: Range<Int>) -> String { // end position must be given as negative advanceBy(-n)! let currentLineLength = currentLine.content.characters.count let fromTokenEnd = currentLineLength - aRange.endIndex let toTokenStart = aRange.startIndex let tokenRange: Range<String.Index> = Range( start: currentLine.content.startIndex.advancedBy(toTokenStart), end: currentLine.content.endIndex.advancedBy(-fromTokenEnd)) // Rewind iterator by one so we don't miss cases where // there is no <whitespace> <tab> or so to seperate it: // for example: (a:2) or divide(): currentLine.back() return currentLine.content.substringWithRange(tokenRange) } private func newLiteralToken() { let literal = buildTokenFrom(currentTokenRange) //check if Int is not out of Int64 range let checkInt = Double.init(literal) if checkInt != nil && checkInt > 2_147_483_647 { currentState = .ErrorState(description: "❌ Int64 out of Range: \(currentLine.number)") } else if checkInt != nil && checkInt < -2_147_483_648 { currentState = .ErrorState(description: "❌ Int64 out of Range: \(currentLine.number)") } else { let token = Token( terminal: Terminal.LITERAL, lineNumber: currentLine.number, attribute: Token.Attribute.Integer(Int(literal)!)) print("✅ New literal token: \(literal)") tokenlist.append(token) // be ready for the next token currentTokenRange.startIndex = currentTokenRange.endIndex } } private func newIdentifierToken() { let identifier = buildTokenFrom(currentTokenRange) if var keywordToken = matchKeyword(identifier) { keywordToken.lineNumber = currentLine.number; print("✅ New keyword token: \(identifier)") tokenlist.append(keywordToken) } else { let token = Token( terminal: Terminal.IDENT, lineNumber: currentLine.number, attribute: Token.Attribute.Ident(identifier)) print("✅ New identifier token: \(identifier)") tokenlist.append(token) } } private func newSymbolToken() { let symbol = buildTokenFrom(currentTokenRange) if var keywordToken = matchKeyword(symbol) { keywordToken.lineNumber = currentLine.number; print("✅ New keyword token: \(symbol)") tokenlist.append(keywordToken) } else { currentState = .ErrorState(description: "❌ Unrecogizable symbol \(symbol)" ) } } /////////////////////////////////////////////////////////// // Scanner State Handling Functions /////////////////////////////////////////////////////////// private func stateChangeHandler(from from: ScannerState, to: ScannerState) { print("➡️ Changed current state from <\(from)> to <\(to)>.") // we have reached the end of a token and come back // to the .InitialState => create the new token. :) switch (from, to) { case (.SymbolState, .SymbolState): fallthrough // continues case (.IdentState, .IdentState): fallthrough // continues case (.LiteralState, .LiteralState): break // continues case (.LiteralState, _): newLiteralToken() case (.IdentState, _): newIdentifierToken() case (.SymbolState, _): newSymbolToken() case (_, _): break } // only increment endIndex when we did not // add a new token switch (from, to) { case (.LiteralState, .InitialState): fallthrough case (.IdentState, .InitialState): fallthrough case (.SymbolState, .InitialState): break case (_, _): currentTokenRange.endIndex++ } switch to { case .IdentState: identStateHandler() case .LiteralState: literalStateHandler() case .InitialState: initialStateHandler() case .SymbolState: symbolStateHandler() case _: break } } private func initialStateHandler() { if let next = currentLine.next() { currentTokenRange.startIndex = currentTokenRange.endIndex switch(next.kind()) { case .Literal: currentState = .LiteralState // literal starts case .Letter: currentState = .IdentState // identifier starts case .Symbol: currentState = .SymbolState // symbol starts case .Skippable: currentState = .InitialState // still nothing case .Other: currentState = .ErrorState(description: " Unsupported Character: \(currentLine.number)") } } else { currentState = .IdleState // end of line } } private func literalStateHandler() { if let next = currentLine.next() { switch(next.kind()) { case .Literal: currentState = .LiteralState // literal continues case .Skippable: currentState = .InitialState // literal ends case .Symbol: currentState = .InitialState // literal ends case .Letter: currentState = .InitialState // literal ends case _: currentState = .ErrorState(description: "❌ Literal not properly finished: \(currentLine.number)") } } else { currentState = .InitialState } } private func identStateHandler() { if let next = currentLine.next() { switch(next.kind()) { case .Literal: currentState = .IdentState // identifier continues case .Letter: currentState = .IdentState // identifier continues case .Symbol: currentState = .InitialState // identifier ends case .Skippable: currentState = .InitialState // idetifier ends case .Other: currentState = .ErrorState(description: "❌ Unsupported Character: \(currentLine.number)") } } else { currentState = .InitialState } } private func symbolStateHandler() { if let next = currentLine.next() { switch(next.kind()) { case .Symbol: currentState = .SymbolState // symbol continues case .Literal: currentState = .InitialState // symbol ends case .Letter: currentState = .InitialState // symbol ends case .Skippable: currentState = .InitialState // symbol ends case .Other: currentState = .ErrorState(description: "❌ Unsupported Character: \(currentLine.number)") } } else { currentState = .InitialState } } // reset the range, state and currentline private func prepareNewLine(newLineContent: String) { currentState = .IdleState currentTokenRange = Range(start: 0, end: 0) currentLine = Line( // append whitespace to make further // end of line / range checking unnecessary // in buildTokenFrom(). content: newLineContent + " ", number: (currentLine.number + 1)) } private func processNewLine() { if let next = currentLine.next() { switch next.kind() { case .Letter: currentState = .IdentState case .Literal: currentState = .LiteralState case .Skippable: currentState = .InitialState case .Symbol: currentState = .SymbolState case _: print("⚠️ Line \(currentLine.number) is just empty.") } } } /////////////////////////////////////////////////////////// // Scanner Input Functions /////////////////////////////////////////////////////////// var debugContent: String? = nil { didSet { print("⚠️ Debugging content set.") } }; func getContentByLine(fromPath: String) -> [String]? { if debugContent != nil { return debugContent!.componentsSeparatedByString("\n") } let location = NSString(string: fromPath).stringByExpandingTildeInPath if let content = try? NSString( contentsOfFile: location, encoding: NSUTF8StringEncoding) as String { return content.componentsSeparatedByString("\n") } return nil } }
0d5638e6abf2aaf9f450a91cc545e156
29.578947
98
0.656981
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/Dashboard/ViewModel/UpdatePreviewViewModel.swift
apache-2.0
1
import KsApi import Library import ReactiveSwift import WebKit internal protocol UpdatePreviewViewModelInputs { /// Call with the update draft. func configureWith(draft: UpdateDraft) /// Call when the webview needs to decide a policy for a navigation action. Returns the decision policy. func decidePolicyFor(navigationAction: WKNavigationActionData) -> WKNavigationActionPolicy /// Call when the publish button is tapped. func publishButtonTapped() /// Call when the publish confirmation is tapped. func publishConfirmationButtonTapped() /// Call when the view loads. func viewDidLoad() } internal protocol UpdatePreviewViewModelOutputs { /// Emits when publishing succeeds. var goToUpdate: Signal<(Project, Update), Never> { get } /// Emits when the view should show a publish confirmation alert with detail message. var showPublishConfirmation: Signal<String, Never> { get } /// Emits when publishing fails. var showPublishFailure: Signal<(), Never> { get } /// Emits a request that should be loaded into the webview. var webViewLoadRequest: Signal<URLRequest, Never> { get } } internal protocol UpdatePreviewViewModelType { var inputs: UpdatePreviewViewModelInputs { get } var outputs: UpdatePreviewViewModelOutputs { get } } internal final class UpdatePreviewViewModel: UpdatePreviewViewModelInputs, UpdatePreviewViewModelOutputs, UpdatePreviewViewModelType { internal init() { let draft = self.draftProperty.signal.skipNil() let initialRequest = draft .takeWhen(self.viewDidLoadProperty.signal) .map { AppEnvironment.current.apiService.previewUrl(forDraft: $0) } .skipNil() .map { AppEnvironment.current.apiService.preparedRequest(forURL: $0) } let redirectRequest = self.policyForNavigationActionProperty.signal.skipNil() .map { $0.request } .filter { !AppEnvironment.current.apiService.isPrepared(request: $0) && Navigation.Project.updateWithRequest($0) != nil } .map { AppEnvironment.current.apiService.preparedRequest(forRequest: $0) } self.webViewLoadRequest = Signal.merge(initialRequest, redirectRequest) self.policyDecisionProperty <~ self.policyForNavigationActionProperty.signal.skipNil() .map { action in action.navigationType == .other || action.targetFrame?.mainFrame == .some(false) ? .allow : .cancel } let projectEvent = draft .switchMap { AppEnvironment.current.apiService.fetchProject(param: .id($0.update.projectId)) .materialize() } let project = projectEvent .values() self.showPublishConfirmation = project .map { // swiftformat:disable wrap Strings.dashboard_post_update_preview_confirmation_alert_this_will_notify_backers_that_a_new_update_is_available(backer_count: $0.stats.backersCount) // swiftformat:enable wrap } .takeWhen(self.publishButtonTappedProperty.signal) let publishEvent = draft .takeWhen(self.publishConfirmationButtonTappedProperty.signal) .switchMap { AppEnvironment.current.apiService.publish(draft: $0) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } let update = publishEvent .values() self.goToUpdate = Signal.combineLatest(project, update) self.showPublishFailure = publishEvent .errors() .ignoreValues() } fileprivate let policyForNavigationActionProperty = MutableProperty<WKNavigationActionData?>(nil) fileprivate let policyDecisionProperty = MutableProperty(WKNavigationActionPolicy.allow) internal func decidePolicyFor(navigationAction: WKNavigationActionData) -> WKNavigationActionPolicy { self.policyForNavigationActionProperty.value = navigationAction return self.policyDecisionProperty.value } fileprivate let publishButtonTappedProperty = MutableProperty(()) internal func publishButtonTapped() { self.publishButtonTappedProperty.value = () } fileprivate let publishConfirmationButtonTappedProperty = MutableProperty(()) internal func publishConfirmationButtonTapped() { self.publishConfirmationButtonTappedProperty.value = () } fileprivate let draftProperty = MutableProperty<UpdateDraft?>(nil) internal func configureWith(draft: UpdateDraft) { self.draftProperty.value = draft } fileprivate let viewDidLoadProperty = MutableProperty(()) internal func viewDidLoad() { self.viewDidLoadProperty.value = () } let goToUpdate: Signal<(Project, Update), Never> let showPublishConfirmation: Signal<String, Never> let showPublishFailure: Signal<(), Never> let webViewLoadRequest: Signal<URLRequest, Never> internal var inputs: UpdatePreviewViewModelInputs { return self } internal var outputs: UpdatePreviewViewModelOutputs { return self } }
98e1182048f3c31c8e3d3ac6b64a167a
34.521739
157
0.740106
false
false
false
false
okerivy/AlgorithmLeetCode
refs/heads/master
AlgorithmLeetCode/AlgorithmLeetCode/E_437_PathSumIII.swift
mit
1
// // E_437_PathSumIII.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/20. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/path-sum-iii import Foundation // MARK: - 题目名称: 437. Path Sum III /* MARK: - 所属类别: 标签: Tree 相关题目: (E) Path Sum (M) Path Sum II */ /* MARK: - 题目英文: You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. Example: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11 */ /* MARK: - 题目翻译: 给定一个二叉树,其中每个节点包含一个整数值。 求与给定值求和的路径数。 该路径不需要在根或叶开始或结束,但必须向下(仅从父节点到子节点)。 该树有不超过1000个节点和值在范围- 1000000到1000000。 例子: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 返回3。总和为8的路径是: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11 */ /* MARK: - 解题思路: 树的遍历,在遍历节点的同时,以经过的节点为根,寻找子树中和为sum的路径。 */ /* MARK: - 复杂度分析: 平衡树的时间复杂度为O(n*logn) 在最坏的情况下,时间复杂度确实是O(n^2) */ // MARK: - 代码: private class Solution { /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ func pathSum(_ root: TreeNode?, _ sum: Int) -> Int { // 定义一个变量记录次数 var ans = 0 // 为空, 直接返回 0 if root == nil { return ans} // 查找根节点的 满足条件的个数 ans += DFS(root, sum) // 查找左右结点的 满足条件的个数 ans += pathSum(root?.left, sum) ans += pathSum(root?.right, sum) return ans } private func DFS(_ root: TreeNode?, _ sum: Int) -> Int { // 定义一个变量记录次数 var res = 0 // 为空, 直接返回 0 if root == nil { return res } // 满足条件 res 加1 if sum == root?.value { res += 1} // 查找左右结点的 满足条件的个数 res += DFS(root?.left, sum - (root?.value)!) res += DFS(root?.right, sum - (root?.value)!) return res } } // MARK: - 测试代码: func PathSumIII() { let root1 = CreateBinaryTree().convertArrayToTree([1, 2, 2, 3, 4, 4, 3]) let root2 = CreateBinaryTree().convertArrayToTree([5, 4, 8, 11, Int.min, 13, 4, 7, 2, Int.min, Int.min, 5, 1]) let root3 = CreateBinaryTree().convertArrayToTree([10, 5, -3, 3, 2, Int.min, 11, 3, -2, Int.min, 1]) print(Solution().pathSum(root1, 6)) print(Solution().pathSum(root2, 22)) print(Solution().pathSum(root3, 8)) }
a2f61139ba03fbd370a96c1ff064a464
18.327044
138
0.531403
false
false
false
false
sauvikatinnofied/SwiftAutolayout
refs/heads/master
Autolayout/Autolayout/ViewController.swift
mit
1
// // ViewController.swift // Autolayout // // Created by Sauvik Dolui on 24/03/17. // Copyright © 2017 Sauvik Dolui. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. drawMyCountryFlag() } func drawMyCountryFlag() { view.backgroundColor = .black let centerView = UIView.autolayoutView() view.addSubview(centerView) centerView._layoutInSuper(percentage: 90.0) let orangeView = UIView.autolayoutView() orangeView.backgroundColor = .orange centerView.addSubview(orangeView) let whiteView = UIView.autolayoutView() whiteView.backgroundColor = .white centerView.addSubview(whiteView) let greenView = UIView.autolayoutView() greenView.backgroundColor = .green centerView.addSubview(greenView) orangeView._setWidth(sidePadding: 0.0) // Width, X set orangeView._setHeight(height: 50.0) // Height Set orangeView._setTop(topPadding: 50) // Top Padding // Adding the white view whiteView._setSizeEqualTo(view: orangeView) // Size Fixed whiteView._setLeftAlignWith(view: orangeView) // X Set whiteView._setTopFromBottomEdgeOf(view: orangeView, offset: 3.0) // Y Set // Adding the green view greenView._setSizeEqualTo(view: orangeView) // Size Fixed greenView._setLeftAlignWith(view: orangeView) // X Set greenView._setTopFromBottomEdgeOf(view: whiteView, offset: 3.0) // Y Set } }
305d9304c6d63234ef6c82a098036802
28.779661
81
0.622083
false
false
false
false
MangoMade/MMSegmentedControl
refs/heads/master
Source/SegmentedControlItemCell.swift
mit
1
// // SegmentedControlItemCell.swift // MMSegmentedControl // // Created by Aqua on 2017/4/11. // Copyright © 2017年 Aqua. All rights reserved. // import UIKit internal class SegmentedControlItemCell: UICollectionViewCell { let titleLabel = UILabel() var font: UIFont = Const.defaultFont { didSet { updateTransform() } } var selectedFont: UIFont = Const.defaultSelectedFont { didSet { titleLabel.font = selectedFont updateTransform() } } var selectedTextColor = Const.defaultSelectedTextColor { didSet { if isSelected { self.titleLabel.textColor = selectedTextColor } } } var normalTextColor = Const.defaultTextColor { didSet { if !isSelected { self.titleLabel.textColor = normalTextColor } } } private var textTransform: CGAffineTransform { didSet { titleLabel.transform = isSelected ? .identity : textTransform } } var isChoosing: Bool = false func set(isChoosing: Bool, animated: Bool = true, completion: ((Bool) -> Void)?) { self.isChoosing = isChoosing UIView.animate(withDuration: animated ? Const.animationDuration : 0, animations: { self.titleLabel.transform = self.isChoosing ? CGAffineTransform.identity : self.textTransform if self.isChoosing { self.titleLabel.font = self.selectedFont } else { self.titleLabel.font = self.font.withSize(self.selectedFont.pointSize) } }, completion: completion) let after = Const.animationDuration / 2.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + after) { self.titleLabel.textColor = self.isChoosing ? self.selectedTextColor : self.normalTextColor } } override init(frame: CGRect) { let scale = self.font.pointSize / self.selectedFont.pointSize textTransform = CGAffineTransform(scaleX: scale, y: scale) super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { let scale = self.font.pointSize / self.selectedFont.pointSize textTransform = CGAffineTransform(scaleX: scale, y: scale) super.init(coder: aDecoder) commonInit() } private func commonInit() { translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = selectedFont titleLabel.transform = textTransform addSubview(titleLabel) NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0).isActive = true } private func updateTransform() { let scale = self.font.pointSize / self.selectedFont.pointSize textTransform = CGAffineTransform(scaleX: scale, y: scale) } }
531907f4d40fb02c5dccf12f95e0737f
30.955752
105
0.567433
false
false
false
false
vapor-community/stripe
refs/heads/main
Tests/StripeTests/TransferTests.swift
mit
1
// // TransferTests.swift // StripeTests // // Created by Andrew Edwards on 4/3/18. // import XCTest @testable import Stripe @testable import Vapor class TransferTests: XCTestCase { let transferString = """ { "id": "tr_164xRv2eZvKYlo2CZxJZWm1E", "object": "transfer", "amount": 200, "amount_reversed": 200, "balance_transaction": "txn_19XJJ02eZvKYlo2ClwuJ1rbA", "created": 1432229235, "currency": "usd", "description": "transfers ahoy!", "destination": "acct_164wxjKbnvuxQXGu", "destination_payment": "py_164xRvKbnvuxQXGuVFV2pZo1", "livemode": false, "metadata": { "order_id": "6735" }, "reversals": { "object": "list", "data": [ { "id": "trr_1BGmS02eZvKYlo2CklK9McmT", "object": "transfer_reversal", "amount": 100, "balance_transaction": "txn_1BGmS02eZvKYlo2C9f16WPBN", "created": 1508928572, "currency": "usd", "metadata": { "hello":"world" }, "transfer": "tr_164xRv2eZvKYlo2CZxJZWm1E" }, ], "has_more": false, "total_count": 2, "url": "/v1/transfers/tr_164xRv2eZvKYlo2CZxJZWm1E/reversals" }, "reversed": true, "source_transaction": "ch_164xRv2eZvKYlo2Clu1sIJWB", "source_type": "card", "transfer_group": "group_ch_164xRv2eZvKYlo2Clu1sIJWB" } """ func testTransferParsedProperly() throws { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let body = HTTPBody(string: transferString) var headers: HTTPHeaders = [:] headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) let request = HTTPRequest(headers: headers, body: body) let transfer = try decoder.decode(StripeTransfer.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) transfer.do { (tran) in XCTAssertEqual(tran.id, "tr_164xRv2eZvKYlo2CZxJZWm1E") XCTAssertEqual(tran.object, "transfer") XCTAssertEqual(tran.amount, 200) XCTAssertEqual(tran.amountReversed, 200) XCTAssertEqual(tran.balanceTransaction, "txn_19XJJ02eZvKYlo2ClwuJ1rbA") XCTAssertEqual(tran.created, Date(timeIntervalSince1970: 1432229235)) XCTAssertEqual(tran.currency, .usd) XCTAssertEqual(tran.description, "transfers ahoy!") XCTAssertEqual(tran.destination, "acct_164wxjKbnvuxQXGu") XCTAssertEqual(tran.destinationPayment, "py_164xRvKbnvuxQXGuVFV2pZo1") XCTAssertEqual(tran.livemode, false) XCTAssertEqual(tran.metadata["order_id"], "6735") XCTAssertEqual(tran.reversed, true) XCTAssertEqual(tran.sourceTransaction, "ch_164xRv2eZvKYlo2Clu1sIJWB") XCTAssertEqual(tran.sourceType, "card") XCTAssertEqual(tran.transferGroup, "group_ch_164xRv2eZvKYlo2Clu1sIJWB") // This test covers the transfer reversal XCTAssertEqual(tran.reversals?.object, "list") XCTAssertEqual(tran.reversals?.hasMore, false) XCTAssertEqual(tran.reversals?.totalCount, 2) XCTAssertEqual(tran.reversals?.url, "/v1/transfers/tr_164xRv2eZvKYlo2CZxJZWm1E/reversals") XCTAssertEqual(tran.reversals?.data?[0].id, "trr_1BGmS02eZvKYlo2CklK9McmT") XCTAssertEqual(tran.reversals?.data?[0].object, "transfer_reversal") XCTAssertEqual(tran.reversals?.data?[0].amount, 100) XCTAssertEqual(tran.reversals?.data?[0].balanceTransaction, "txn_1BGmS02eZvKYlo2C9f16WPBN") XCTAssertEqual(tran.reversals?.data?[0].created, Date(timeIntervalSince1970: 1508928572)) XCTAssertEqual(tran.reversals?.data?[0].metadata["hello"], "world") XCTAssertEqual(tran.reversals?.data?[0].transfer, "tr_164xRv2eZvKYlo2CZxJZWm1E") }.catch { (error) in XCTFail("\(error.localizedDescription)") } } catch { XCTFail("\(error.localizedDescription)") } } }
90588fadf5686a9ee82eef69f8b23c1a
39.056604
123
0.614696
false
true
false
false
oceanfive/swift
refs/heads/master
swift_two/swift_two/Classes/ViewModel/HYStausInfoViewModel.swift
mit
1
// // HYStausInfoViewModel.swift // swift_two // // Created by ocean on 16/6/20. // Copyright © 2016年 ocean. All rights reserved. // import UIKit //MARK: - 这个类中的数组传递不出去,总是出错,因而采用闭包的形式把结果传递出去 class HYStausInfoViewModel: NSObject { // static var dataArrary: NSMutableArray! = [] //MARK: - 闭包的定义以及初始化,还可以给闭包设置别名 // var success: (NSData?, NSURLResponse?) -> () = {_,_ in } // typealias success = (Int, Int) -> () //MARK: - 获取微博数据 //MARK: - 如果设置返回值,第一次为nil???? //MARK: - 这里需要注意闭包的写法和oc的区别:oc中需要给block定义别名,然后把block作为参数传递,swift中不需要定义别名,可以直接把闭包作为参数传递 //MARK: - 这里的参数列表success: (NSData?, NSURLResponse?) -> (), fail: (NSError?) -> ()作为回调 class func getStatusesInfo(success: (NSData?, NSURLResponse?) -> (), failure: (NSError?) -> ()) { //获取access_token let model: HYAccessTokenModel? = HYAccountTool.getAccount() if model != nil { //取到access_token值 //MARK: - 这里账号工具类的属性access_token为String?需要进行强制解包!这里进行两次强制解包!否则会崩溃 let urlString = kHome_timelineString + "?" + "access_token=\(model!.access_token!)" let url = NSURL(string: urlString) let request = NSURLRequest(URL: url!) NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in if error == nil && data != nil { //MARK: - 相应成功,闭包传递参数, 这里是闭包的名称success,然后给闭包传递参数data和response success(data, response) //MARK: - swift中的NSJSONReadingOptions是一个结构体,但是oc中的是一个枚举类型 //MARK: - 这里的方法JSONObjectWithData有肯能 throw,需要用try // let dictData = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.init(rawValue: 0)) //MARK: - 字典通过key值statuses取出来的是一个数组,即字典数组,通过第三方框架把字典数组转为模型数组 // let modelArray = HYStatuses.mj_objectArrayWithKeyValuesArray(dictData!["statuses"]) //// dataArray = modelArray //MARK: - 这里return会报错????!!!解决方法?????!!! //MARK: - oc和swift类型转换 用as ()® // let modelone: HYStatuses = modelArray.firstObject! as! (HYStatuses) // // print(modelone.text!) // let dataArrary = modelArray as ([AnyObject]) // // print(modelArray) // // print(dataArrary) // print(response) }else { failure(error) } //MARK: - 这里resume是个函数,不是属性,所以需要加上() }).resume() }else { print("未取得到access_token值") } //MARK: - 这里函数有返回值第一次为nil // return dataArray } }
c772ecba89e1659b70f679a21f50d20f
32.821429
160
0.555086
false
false
false
false
obrichak/discounts
refs/heads/master
discounts/Classes/BarCodeGenerator/RSITFGenerator.swift
gpl-3.0
1
// // RSITFGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit // http://www.barcodeisland.com/int2of5.phtml class RSITFGenerator: RSAbstractCodeGenerator { let ITF_CHARACTER_ENCODINGS = [ "00110", "10001", "01001", "11000", "00101", "10100", "01100", "00011", "10010", "01010", ] override func isValid(contents: String) -> Bool { return super.isValid(contents) && contents.length() % 2 == 0 } override func initiator() -> String { return "1010" } override func terminator() -> String { return "1101" } override func barcode(contents: String) -> String { var barcode = "" for i in 0..<contents.length() / 2 { let pair = contents.substring(i * 2, length: 2) let bars = ITF_CHARACTER_ENCODINGS[pair[0].toInt()!] let spaces = ITF_CHARACTER_ENCODINGS[pair[1].toInt()!] for j in 0..<10 { if j % 2 == 0 { let bar = bars[j / 2].toInt() if bar == 1 { barcode += "11" } else { barcode += "1" } } else { let space = spaces[j / 2].toInt() if space == 1 { barcode += "00" } else { barcode += "0" } } } } return barcode } }
b5fa4efeb5f73feb86dda3bfce4d7703
24.815385
68
0.426698
false
false
false
false
matrix-org/matrix-ios-sdk
refs/heads/develop
MatrixSDKTests/Mocks/MockRoomSummary.swift
apache-2.0
1
// // Copyright 2021 The Matrix.org Foundation C.I.C // // 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 internal class MockRoomSummary: NSObject, MXRoomSummaryProtocol { var roomId: String var roomTypeString: String? var roomType: MXRoomType = .room var avatar: String? var displayname: String? var topic: String? var creatorUserId: String = "@room_creator:some_domain.com" var aliases: [String] = [] var historyVisibility: String? = nil var joinRule: String? = kMXRoomJoinRuleInvite var membership: MXMembership = .join var membershipTransitionState: MXMembershipTransitionState = .joined var membersCount: MXRoomMembersCount = MXRoomMembersCount(members: 2, joined: 2, invited: 0) var isConferenceUserRoom: Bool = false var hiddenFromUser: Bool = false var storedHash: UInt = 0 var lastMessage: MXRoomLastMessage? var isEncrypted: Bool = false var trust: MXUsersTrustLevelSummary? var localUnreadEventCount: UInt = 0 var notificationCount: UInt = 0 var highlightCount: UInt = 0 var hasAnyUnread: Bool { return localUnreadEventCount > 0 } var hasAnyNotification: Bool { return notificationCount > 0 } var hasAnyHighlight: Bool { return highlightCount > 0 } var isDirect: Bool { return isTyped(.direct) } var directUserId: String? var others: [String: NSCoding]? var favoriteTagOrder: String? var dataTypes: MXRoomSummaryDataTypes = [] func isTyped(_ types: MXRoomSummaryDataTypes) -> Bool { return (dataTypes.rawValue & types.rawValue) != 0 } var sentStatus: MXRoomSummarySentStatus = .ok var spaceChildInfo: MXSpaceChildInfo? var parentSpaceIds: Set<String> = [] var userIdsSharingLiveBeacon: Set<String> = [] init(withRoomId roomId: String) { self.roomId = roomId super.init() } static func generate() -> MockRoomSummary { return generate(withTypes: []) } static func generateDirect() -> MockRoomSummary { return generate(withTypes: .direct) } static func generate(withTypes types: MXRoomSummaryDataTypes) -> MockRoomSummary { guard let random = MXTools.generateSecret() else { fatalError("Room id cannot be created") } let result = MockRoomSummary(withRoomId: "!\(random):some_domain.com") result.dataTypes = types if types.contains(.invited) { result.membership = .invite result.membershipTransitionState = .invited } return result } override var description: String { return "<MockRoomSummary: \(roomId) \(String(describing: displayname))>" } }
31f1c65acda5bd08cf7f038bd2b06224
25.705426
96
0.644702
false
false
false
false
haskellswift/swift-package-manager
refs/heads/master
Tests/XcodeprojTests/XcodeProjectModelSerializationTests.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import TestSupport @testable import Xcodeproj import XCTest class XcodeProjectModelSerializationTests: XCTestCase { func testBasicProjectSerialization() { // Create a project. let proj = Xcode.Project() // Serialize it to a property list. let plist = proj.generatePlist() // Assert various things about the property list. guard case let .dictionary(topLevelDict) = plist else { XCTFail("top-level of plist must be a dictionary") return } XCTAssertFalse(topLevelDict.isEmpty) // FIXME: We should factor out all of the following using helper assert // functions that deal with the enum casing. // Archive version should be 1. guard case let .string(archiveVersionStr) = topLevelDict["archiveVersion"]! else { XCTFail("top-level plist dictionary must have an `archiveVersion` string") return } XCTAssertEqual(archiveVersionStr, "1") // Object version should be 46 (Xcode 8.0). guard case let .string(objectVersionStr) = topLevelDict["objectVersion"]! else { XCTFail("top-level plist dictionary must have an `objectVersion` string") return } XCTAssertEqual(objectVersionStr, "46") // There should be a root object. guard case let .identifier(rootObjectID) = topLevelDict["rootObject"]! else { XCTFail("top-level plist dictionary must have a `rootObject` string") return } XCTAssertFalse(rootObjectID.isEmpty) // There should be a dictionary mapping identifiers to object dictionaries. guard case let .dictionary(objectDict) = topLevelDict["objects"]! else { XCTFail("top-level plist dictionary must have a `objects` dictionary") return } XCTAssertFalse(objectDict.isEmpty) // The root object should reference a PBXProject dictionary. guard case let .dictionary(projectDict) = objectDict[rootObjectID]! else { XCTFail("object dictionary must have an entry for the project") return } XCTAssertFalse(projectDict.isEmpty) // Project dictionary's `isa` must be "PBXProject". guard case let .string(projectClassName) = projectDict["isa"]! else { XCTFail("project object dictionary must have an `isa` string") return } XCTAssertEqual(projectClassName, "PBXProject") } func testBuildSettingsSerialization() { // Create build settings. var buildSettings = Xcode.BuildSettingsTable.BuildSettings() let productNameValue = "$(TARGET_NAME:c99extidentifier)" buildSettings.PRODUCT_NAME = productNameValue let otherSwiftFlagValues = ["$(inherited)", "-DXcode"] buildSettings.OTHER_SWIFT_FLAGS = otherSwiftFlagValues // Serialize it to a property list. let plist = buildSettings.asPropertyList() // Assert things about plist guard case let .dictionary(buildSettingsDict) = plist else { XCTFail("build settings plist must be a dictionary") return } guard let productNamePlist = buildSettingsDict["PRODUCT_NAME"], let otherSwiftFlagsPlist = buildSettingsDict["OTHER_SWIFT_FLAGS"] else { XCTFail("build settings plist must contain PRODUCT_NAME and OTHER_SWIFT_FLAGS") return } guard case let .string(productName) = productNamePlist else { XCTFail("productName plist must be a string") return } XCTAssertEqual(productName, productNameValue) guard case let .array(otherSwiftFlagsPlists) = otherSwiftFlagsPlist else { XCTFail("otherSwiftFlags plist must be an array") return } let otherSwiftFlags = otherSwiftFlagsPlists.flatMap { flagPlist -> String? in guard case let .string(flag) = flagPlist else { XCTFail("otherSwiftFlag plist must be string") return nil } return flag } XCTAssertEqual(otherSwiftFlags, otherSwiftFlagValues) } static var allTests = [ ("testBasicProjectSerialization", testBasicProjectSerialization), ("testBuildSettingsSerialization", testBuildSettingsSerialization), ] }
0d97b55a0c743fdcc62316311106d050
36.458015
91
0.629916
false
true
false
false
questbeat/PageMenu
refs/heads/master
PageMenuDemo/PageViewDemoViewController.swift
mit
1
// // PageViewDemoViewController.swift // PageMenu // // Created by Katsuma Tanaka on 2015/10/08. // Copyright © 2015 Katsuma Tanaka. All rights reserved. // import UIKit import PageMenu class PageViewDemoViewController: UIViewController, PageViewControllerDataSource, PageViewControllerDelegate { // MARK: - Properties let viewControllerIdentifiers = [ "FirstViewController", "SecondViewController", "ThirdViewController" ] var contentViewController: PageViewController? { willSet { if let contentViewController = self.contentViewController { contentViewController.willMoveToParentViewController(nil) contentViewController.view.removeFromSuperview() contentViewController.removeFromParentViewController() } } didSet { if let contentViewController = self.contentViewController { addChildViewController(contentViewController) let view = contentViewController.view view.frame = self.view.bounds view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.view.addSubview(view) contentViewController.didMoveToParentViewController(self) } } } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() let pageViewController = PageViewController.pageViewController()! pageViewController.dataSource = self pageViewController.delegate = self self.contentViewController = pageViewController } // MARK: - PageControllerDataSource func numberOfPagesInPageViewController(pageViewController: PageViewController) -> Int { return viewControllerIdentifiers.count } func pageViewController(pageViewController: PageViewController, viewControllerForPageAtIndex index: Int) -> UIViewController { return storyboard!.instantiateViewControllerWithIdentifier(viewControllerIdentifiers[index]) } // MARK: - PageControllerDelegate func pageViewController(pageViewController: PageViewController, didMoveToPageAtIndex index: Int) { NSLog("*** pageViewController:didMoveToPageAtIndex:") } func pageViewController(pageViewController: PageViewController, willLoadViewControllerForPageAtIndex index: Int) { NSLog("*** pageViewController:willLoadViewControllerForPageAtIndex:") } func pageViewController(pageViewController: PageViewController, didLoadViewControllerForPageAtIndex index: Int) { NSLog("*** pageViewController:didLoadViewControllerForPageAtIndex:") } func pageViewController(pageViewController: PageViewController, willUnloadViewControllerForPageAtIndex index: Int) { NSLog("*** pageViewController:willUnloadViewControllerForPageAtIndex:") } func pageViewController(pageViewController: PageViewController, didUnloadViewControllerForPageAtIndex index: Int) { NSLog("*** pageViewController:didUnloadViewControllerForPageAtIndex:") } func pageViewControllerDidScroll(pageViewController: PageViewController) { } }
e36338e8bf8300f41ab13fb2822bc9e1
33.978947
130
0.689136
false
false
false
false
Ansem717/MotivationalModel
refs/heads/master
MotivationalModel/MotivationalModel/NavigationStack.swift
mit
1
// // StackedRoomDataStructure.swift // MotivationalModel // // Created by Andy Malik on 2/26/16. // Copyright © 2016 VanguardStrategiesInc. All rights reserved. // import Foundation class NavigationStack { static let shared = NavigationStack() private init() {} let head = NavigationStackRoom() func isEmpty() -> Bool { return head.key == nil } func printContents() { var current: NavigationStackRoom? = head print("--START NAV HIERARCHY--") while current != nil { print("\(current!.key!)") current = current!.next } print("--END NAV HIERARCHY--\n") } func addRoomToNavigationStack(key: String) { if self.isEmpty() { head.key = key return } var current: NavigationStackRoom? = head if key == findCurrentRoomInNavStack() { return } while current != nil { if current?.next == nil { let newRoom = NavigationStackRoom() newRoom.prev = current newRoom.key = key current!.next = newRoom break } else { current = current?.next } } } func removeLastFromNavigationStack() { if self.isEmpty() { return } var current: NavigationStackRoom? = head while current != nil { if current?.next == nil { let parent = current?.prev current!.key = nil current!.prev = nil parent!.next = nil break } else { current = current?.next } } } func findCurrentRoomInNavStack() -> String { if self.isEmpty() { return kHome } var current: NavigationStackRoom? = head while current != nil{ if current?.next == nil { guard let currentKey = current?.key else { fatalError("7") } return currentKey } else { current = current?.next } } print("\n\nERROR - Nav Stack - Current is nil - \(__FUNCTION__)\n\n\n"); return kHome } func findPreviousRoomInNavStack() -> String { if self.isEmpty() { return kHome } var current: NavigationStackRoom? = head while current != nil{ if current?.next == nil { guard let prevKey = current?.prev?.key else { fatalError("8") } return prevKey } else { current = current?.next } } print("\n\nERROR - Nav Stack - Current is nil - \(__FUNCTION__)\n\n\n") return kHome } func count() -> Int { if self.isEmpty() { return 0 } var current: NavigationStackRoom? = head var index: Int = 0 while current != nil { index++ current = current!.next } return index } }
2cc825431893b38ca86325ef3cbff120
22.007042
80
0.46281
false
false
false
false
Flixpicks/Flixpicks
refs/heads/master
Sources/App/Models/Movie.swift
mit
1
// // Movie.swift // flixpicks // // Created by Logan Heitz on 7/5/17. // // import Vapor import FluentProvider import HTTP final class Movie: Model { let storage = Storage() /// The content of the Movie var title: String var description: String var release_date: Date var age_rating: Int var genre: Int /// Creates a new Movie init(title: String, description: String, release_date: Date, age_rating: Int, genre: Int) { self.title = title self.description = description self.release_date = release_date self.age_rating = age_rating self.genre = genre } // MARK: Fluent Serialization /// Initializes the Movie from the /// database row init(row: Row) throws { title = try row.get("title") description = try row.get("description") release_date = try row.get("release_date") age_rating = try row.get("age_rating") genre = try row.get("genre") } // Serializes the Movie to the database func makeRow() throws -> Row { var row = Row() try row.set("title", title) try row.set("description", description) try row.set("release_date", release_date) try row.set("age_rating", age_rating) try row.set("genre", genre) return row } } // MARK: Preparation extension Movie: Preparation { /// Prepares a table/collection in the database /// for storing Movies static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string("title") builder.string("description", length: 1000) builder.date("release_date") builder.int("age_rating") builder.int("genre") } } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSONConvertible extension Movie: JSONConvertible { convenience init(json: JSON) throws { try self.init( title: json.get("title"), description: json.get("description"), release_date: json.get("release_date"), age_rating: json.get("age_rating"), genre: json.get("genre") ) } func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) try json.set("title", title) try json.set("description", description) try json.set("release_date", release_date) try json.set("age_rating", age_rating) try json.set("genre", genre) return json } } // MARK: HTTP extension Movie: ResponseRepresentable { } // MARK: Request extension Request { func jsonMovie() throws -> Movie { return try Movie(json: json!) } }
d512a60980188bfcc112bf33113868f5
25.12844
95
0.589185
false
false
false
false
1457792186/JWSwift
refs/heads/master
AlamofireSwift/Pods/Kingfisher/Sources/Image.swift
apache-2.0
25
// // Image.swift // Kingfisher // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2016 Wei Wang <[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. #if os(macOS) import AppKit private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices private var imageSourceKey: Void? private var animatedImageDataKey: Void? #endif import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: - Image Properties extension Kingfisher where Base: Image { #if os(macOS) var cgImage: CGImage? { return base.cgImage(forProposedRect: nil, context: nil, hints: nil) } var scale: CGFloat { return 1.0 } fileprivate(set) var images: [Image]? { get { return objc_getAssociatedObject(base, &imagesKey) as? [Image] } set { objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var duration: TimeInterval { get { return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var cgImage: CGImage? { return base.cgImage } var scale: CGFloat { return base.scale } var images: [Image]? { return base.images } var duration: TimeInterval { return base.duration } fileprivate(set) var imageSource: ImageSource? { get { return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var animatedImageData: Data? { get { return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.size } #endif } // MARK: - Image Conversion extension Kingfisher where Base: Image { #if os(macOS) static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public var normalized: Image { return base } static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale. */ public var normalized: Image { // prevent animated image (GIF) lose it's images guard images == nil else { return base } // No need to do anything if already up guard base.imageOrientation != .up else { return base } return draw(cgImage: nil, to: size) { base.draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: - Image Representation extension Kingfisher where Base: Image { // MARK: - PNG func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(base) #endif } // MARK: - JPEG func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(base, compressionQuality) #endif } // MARK: - GIF func gifRepresentation() -> Data? { #if os(macOS) return gifRepresentation(duration: 0.0, repeatCount: 0) #else return animatedImageData #endif } #if os(macOS) func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? { guard let images = images else { return nil } let frameCount = images.count let gifDuration = duration <= 0.0 ? duration / Double(frameCount) : duration / Double(frameCount) let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]] let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else { return nil } CGImageDestinationSetProperties(destination, imageProperties as CFDictionary) for image in images { CGImageDestinationAddImage(destination, image.kf.cgImage!, frameProperties as CFDictionary) } return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil } #endif } // MARK: - Create images from data extension Kingfisher where Base: Image { static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image? { func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary) -> Double { let gifDefaultFrameDuration = 0.100 let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else { return nil } gifDuration += frameDuration(from: gifInfo) } images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil)) } return (images, gifDuration) } // Start of kf.animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Image(data: data) image?.kf.images = images image?.kf.duration = gifDuration return image #else if preloadAll { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) image?.kf.animatedImageData = data return image } else { let image = Image(data: data) image?.kf.animatedImageData = data image?.kf.imageSource = ImageSource(ref: imageSource) return image } #endif } static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf.imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = Kingfisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data) } #else switch data.kf.imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = Kingfisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // MARK: - Image Transforming extension Kingfisher where Base: Image { // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Round corder image only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) path.windingRule = .evenOddWindingRule path.addClip() base.draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath context.addPath(path) context.clip() base.draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { switch contentMode { case .scaleAspectFit: let newSize = self.size.kf.constrained(size) return resize(to: newSize) case .scaleAspectFill: let newSize = self.size.kf.filling(size) return resize(to: newSize) default: return resize(to: size) } } #endif // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. public func resize(to size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) #else base.draw(in: rect) #endif } } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. public func blurred(withRadius radius: CGFloat) -> Image { #if os(watchOS) return base #else guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return base } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = max(radius, 2.0) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. var targetRadius = floor((Double(s * 3.0) * sqrt(2 * M_PI) / 4.0 + 0.5)) if targetRadius.isEven { targetRadius += 1 } let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(size.width) let h = Int(size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) let inDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h)) inDataPointer.initialize(to: 0) defer { inDataPointer.deinitialize() inDataPointer.deallocate(capacity: rowBytes * Int(h)) } let bitmapInfo = cgImage.bitmapInfo.fixed guard let context = CGContext(data: inDataPointer, width: w, height: h, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: rowBytes, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) let outDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h)) outDataPointer.initialize(to: 0) defer { outDataPointer.deinitialize() outDataPointer.deallocate(capacity: rowBytes * Int(h)) } var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) for _ in 0 ..< iterations { vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) (inBuffer, outBuffer) = (outBuffer, inBuffer) } guard let outContext = CGContext(data: inDataPointer, width: w, height: h, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: rowBytes, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } #if os(macOS) let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return base } return blurredImage #endif } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. public func overlaying(with color: Color, fraction: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return base } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) return draw(cgImage: cgImage, to: rect.size) { #if os(macOS) base.draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() NSRectFillUsingOperation(rect, .sourceAtop) } #else color.set() UIRectFill(rect) base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. public func tinted(with color: Color) -> Image { #if os(watchOS) return base #else return apply(.tint(color)) #endif } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return base #else return apply(.colorControl(brightness, contrast, saturation, inputEV)) #endif } } // MARK: - Decode extension Kingfisher where Base: Image { var decoded: Image? { return decoded(scale: scale) } func decoded(scale: CGFloat) -> Image { // prevent animated image (GIF) lose it's images #if os(iOS) if imageSource != nil { return base } #else if images != nil { return base } #endif guard let imageRef = self.cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return base } let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = imageRef.bitmapInfo.fixed guard let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Decoding fails to create a valid context.") return base } let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) context.draw(imageRef, in: rect) let decompressedImageRef = context.makeImage() return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base) } } /// Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers public struct DataProxy { fileprivate let base: Data init(proxy: Data) { base = proxy } } extension Data: KingfisherCompatible { public typealias CompatibleType = DataProxy public var kf: DataProxy { return DataProxy(proxy: self) } } extension DataProxy { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (base as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } } public struct CGSizeProxy { fileprivate let base: CGSize init(proxy: CGSize) { base = proxy } } extension CGSize: KingfisherCompatible { public typealias CompatibleType = CGSizeProxy public var kf: CGSizeProxy { return CGSizeProxy(proxy: self) } } extension CGSizeProxy { func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension CGBitmapInfo { var fixed: CGBitmapInfo { var fixed = self let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if alpha == CGImageAlphaInfo.none.rawValue { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) } return fixed } } extension Kingfisher where Base: Image { func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return base } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? base #endif } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: self.size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension CGContext { static func createARGBContext(from imageRef: CGImage) -> CGContext? { let w = imageRef.width let h = imageRef.height let bytesPerRow = w * 4 let colorSpace = CGColorSpaceCreateDeviceRGB() let data = malloc(bytesPerRow * h) defer { free(data) } let bitmapInfo = imageRef.bitmapInfo.fixed // Create the bitmap context. We want pre-multiplied ARGB, 8-bits // per component. Regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here. return CGContext(data: data, width: w, height: h, bitsPerComponent: imageRef.bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) } } extension Double { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } } // MARK: - Deprecated. Only for back compatibility. extension Image { /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.", renamed: "kf.normalized") public func kf_normalized() -> Image { return kf.normalized } // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// - parameter scale: The image scale of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.", renamed: "kf.image") public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return kf.image(withRoundRadius: radius, fit: size) } // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.", renamed: "kf.resize") public func kf_resize(to size: CGSize) -> Image { return kf.resize(to: size) } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.", renamed: "kf.blurred") public func kf_blurred(withRadius radius: CGFloat) -> Image { return kf.blurred(withRadius: radius) } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.", renamed: "kf.overlaying") public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { return kf.overlaying(with: color, fraction: fraction) } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.", renamed: "kf.tinted") public func kf_tinted(with color: Color) -> Image { return kf.tinted(with: color) } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.", renamed: "kf.adjusted") public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) } } extension Kingfisher where Base: Image { @available(*, deprecated, message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)") public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return image(withRoundRadius: radius, fit: size) } }
99a5b6ab4693c6d402b3f30d67ab3b77
34.989429
192
0.584121
false
false
false
false
dcunited001/Spectra
refs/heads/master
Pod/Classes/RenderStrategy.swift
mit
1
// // RenderStrategy.swift // Pods // // Created by David Conner on 10/7/15. // // import Foundation public protocol RenderStrategy: class { var renderStages: [RenderStage] { get set } func execRenderStage(commandBuffer: MTLCommandBuffer, renderPassDescriptor: MTLRenderPassDescriptor, renderEncoder: MTLRenderCommandEncoder, renderStage: RenderStage, renderer: Renderer, nextRenderer: Renderer?) } extension RenderStrategy { public func execRenderStage(commandBuffer: MTLCommandBuffer, renderPassDescriptor: MTLRenderPassDescriptor, renderEncoder: MTLRenderCommandEncoder, renderStage: RenderStage, renderer: Renderer, nextRenderer: Renderer?) { var nextRenderEncoder: MTLRenderCommandEncoder? if let renderEncoderTransition = renderStage.transition(renderer, nextRenderer: nextRenderer) { nextRenderEncoder = renderEncoderTransition(renderEncoder) } else { nextRenderEncoder = (renderer.defaultRenderEncoderTransition())(commandBuffer, renderPassDescriptor) } } } public class BaseRenderStrategy: RenderStrategy { public var currentRenderStage: Int = 0 public var renderStages: [RenderStage] = [] }
ca4c95ac7130f5765b44bcb983e29563
37.612903
224
0.756057
false
false
false
false
envoy/Ambassador
refs/heads/master
AmbassadorTests/URLParametersReaderTests.swift
mit
1
// // URLParametersReaderTests.swift // Ambassador // // Created by Fang-Pen Lin on 6/10/16. // Copyright © 2016 Fang-Pen Lin. All rights reserved. // import XCTest import Ambassador class URLParametersReaderTests: XCTestCase { func testParseURLParameter() { let params1 = URLParametersReader.parseURLParameters("foo=bar&eggs=spam") XCTAssertEqual(params1.count, 2) XCTAssertEqual(params1.first?.0, "foo") XCTAssertEqual(params1.first?.1, "bar") XCTAssertEqual(params1.last?.0, "eggs") XCTAssertEqual(params1.last?.1, "spam") let params2 = URLParametersReader.parseURLParameters("foo%5Bbar%5D=eggs%20spam") XCTAssertEqual(params2.count, 1) XCTAssertEqual(params2.first?.0, "foo[bar]") XCTAssertEqual(params2.first?.1, "eggs spam") } func testURLParameterReader() { let input = { (handler: ((Data) -> Void)?) in handler!(Data("foo".utf8)) handler!(Data("=".utf8)) handler!(Data("bar".utf8)) handler!(Data("&eggs=spam".utf8)) handler!(Data()) } var receivedParams: [(String, String)]! URLParametersReader.read(input) { params in receivedParams = params } XCTAssertEqual(receivedParams.count, 2) XCTAssertEqual(receivedParams.first?.0, "foo") XCTAssertEqual(receivedParams.first?.1, "bar") XCTAssertEqual(receivedParams.last?.0, "eggs") XCTAssertEqual(receivedParams.last?.1, "spam") } }
10a44c44fcedd4e544a7bda04a15d7f4
32.521739
88
0.629053
false
true
false
false
mattrubin/SwiftGit2
refs/heads/develop
SwiftGit2Tests/RepositorySpec.swift
mit
1
// // RepositorySpec.swift // RepositorySpec // // Created by Matt Diephouse on 11/7/14. // Copyright (c) 2014 GitHub, Inc. All rights reserved. // import SwiftGit2 import Nimble import Quick // swiftlint:disable cyclomatic_complexity class RepositorySpec: QuickSpec { override func spec() { describe("Repository.Type.at(_:)") { it("should work if the repo exists") { let repo = Fixtures.simpleRepository expect(repo.directoryURL).notTo(beNil()) } it("should fail if the repo doesn't exist") { let url = URL(fileURLWithPath: "blah") let result = Repository.at(url) expect(result.error?.domain) == libGit2ErrorDomain expect(result.error?.localizedDescription).to(match("failed to resolve path")) } } describe("Repository.Type.isValid(url:)") { it("should return true if the repo exists") { guard let repositoryURL = Fixtures.simpleRepository.directoryURL else { fail("Fixture setup broken: Repository does not exist"); return } let result = Repository.isValid(url: repositoryURL) expect(result.error).to(beNil()) if case .success(let isValid) = result { expect(isValid).to(beTruthy()) } } it("should return false if the directory does not contain a repo") { let tmpURL = URL(fileURLWithPath: "/dev/null") let result = Repository.isValid(url: tmpURL) expect(result.error).to(beNil()) if case .success(let isValid) = result { expect(isValid).to(beFalsy()) } } it("should return error if .git is not readable") { let localURL = self.temporaryURL(forPurpose: "git-isValid-unreadable").appendingPathComponent(".git") let nonReadablePermissions: [FileAttributeKey: Any] = [.posixPermissions: 0o077] try! FileManager.default.createDirectory( at: localURL, withIntermediateDirectories: true, attributes: nonReadablePermissions) let result = Repository.isValid(url: localURL) expect(result.value).to(beNil()) expect(result.error).notTo(beNil()) } } describe("Repository.Type.create(at:)") { it("should create a new repo at the specified location") { let localURL = self.temporaryURL(forPurpose: "local-create") let result = Repository.create(at: localURL) expect(result.error).to(beNil()) if case .success(let clonedRepo) = result { expect(clonedRepo.directoryURL).notTo(beNil()) } } } describe("Repository.Type.clone(from:to:)") { it("should handle local clones") { let remoteRepo = Fixtures.simpleRepository let localURL = self.temporaryURL(forPurpose: "local-clone") let result = Repository.clone(from: remoteRepo.directoryURL!, to: localURL, localClone: true) expect(result.error).to(beNil()) if case .success(let clonedRepo) = result { expect(clonedRepo.directoryURL).notTo(beNil()) } } it("should handle bare clones") { let remoteRepo = Fixtures.simpleRepository let localURL = self.temporaryURL(forPurpose: "bare-clone") let result = Repository.clone(from: remoteRepo.directoryURL!, to: localURL, localClone: true, bare: true) expect(result.error).to(beNil()) if case .success(let clonedRepo) = result { expect(clonedRepo.directoryURL).to(beNil()) } } it("should have set a valid remote url") { let remoteRepo = Fixtures.simpleRepository let localURL = self.temporaryURL(forPurpose: "valid-remote-clone") let cloneResult = Repository.clone(from: remoteRepo.directoryURL!, to: localURL, localClone: true) expect(cloneResult.error).to(beNil()) if case .success(let clonedRepo) = cloneResult { let remoteResult = clonedRepo.remote(named: "origin") expect(remoteResult.error).to(beNil()) if case .success(let remote) = remoteResult { expect(remote.URL).to(equal(remoteRepo.directoryURL?.absoluteString)) } } } it("should be able to clone a remote repository") { let remoteRepoURL = URL(string: "https://github.com/libgit2/libgit2.github.com.git") let localURL = self.temporaryURL(forPurpose: "public-remote-clone") let cloneResult = Repository.clone(from: remoteRepoURL!, to: localURL) expect(cloneResult.error).to(beNil()) if case .success(let clonedRepo) = cloneResult { let remoteResult = clonedRepo.remote(named: "origin") expect(remoteResult.error).to(beNil()) if case .success(let remote) = remoteResult { expect(remote.URL).to(equal(remoteRepoURL?.absoluteString)) } } } let env = ProcessInfo.processInfo.environment if let privateRepo = env["SG2TestPrivateRepo"], let gitUsername = env["SG2TestUsername"], let publicKey = env["SG2TestPublicKey"], let privateKey = env["SG2TestPrivateKey"], let passphrase = env["SG2TestPassphrase"] { it("should be able to clone a remote repository requiring credentials") { let remoteRepoURL = URL(string: privateRepo) let localURL = self.temporaryURL(forPurpose: "private-remote-clone") let credentials = Credentials.sshMemory(username: gitUsername, publicKey: publicKey, privateKey: privateKey, passphrase: passphrase) let cloneResult = Repository.clone(from: remoteRepoURL!, to: localURL, credentials: credentials) expect(cloneResult.error).to(beNil()) if case .success(let clonedRepo) = cloneResult { let remoteResult = clonedRepo.remote(named: "origin") expect(remoteResult.error).to(beNil()) if case .success(let remote) = remoteResult { expect(remote.URL).to(equal(remoteRepoURL?.absoluteString)) } } } } } describe("Repository.blob(_:)") { it("should return the commit if it exists") { let repo = Fixtures.simpleRepository let oid = OID(string: "41078396f5187daed5f673e4a13b185bbad71fba")! let result = repo.blob(oid) expect(result.map { $0.oid }.value) == oid } it("should error if the blob doesn't exist") { let repo = Fixtures.simpleRepository let oid = OID(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")! let result = repo.blob(oid) expect(result.error?.domain) == libGit2ErrorDomain } it("should error if the oid doesn't point to a blob") { let repo = Fixtures.simpleRepository // This is a tree in the repository let oid = OID(string: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc")! let result = repo.blob(oid) expect(result.error).notTo(beNil()) } } describe("Repository.commit(_:)") { it("should return the commit if it exists") { let repo = Fixtures.simpleRepository let oid = OID(string: "dc220a3f0c22920dab86d4a8d3a3cb7e69d6205a")! let result = repo.commit(oid) expect(result.map { $0.oid }.value) == oid } it("should error if the commit doesn't exist") { let repo = Fixtures.simpleRepository let oid = OID(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")! let result = repo.commit(oid) expect(result.error?.domain) == libGit2ErrorDomain } it("should error if the oid doesn't point to a commit") { let repo = Fixtures.simpleRepository // This is a tree in the repository let oid = OID(string: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc")! let result = repo.commit(oid) expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.tag(_:)") { it("should return the tag if it exists") { let repo = Fixtures.simpleRepository let oid = OID(string: "57943b8ee00348180ceeedc960451562750f6d33")! let result = repo.tag(oid) expect(result.map { $0.oid }.value) == oid } it("should error if the tag doesn't exist") { let repo = Fixtures.simpleRepository let oid = OID(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")! let result = repo.tag(oid) expect(result.error?.domain) == libGit2ErrorDomain } it("should error if the oid doesn't point to a tag") { let repo = Fixtures.simpleRepository // This is a commit in the repository let oid = OID(string: "dc220a3f0c22920dab86d4a8d3a3cb7e69d6205a")! let result = repo.tag(oid) expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.tree(_:)") { it("should return the tree if it exists") { let repo = Fixtures.simpleRepository let oid = OID(string: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc")! let result = repo.tree(oid) expect(result.map { $0.oid }.value) == oid } it("should error if the tree doesn't exist") { let repo = Fixtures.simpleRepository let oid = OID(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")! let result = repo.tree(oid) expect(result.error?.domain) == libGit2ErrorDomain } it("should error if the oid doesn't point to a tree") { let repo = Fixtures.simpleRepository // This is a commit in the repository let oid = OID(string: "dc220a3f0c22920dab86d4a8d3a3cb7e69d6205a")! let result = repo.tree(oid) expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.object(_:)") { it("should work with a blob") { let repo = Fixtures.simpleRepository let oid = OID(string: "41078396f5187daed5f673e4a13b185bbad71fba")! let blob = repo.blob(oid).value let result = repo.object(oid) expect(result.map { $0 as! Blob }.value) == blob } it("should work with a commit") { let repo = Fixtures.simpleRepository let oid = OID(string: "dc220a3f0c22920dab86d4a8d3a3cb7e69d6205a")! let commit = repo.commit(oid).value let result = repo.object(oid) expect(result.map { $0 as! Commit }.value) == commit } it("should work with a tag") { let repo = Fixtures.simpleRepository let oid = OID(string: "57943b8ee00348180ceeedc960451562750f6d33")! let tag = repo.tag(oid).value let result = repo.object(oid) expect(result.map { $0 as! Tag }.value) == tag } it("should work with a tree") { let repo = Fixtures.simpleRepository let oid = OID(string: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc")! let tree = repo.tree(oid).value let result = repo.object(oid) expect(result.map { $0 as! Tree }.value) == tree } it("should error if there's no object with that oid") { let repo = Fixtures.simpleRepository let oid = OID(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")! let result = repo.object(oid) expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.object(from: PointerTo)") { it("should work with commits") { let repo = Fixtures.simpleRepository let oid = OID(string: "dc220a3f0c22920dab86d4a8d3a3cb7e69d6205a")! let pointer = PointerTo<Commit>(oid) let commit = repo.commit(oid).value! expect(repo.object(from: pointer).value) == commit } it("should work with trees") { let repo = Fixtures.simpleRepository let oid = OID(string: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc")! let pointer = PointerTo<Tree>(oid) let tree = repo.tree(oid).value! expect(repo.object(from: pointer).value) == tree } it("should work with blobs") { let repo = Fixtures.simpleRepository let oid = OID(string: "41078396f5187daed5f673e4a13b185bbad71fba")! let pointer = PointerTo<Blob>(oid) let blob = repo.blob(oid).value! expect(repo.object(from: pointer).value) == blob } it("should work with tags") { let repo = Fixtures.simpleRepository let oid = OID(string: "57943b8ee00348180ceeedc960451562750f6d33")! let pointer = PointerTo<Tag>(oid) let tag = repo.tag(oid).value! expect(repo.object(from: pointer).value) == tag } } describe("Repository.object(from: Pointer)") { it("should work with commits") { let repo = Fixtures.simpleRepository let oid = OID(string: "dc220a3f0c22920dab86d4a8d3a3cb7e69d6205a")! let pointer = Pointer.commit(oid) let commit = repo.commit(oid).value! let result = repo.object(from: pointer).map { $0 as! Commit } expect(result.value) == commit } it("should work with trees") { let repo = Fixtures.simpleRepository let oid = OID(string: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc")! let pointer = Pointer.tree(oid) let tree = repo.tree(oid).value! let result = repo.object(from: pointer).map { $0 as! Tree } expect(result.value) == tree } it("should work with blobs") { let repo = Fixtures.simpleRepository let oid = OID(string: "41078396f5187daed5f673e4a13b185bbad71fba")! let pointer = Pointer.blob(oid) let blob = repo.blob(oid).value! let result = repo.object(from: pointer).map { $0 as! Blob } expect(result.value) == blob } it("should work with tags") { let repo = Fixtures.simpleRepository let oid = OID(string: "57943b8ee00348180ceeedc960451562750f6d33")! let pointer = Pointer.tag(oid) let tag = repo.tag(oid).value! let result = repo.object(from: pointer).map { $0 as! Tag } expect(result.value) == tag } } describe("Repository.allRemotes()") { it("should return an empty list if there are no remotes") { let repo = Fixtures.simpleRepository let result = repo.allRemotes() expect(result.value) == [] } it("should return all the remotes") { let repo = Fixtures.mantleRepository let remotes = repo.allRemotes() let names = remotes.map { $0.map { $0.name } } expect(remotes.map { $0.count }.value) == 2 expect(names.value).to(contain("origin", "upstream")) } } describe("Repository.remote(named:)") { it("should return the remote if it exists") { let repo = Fixtures.mantleRepository let result = repo.remote(named: "upstream") expect(result.map { $0.name }.value) == "upstream" } it("should error if the remote doesn't exist") { let repo = Fixtures.simpleRepository let result = repo.remote(named: "nonexistent") expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.reference(named:)") { it("should return a local branch if it exists") { let name = "refs/heads/master" let result = Fixtures.simpleRepository.reference(named: name) expect(result.map { $0.longName }.value) == name expect(result.value as? Branch).notTo(beNil()) } it("should return a remote branch if it exists") { let name = "refs/remotes/upstream/master" let result = Fixtures.mantleRepository.reference(named: name) expect(result.map { $0.longName }.value) == name expect(result.value as? Branch).notTo(beNil()) } it("should return a tag if it exists") { let name = "refs/tags/tag-2" let result = Fixtures.simpleRepository.reference(named: name) expect(result.value?.longName).to(equal(name)) expect(result.value as? TagReference).notTo(beNil()) } it("should return the reference if it exists") { let name = "refs/other-ref" let result = Fixtures.simpleRepository.reference(named: name) expect(result.value?.longName).to(equal(name)) } it("should error if the reference doesn't exist") { let result = Fixtures.simpleRepository.reference(named: "refs/heads/nonexistent") expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.localBranches()") { it("should return all the local branches") { let repo = Fixtures.simpleRepository let expected = [ repo.localBranch(named: "another-branch").value!, repo.localBranch(named: "master").value!, repo.localBranch(named: "yet-another-branch").value!, ] expect(repo.localBranches().value).to(equal(expected)) } } describe("Repository.remoteBranches()") { it("should return all the remote branches") { let repo = Fixtures.mantleRepository let expectedNames = [ "origin/2.0-development", "origin/HEAD", "origin/bump-config", "origin/bump-xcconfigs", "origin/github-reversible-transformer", "origin/master", "origin/mtlmanagedobject", "origin/reversible-transformer", "origin/subclassing-notes", "upstream/2.0-development", "upstream/bump-config", "upstream/bump-xcconfigs", "upstream/github-reversible-transformer", "upstream/master", "upstream/mtlmanagedobject", "upstream/reversible-transformer", "upstream/subclassing-notes", ] let expected = expectedNames.map { repo.remoteBranch(named: $0).value! } let actual = repo.remoteBranches().value!.sorted { return $0.longName.lexicographicallyPrecedes($1.longName) } expect(actual).to(equal(expected)) expect(actual.map { $0.name }).to(equal(expectedNames)) } } describe("Repository.localBranch(named:)") { it("should return the branch if it exists") { let result = Fixtures.simpleRepository.localBranch(named: "master") expect(result.value?.longName).to(equal("refs/heads/master")) } it("should error if the branch doesn't exists") { let result = Fixtures.simpleRepository.localBranch(named: "nonexistent") expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.remoteBranch(named:)") { it("should return the branch if it exists") { let result = Fixtures.mantleRepository.remoteBranch(named: "upstream/master") expect(result.value?.longName).to(equal("refs/remotes/upstream/master")) } it("should error if the branch doesn't exists") { let result = Fixtures.simpleRepository.remoteBranch(named: "origin/nonexistent") expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.fetch(_:)") { it("should fetch the data") { let repo = Fixtures.mantleRepository let remote = repo.remote(named: "origin").value! expect(repo.fetch(remote).value).toNot(beNil()) } } describe("Repository.allTags()") { it("should return all the tags") { let repo = Fixtures.simpleRepository let expected = [ repo.tag(named: "tag-1").value!, repo.tag(named: "tag-2").value!, ] expect(repo.allTags().value).to(equal(expected)) } } describe("Repository.tag(named:)") { it("should return the tag if it exists") { let result = Fixtures.simpleRepository.tag(named: "tag-2") expect(result.value?.longName).to(equal("refs/tags/tag-2")) } it("should error if the branch doesn't exists") { let result = Fixtures.simpleRepository.tag(named: "nonexistent") expect(result.error?.domain) == libGit2ErrorDomain } } describe("Repository.HEAD()") { it("should work when on a branch") { let result = Fixtures.simpleRepository.HEAD() expect(result.value?.longName).to(equal("refs/heads/master")) expect(result.value?.shortName).to(equal("master")) expect(result.value as? Branch).notTo(beNil()) } it("should work when on a detached HEAD") { let result = Fixtures.detachedHeadRepository.HEAD() expect(result.value?.longName).to(equal("HEAD")) expect(result.value?.shortName).to(beNil()) expect(result.value?.oid).to(equal(OID(string: "315b3f344221db91ddc54b269f3c9af422da0f2e")!)) expect(result.value as? Reference).notTo(beNil()) } } describe("Repository.setHEAD(OID)") { it("should set HEAD to the OID") { let repo = Fixtures.simpleRepository let oid = OID(string: "315b3f344221db91ddc54b269f3c9af422da0f2e")! expect(repo.HEAD().value?.shortName).to(equal("master")) expect(repo.setHEAD(oid).error).to(beNil()) let HEAD = repo.HEAD().value expect(HEAD?.longName).to(equal("HEAD")) expect(HEAD?.oid).to(equal(oid)) expect(repo.setHEAD(repo.localBranch(named: "master").value!).error).to(beNil()) expect(repo.HEAD().value?.shortName).to(equal("master")) } } describe("Repository.setHEAD(ReferenceType)") { it("should set HEAD to a branch") { let repo = Fixtures.detachedHeadRepository let oid = repo.HEAD().value!.oid expect(repo.HEAD().value?.longName).to(equal("HEAD")) let branch = repo.localBranch(named: "another-branch").value! expect(repo.setHEAD(branch).error).to(beNil()) expect(repo.HEAD().value?.shortName).to(equal(branch.name)) expect(repo.setHEAD(oid).error).to(beNil()) expect(repo.HEAD().value?.longName).to(equal("HEAD")) } } describe("Repository.checkout()") { // We're not really equipped to test this yet. :( } describe("Repository.checkout(OID)") { it("should set HEAD") { let repo = Fixtures.simpleRepository let oid = OID(string: "315b3f344221db91ddc54b269f3c9af422da0f2e")! expect(repo.HEAD().value?.shortName).to(equal("master")) expect(repo.checkout(oid, strategy: CheckoutStrategy.None).error).to(beNil()) let HEAD = repo.HEAD().value expect(HEAD?.longName).to(equal("HEAD")) expect(HEAD?.oid).to(equal(oid)) expect(repo.checkout(repo.localBranch(named: "master").value!, strategy: CheckoutStrategy.None).error).to(beNil()) expect(repo.HEAD().value?.shortName).to(equal("master")) } it("should call block on progress") { let repo = Fixtures.simpleRepository let oid = OID(string: "315b3f344221db91ddc54b269f3c9af422da0f2e")! expect(repo.HEAD().value?.shortName).to(equal("master")) expect(repo.checkout(oid, strategy: .None, progress: { (_, completedSteps, totalSteps) -> Void in expect(completedSteps).to(beLessThanOrEqualTo(totalSteps)) }).error).to(beNil()) let HEAD = repo.HEAD().value expect(HEAD?.longName).to(equal("HEAD")) expect(HEAD?.oid).to(equal(oid)) } } describe("Repository.checkout(ReferenceType)") { it("should set HEAD") { let repo = Fixtures.detachedHeadRepository let oid = repo.HEAD().value!.oid expect(repo.HEAD().value?.longName).to(equal("HEAD")) let branch = repo.localBranch(named: "another-branch").value! expect(repo.checkout(branch, strategy: CheckoutStrategy.None).error).to(beNil()) expect(repo.HEAD().value?.shortName).to(equal(branch.name)) expect(repo.checkout(oid, strategy: CheckoutStrategy.None).error).to(beNil()) expect(repo.HEAD().value?.longName).to(equal("HEAD")) } } describe("Repository.allCommits(in:)") { it("should return all (9) commits") { let repo = Fixtures.simpleRepository let branches = repo.localBranches().value! let expectedCount = 9 let expectedMessages: [String] = [ "List branches in README\n", "Create a README\n", "Merge branch 'alphabetize'\n", "Alphabetize branches\n", "List new branches\n", "List branches in README\n", "Create a README\n", "List branches in README\n", "Create a README\n", ] var commitMessages: [String] = [] for branch in branches { for commit in repo.commits(in: branch) { commitMessages.append(commit.value!.message) } } expect(commitMessages.count).to(equal(expectedCount)) expect(commitMessages).to(equal(expectedMessages)) } } describe("Repository.add") { it("Should add the modification under a path") { let repo = Fixtures.simpleRepository let branch = repo.localBranch(named: "master").value! expect(repo.checkout(branch, strategy: CheckoutStrategy.None).error).to(beNil()) // make a change to README let readmeURL = repo.directoryURL!.appendingPathComponent("README.md") let readmeData = try! Data(contentsOf: readmeURL) defer { try! readmeData.write(to: readmeURL) } try! "different".data(using: .utf8)?.write(to: readmeURL) let status = repo.status() expect(status.value?.count).to(equal(1)) expect(status.value!.first!.status).to(equal(.workTreeModified)) expect(repo.add(path: "README.md").error).to(beNil()) let newStatus = repo.status() expect(newStatus.value?.count).to(equal(1)) expect(newStatus.value!.first!.status).to(equal(.indexModified)) } it("Should add an untracked file under a path") { let repo = Fixtures.simpleRepository let branch = repo.localBranch(named: "master").value! expect(repo.checkout(branch, strategy: CheckoutStrategy.None).error).to(beNil()) // make a change to README let untrackedURL = repo.directoryURL!.appendingPathComponent("untracked") try! "different".data(using: .utf8)?.write(to: untrackedURL) defer { try! FileManager.default.removeItem(at: untrackedURL) } expect(repo.add(path: ".").error).to(beNil()) let newStatus = repo.status() expect(newStatus.value?.count).to(equal(1)) expect(newStatus.value!.first!.status).to(equal(.indexNew)) } } describe("Repository.commit") { it("Should perform a simple commit with specified signature") { let repo = Fixtures.simpleRepository let branch = repo.localBranch(named: "master").value! expect(repo.checkout(branch, strategy: CheckoutStrategy.None).error).to(beNil()) // make a change to README let untrackedURL = repo.directoryURL!.appendingPathComponent("untrackedtest") try! "different".data(using: .utf8)?.write(to: untrackedURL) expect(repo.add(path: ".").error).to(beNil()) let signature = Signature( name: "swiftgit2", email: "[email protected]", time: Date(timeIntervalSince1970: 1525200858), timeZone: TimeZone(secondsFromGMT: 3600)! ) let message = "Test Commit" expect(repo.commit(message: message, signature: signature).error).to(beNil()) let updatedBranch = repo.localBranch(named: "master").value! expect(repo.commits(in: updatedBranch).next()?.value?.author).to(equal(signature)) expect(repo.commits(in: updatedBranch).next()?.value?.committer).to(equal(signature)) expect(repo.commits(in: updatedBranch).next()?.value?.message).to(equal("\(message)\n")) expect(repo.commits(in: updatedBranch).next()?.value?.oid.description) .to(equal("7d6b2d7492f29aee48022387f96dbfe996d435fe")) // should be clean now let newStatus = repo.status() expect(newStatus.value?.count).to(equal(0)) } } describe("Repository.status") { it("Should accurately report status for repositories with no status") { let expectedCount = 0 let repo = Fixtures.mantleRepository let branch = repo.localBranch(named: "master").value! expect(repo.checkout(branch, strategy: CheckoutStrategy.None).error).to(beNil()) let status = repo.status() expect(status.value?.count).to(equal(expectedCount)) } it("Should accurately report status for repositories with status") { let expectedCount = 5 let expectedNewFilePaths = [ "stage-file-1", "stage-file-2", "stage-file-3", "stage-file-4", "stage-file-5", ] let expectedOldFilePaths = [ "stage-file-1", "stage-file-2", "stage-file-3", "stage-file-4", "stage-file-5", ] let repoWithStatus = Fixtures.sharedInstance.repository(named: "repository-with-status") let branchWithStatus = repoWithStatus.localBranch(named: "master").value! expect(repoWithStatus.checkout(branchWithStatus, strategy: CheckoutStrategy.None).error).to(beNil()) let statuses = repoWithStatus.status().value! var newFilePaths: [String] = [] for status in statuses { newFilePaths.append((status.headToIndex?.newFile?.path)!) } var oldFilePaths: [String] = [] for status in statuses { oldFilePaths.append((status.headToIndex?.oldFile?.path)!) } expect(statuses.count).to(equal(expectedCount)) expect(newFilePaths).to(equal(expectedNewFilePaths)) expect(oldFilePaths).to(equal(expectedOldFilePaths)) } } describe("Repository.diff") { it("Should have accurate delta information") { let expectedCount = 13 let expectedNewFilePaths = [ ".gitmodules", "Cartfile", "Cartfile.lock", "Cartfile.private", "Cartfile.resolved", "Carthage.checkout/Nimble", "Carthage.checkout/Quick", "Carthage.checkout/xcconfigs", "Carthage/Checkouts/Nimble", "Carthage/Checkouts/Quick", "Carthage/Checkouts/xcconfigs", "Mantle.xcodeproj/project.pbxproj", "Mantle.xcworkspace/contents.xcworkspacedata", ] let expectedOldFilePaths = [ ".gitmodules", "Cartfile", "Cartfile.lock", "Cartfile.private", "Cartfile.resolved", "Carthage.checkout/Nimble", "Carthage.checkout/Quick", "Carthage.checkout/xcconfigs", "Carthage/Checkouts/Nimble", "Carthage/Checkouts/Quick", "Carthage/Checkouts/xcconfigs", "Mantle.xcodeproj/project.pbxproj", "Mantle.xcworkspace/contents.xcworkspacedata", ] let repo = Fixtures.mantleRepository let branch = repo.localBranch(named: "master").value! expect(repo.checkout(branch, strategy: CheckoutStrategy.None).error).to(beNil()) let head = repo.HEAD().value! let commit = repo.object(head.oid).value! as! Commit let diff = repo.diff(for: commit).value! let newFilePaths = diff.deltas.map { $0.newFile!.path } let oldFilePaths = diff.deltas.map { $0.oldFile!.path } expect(diff.deltas.count).to(equal(expectedCount)) expect(newFilePaths).to(equal(expectedNewFilePaths)) expect(oldFilePaths).to(equal(expectedOldFilePaths)) } it("Should handle initial commit well") { let expectedCount = 2 let expectedNewFilePaths = [ ".gitignore", "README.md", ] let expectedOldFilePaths = [ ".gitignore", "README.md", ] let repo = Fixtures.mantleRepository expect(repo.checkout(OID(string: "047b931bd7f5478340cef5885a6fff713005f4d6")!, strategy: CheckoutStrategy.None).error).to(beNil()) let head = repo.HEAD().value! let initalCommit = repo.object(head.oid).value! as! Commit let diff = repo.diff(for: initalCommit).value! var newFilePaths: [String] = [] for delta in diff.deltas { newFilePaths.append((delta.newFile?.path)!) } var oldFilePaths: [String] = [] for delta in diff.deltas { oldFilePaths.append((delta.oldFile?.path)!) } expect(diff.deltas.count).to(equal(expectedCount)) expect(newFilePaths).to(equal(expectedNewFilePaths)) expect(oldFilePaths).to(equal(expectedOldFilePaths)) } it("Should handle merge commits well") { let expectedCount = 20 let expectedNewFilePaths = [ "Mantle.xcodeproj/project.pbxproj", "Mantle/MTLModel+NSCoding.m", "Mantle/Mantle.h", "Mantle/NSArray+MTLHigherOrderAdditions.h", "Mantle/NSArray+MTLHigherOrderAdditions.m", "Mantle/NSArray+MTLManipulationAdditions.m", "Mantle/NSDictionary+MTLHigherOrderAdditions.h", "Mantle/NSDictionary+MTLHigherOrderAdditions.m", "Mantle/NSDictionary+MTLManipulationAdditions.m", "Mantle/NSNotificationCenter+MTLWeakReferenceAdditions.h", "Mantle/NSNotificationCenter+MTLWeakReferenceAdditions.m", "Mantle/NSOrderedSet+MTLHigherOrderAdditions.h", "Mantle/NSOrderedSet+MTLHigherOrderAdditions.m", "Mantle/NSSet+MTLHigherOrderAdditions.h", "Mantle/NSSet+MTLHigherOrderAdditions.m", "Mantle/NSValueTransformer+MTLPredefinedTransformerAdditions.m", "MantleTests/MTLHigherOrderAdditionsSpec.m", "MantleTests/MTLNotificationCenterAdditionsSpec.m", "MantleTests/MTLPredefinedTransformerAdditionsSpec.m", "README.md", ] let expectedOldFilePaths = [ "Mantle.xcodeproj/project.pbxproj", "Mantle/MTLModel+NSCoding.m", "Mantle/Mantle.h", "Mantle/NSArray+MTLHigherOrderAdditions.h", "Mantle/NSArray+MTLHigherOrderAdditions.m", "Mantle/NSArray+MTLManipulationAdditions.m", "Mantle/NSDictionary+MTLHigherOrderAdditions.h", "Mantle/NSDictionary+MTLHigherOrderAdditions.m", "Mantle/NSDictionary+MTLManipulationAdditions.m", "Mantle/NSNotificationCenter+MTLWeakReferenceAdditions.h", "Mantle/NSNotificationCenter+MTLWeakReferenceAdditions.m", "Mantle/NSOrderedSet+MTLHigherOrderAdditions.h", "Mantle/NSOrderedSet+MTLHigherOrderAdditions.m", "Mantle/NSSet+MTLHigherOrderAdditions.h", "Mantle/NSSet+MTLHigherOrderAdditions.m", "Mantle/NSValueTransformer+MTLPredefinedTransformerAdditions.m", "MantleTests/MTLHigherOrderAdditionsSpec.m", "MantleTests/MTLNotificationCenterAdditionsSpec.m", "MantleTests/MTLPredefinedTransformerAdditionsSpec.m", "README.md", ] let repo = Fixtures.mantleRepository expect(repo.checkout(OID(string: "d0d9c13da5eb5f9e8cf2a9f1f6ca3bdbe975b57d")!, strategy: CheckoutStrategy.None).error).to(beNil()) let head = repo.HEAD().value! let initalCommit = repo.object(head.oid).value! as! Commit let diff = repo.diff(for: initalCommit).value! var newFilePaths: [String] = [] for delta in diff.deltas { newFilePaths.append((delta.newFile?.path)!) } var oldFilePaths: [String] = [] for delta in diff.deltas { oldFilePaths.append((delta.oldFile?.path)!) } expect(diff.deltas.count).to(equal(expectedCount)) expect(newFilePaths).to(equal(expectedNewFilePaths)) expect(oldFilePaths).to(equal(expectedOldFilePaths)) } } } func temporaryURL(forPurpose purpose: String) -> URL { let globallyUniqueString = ProcessInfo.processInfo.globallyUniqueString let path = "\(NSTemporaryDirectory())\(globallyUniqueString)_\(purpose)" return URL(fileURLWithPath: path) } }
768ece61b9cc127f0f9a7faa28d1ef36
33.241521
118
0.681124
false
false
false
false
zhangao0086/DrawingBoard
refs/heads/master
DrawingBoard/RGBColorPicker.swift
mit
1
// // RGBColorPicker.swift // DrawingBoard // // Created by ZhangAo on 15-3-29. // Copyright (c) 2015年 zhangao. All rights reserved. // import UIKit class RGBColorPicker: UIView { var colorChangedBlock: ((color: UIColor) -> Void)? private var sliders = [UISlider]() private var labels = [UILabel]() override init(frame: CGRect) { super.init(frame: frame) self.initial() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initial() } private func initial() { self.backgroundColor = UIColor.clearColor() let trackColors = [UIColor.redColor(), UIColor.greenColor(), UIColor.blueColor()] for index in 1...3 { let slider = UISlider() slider.minimumValue = 0 slider.value = 0 slider.maximumValue = 255 slider.minimumTrackTintColor = trackColors[index - 1] slider.addTarget(self, action: "colorChanged:", forControlEvents: .ValueChanged) self.addSubview(slider) self.sliders.append(slider) let label = UILabel() label.text = "0" self.addSubview(label) self.labels.append(label) } } override func layoutSubviews() { super.layoutSubviews() let sliderHeight = CGFloat(31) let labelWidth = CGFloat(29) let yHeight = self.bounds.size.height / CGFloat(sliders.count) for index in 0..<self.sliders.count { let slider = self.sliders[index] slider.frame = CGRect(x: 0, y: CGFloat(index) * yHeight, width: self.bounds.size.width - labelWidth - 5.0, height: sliderHeight) let label = self.labels[index] label.frame = CGRect(x: CGRectGetMaxX(slider.frame) + 5, y: slider.frame.origin.y, width: labelWidth, height: sliderHeight) } } override func intrinsicContentSize() -> CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: 107) } @IBAction private func colorChanged(slider: UISlider) { let color = UIColor( red: CGFloat(self.sliders[0].value / 255.0), green: CGFloat(self.sliders[1].value / 255.0), blue: CGFloat(self.sliders[2].value / 255.0), alpha: 1) let label = self.labels[self.sliders.indexOf(slider)!] label.text = NSString(format: "%.0f", slider.value) as String if let colorChangedBlock = self.colorChangedBlock { colorChangedBlock(color: color) } } func setCurrentColor(color: UIColor) { var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: nil) let colors = [red, green, blue] for index in 0..<self.sliders.count { let slider = self.sliders[index] slider.value = Float(colors[index]) * 255 let label = self.labels[index] label.text = NSString(format: "%.0f", slider.value) as String } } }
51d13f5f29813cfe818a2f44af03253c
31.393939
140
0.571429
false
false
false
false
WickedColdfront/Slide-iOS
refs/heads/master
Pods/reddift/reddift/OAuth/OAuth2AppOnlyToken.swift
apache-2.0
1
// // OAuth2AppOnlyToken.swift // reddift // // Created by sonson on 2015/05/05. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** OAuth2Token extension to authorize without a user context. This class is private and for only unit testing because "Installed app" is prohibited from using "Application Only OAuth" scheme, that is without user context. */ public struct OAuth2AppOnlyToken: Token { public static let baseURL = "https://www.reddit.com/api/v1" public let accessToken: String public let tokenType: String public let expiresIn: Int public let scope: String public let refreshToken: String public let name: String public let expiresDate: TimeInterval /** Time inteval the access token expires from being authorized. */ // public var expiresIn:Int { // set (newValue) { _expiresIn = newValue; expiresDate = NSDate.timeIntervalSinceReferenceDate() + Double(_expiresIn) } // get { return _expiresIn } // } /** Initialize vacant OAuth2AppOnlyToken with JSON. */ public init() { self.name = "" self.accessToken = "" self.tokenType = "" self.expiresIn = 0 self.scope = "" self.refreshToken = "" self.expiresDate = Date.timeIntervalSinceReferenceDate + 0 } /** Initialize OAuth2AppOnlyToken with JSON. - parameter json: JSON as JSONDictionary should include "name", "access_token", "token_type", "expires_in", "scope" and "refresh_token". */ public init(_ json: JSONDictionary) { self.name = json["name"] as? String ?? "" self.accessToken = json["access_token"] as? String ?? "" self.tokenType = json["token_type"] as? String ?? "" let expiresIn = json["expires_in"] as? Int ?? 0 self.expiresIn = expiresIn self.expiresDate = json["expires_date"] as? TimeInterval ?? Date.timeIntervalSinceReferenceDate + Double(expiresIn) self.scope = json["scope"] as? String ?? "" self.refreshToken = json["refresh_token"] as? String ?? "" } /** Create URLRequest object to request getting an access token. - parameter code: The code which is obtained from OAuth2 redict URL at reddit.com. - returns: URLRequest object to request your access token. */ public static func requestForOAuth2AppOnly(username: String, password: String, clientID: String, secret: String) -> URLRequest? { guard let URL = URL(string: "https://ssl.reddit.com/api/v1/access_token") else { return nil } var request = URLRequest(url:URL) do { try request.setRedditBasicAuthentication(username:clientID, password:secret) let param = "grant_type=password&username=" + username + "&password=" + password let data = param.data(using: .utf8) request.httpBody = data request.httpMethod = "POST" return request } catch { print(error) return nil } } /** Request to get a new access token. - parameter code: Code to be confirmed your identity by reddit. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public static func getOAuth2AppOnlyToken(username: String, password: String, clientID: String, secret: String, completion: @escaping (Result<Token>) -> Void) throws -> URLSessionDataTask { let session = URLSession(configuration: URLSessionConfiguration.default) guard let request = requestForOAuth2AppOnly(username:username, password:password, clientID:clientID, secret:secret) else { throw ReddiftError.canNotCreateURLRequest as NSError } let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in let result = Result(from: Response(data: data, urlResponse: response), optional:error as NSError?) .flatMap(response2Data) .flatMap(data2Json) .flatMap({(json: JSONAny) -> Result<JSONDictionary> in if let json = json as? JSONDictionary { return Result(value: json) } return Result(error: ReddiftError.tokenJsonObjectIsNotDictionary as NSError) }) var token: OAuth2AppOnlyToken? = nil switch result { case .success(let json): var newJSON = json newJSON["name"] = username as AnyObject token = OAuth2AppOnlyToken(newJSON) default: break } completion(Result(fromOptional: token, error: ReddiftError.unknown as NSError)) }) task.resume() return task } }
7c5510a43aa4dbb8459f1b70cd50f498
40.25
192
0.629899
false
false
false
false
CodaFi/swift
refs/heads/main
test/IDE/complete_from_reexport.swift
apache-2.0
53
// RUN: %empty-directory(%t) // // RUN: %target-swift-frontend -emit-module -module-name FooSwiftModule %S/Inputs/foo_swift_module.swift -o %t // RUN: %target-swift-frontend -emit-module -module-name FooSwiftModuleOverlay %S/Inputs/foo_swift_module_overlay.swift -I %t -o %t // // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 -I %t > %t.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_1 < %t.txt // RUN: %FileCheck %s -check-prefix=NO_DUPLICATES < %t.txt // TOP_LEVEL_1: Begin completions // TOP_LEVEL_1-DAG: Decl[FreeFunction]/OtherModule[FooSwiftModuleOverlay]: overlayedFoo()[#Void#]{{; name=.+$}} // TOP_LEVEL_1-DAG: Decl[FreeFunction]/OtherModule[FooSwiftModuleOverlay]: onlyInFooOverlay()[#Void#]{{; name=.+$}} // TOP_LEVEL_1: End completions // FIXME: there should be only one instance of this completion result. // NO_DUPLICATES: overlayedFoo()[#Void#]{{; name=.+$}} // NO_DUPLICATES: overlayedFoo()[#Void#]{{; name=.+$}} // NO_DUPLICATES-NOT: overlayedFoo()[#Void#]{{; name=.+$}} import FooSwiftModuleOverlay #^TOP_LEVEL_1^#
4b57796fbc123473b7fa65f01fb0c093
49.136364
131
0.693563
false
false
false
false
seanwoodward/IBAnimatable
refs/heads/master
IBAnimatable/FoldAnimator.swift
mit
1
// // Created by Tom Baranes on 09/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class FoldAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - Private params private var fromDirection: TransitionDirection private var folds: Int = 2 // MARK: - Private fold transition private var transform: CATransform3D = CATransform3DIdentity private var reverse: Bool = false private var horizontal: Bool = false private var size: CGSize = CGSize.zero private var foldSize: CGFloat = 0.0 private var width: CGFloat { return horizontal ? size.width : size.height } private var height: CGFloat { return horizontal ? size.height : size.width } // MARK: - Life cycle public init(fromDirection: TransitionDirection, params: [String], transitionDuration: Duration) { self.fromDirection = fromDirection self.transitionDuration = transitionDuration horizontal = fromDirection.isHorizontal if let firstParam = params.first, unwrappedFolds = Int(firstParam) { self.folds = unwrappedFolds } switch fromDirection { case .Right: self.transitionAnimationType = .Fold(fromDirection: .Right, params: params) self.reverseAnimationType = .Fold(fromDirection: .Left, params: params) self.interactiveGestureType = .Pan(fromDirection: .Left) reverse = true case .Top: self.transitionAnimationType = .Fold(fromDirection: .Top, params: params) self.reverseAnimationType = .Fold(fromDirection: .Bottom, params: params) self.interactiveGestureType = .Pan(fromDirection: .Bottom) reverse = false case .Bottom: self.transitionAnimationType = .Fold(fromDirection: .Bottom, params: params) self.reverseAnimationType = .Fold(fromDirection: .Top, params: params) self.interactiveGestureType = .Pan(fromDirection: .Top) reverse = true default: self.transitionAnimationType = .Fold(fromDirection: .Left, params: params) self.reverseAnimationType = .Fold(fromDirection: .Right, params: params) self.interactiveGestureType = .Pan(fromDirection: .Right) reverse = false } super.init() } } extension FoldAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return retrieveTransitionDuration(transitionContext) } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext) guard let fromView = tempfromView, toView = tempToView, containerView = tempContainerView else { transitionContext.completeTransition(true) return } toView.frame = toView.frame.offsetBy(dx: toView.frame.size.width, dy: 0) containerView.addSubview(toView) transform.m34 = -0.005 containerView.layer.sublayerTransform = transform size = toView.frame.size foldSize = width * 0.5 / CGFloat(folds) let viewFolds = createSnapshots(toView: toView, fromView: fromView, containerView: containerView) animateFoldTransition(fromView: fromView, toViewFolds: viewFolds[0], fromViewFolds: viewFolds[1], completion: { if !transitionContext.transitionWasCancelled() { toView.frame = containerView.bounds fromView.frame = containerView.bounds } else { fromView.frame = containerView.bounds } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } ) } } // MARK: - Setup fold transition private extension FoldAnimator { func createSnapshots(toView toView: UIView, fromView: UIView, containerView: UIView) -> [[UIView]] { var fromViewFolds = [UIView]() var toViewFolds = [UIView]() for i in 0..<folds { let offset = CGFloat(i) * foldSize * 2 let leftFromViewFold = createSnapshot(fromView: fromView, afterUpdates: false, offset: offset, left: true) var axesValues = valuesForAxe(offset, reverseValue: height / 2) leftFromViewFold.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) fromViewFolds.append(leftFromViewFold) leftFromViewFold.subviews[1].alpha = 0.0 let rightFromViewFold = createSnapshot(fromView: fromView, afterUpdates: false, offset: offset + foldSize, left: false) axesValues = valuesForAxe(offset + foldSize * 2, reverseValue: height / 2) rightFromViewFold.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) fromViewFolds.append(rightFromViewFold) rightFromViewFold.subviews[1].alpha = 0.0 let leftToViewFold = createSnapshot(fromView: toView, afterUpdates: true, offset: offset, left: true) axesValues = valuesForAxe(self.reverse ? width : 0.0, reverseValue: height / 2) leftToViewFold.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = valuesForAxe(0.0, reverseValue: 1.0) leftToViewFold.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI_2), axesValues.0, axesValues.1, 0.0) toViewFolds.append(leftToViewFold) let rightToViewFold = createSnapshot(fromView: toView, afterUpdates: true, offset: offset + foldSize, left: false) axesValues = valuesForAxe(self.reverse ? width : 0.0, reverseValue: height / 2) rightToViewFold.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = valuesForAxe(0.0, reverseValue: 1.0) rightToViewFold.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI_2), axesValues.0, axesValues.1, 0.0) toViewFolds.append(rightToViewFold) } return [toViewFolds, fromViewFolds] } func createSnapshot(fromView view: UIView, afterUpdates: Bool, offset: CGFloat, left: Bool) -> UIView { let containerView = view.superview var snapshotView: UIView var axesValues = valuesForAxe(offset, reverseValue: 0.0) let axesValues2 = valuesForAxe(foldSize, reverseValue: height) let snapshotRegion = CGRect(x: axesValues.0, y: axesValues.1, width: axesValues2.0, height: axesValues2.1) if !afterUpdates { snapshotView = view.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: afterUpdates, withCapInsets: UIEdgeInsetsZero) } else { axesValues = valuesForAxe(foldSize, reverseValue: height) snapshotView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: axesValues.0, height: axesValues.1)) snapshotView.backgroundColor = view.backgroundColor let subSnapshotView = view.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: afterUpdates, withCapInsets: UIEdgeInsetsZero) snapshotView.addSubview(subSnapshotView) } let snapshotWithShadowView = addShadow(toView: snapshotView, reverse: left) containerView?.addSubview(snapshotWithShadowView) axesValues = valuesForAxe(left ? 0.0 : 1.0, reverseValue: 0.5) snapshotWithShadowView.layer.anchorPoint = CGPoint(x: axesValues.0, y: axesValues.1) return snapshotWithShadowView } func addShadow(toView view: UIView, reverse: Bool) -> UIView { let viewWithShadow = UIView(frame: view.frame) let shadowView = UIView(frame: viewWithShadow.bounds) let gradient = CAGradientLayer() gradient.frame = shadowView.bounds gradient.colors = [UIColor(white: 0.0, alpha: 0.0).CGColor, UIColor(white: 0.0, alpha: 1.0).CGColor] if horizontal { var axesValues = valuesForAxe(reverse ? 0.0 : 1.0, reverseValue: reverse ? 0.2 : 0.0) gradient.startPoint = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = valuesForAxe(reverse ? 1.0 : 0.0, reverseValue: reverse ? 0.0 : 1.0) gradient.endPoint = CGPoint(x: axesValues.0, y: axesValues.1) } else { var axesValues = valuesForAxe(reverse ? 0.2 : 0.0, reverseValue: reverse ? 0.0 : 1.0) gradient.startPoint = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = valuesForAxe(reverse ? 0.0 : 1.0, reverseValue: reverse ? 1.0 : 0.0) gradient.endPoint = CGPoint(x: axesValues.0, y: axesValues.1) } shadowView.layer.insertSublayer(gradient, atIndex: 1) view.frame = view.bounds viewWithShadow.addSubview(view) viewWithShadow.addSubview(shadowView) return viewWithShadow } } // MARK: - Animates private extension FoldAnimator { func animateFoldTransition(fromView view: UIView, toViewFolds: [UIView], fromViewFolds: [UIView], completion: AnimatableCompletion) { view.frame = view.frame.offsetBy(dx: view.frame.width, dy: 0) UIView.animateWithDuration(transitionDuration, animations: { for i in 0..<self.folds { let offset = CGFloat(i) * self.foldSize * 2 let leftFromView = fromViewFolds[i * 2] var axesValues = self.valuesForAxe(self.reverse ? 0.0 : self.width, reverseValue: self.height / 2) leftFromView.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = self.valuesForAxe(0.0, reverseValue: 1.0) leftFromView.layer.transform = CATransform3DRotate(self.transform, CGFloat(M_PI_2), axesValues.0, axesValues.1, 0) leftFromView.subviews[1].alpha = 1.0 let rightFromView = fromViewFolds[i * 2 + 1] axesValues = self.valuesForAxe(self.reverse ? 0.0 : self.width, reverseValue: self.height / 2) rightFromView.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = self.valuesForAxe(0.0, reverseValue: 1.0) rightFromView.layer.transform = CATransform3DRotate(self.transform, CGFloat(-M_PI_2), axesValues.0, axesValues.1, 0) rightFromView.subviews[1].alpha = 1.0 let leftToView = toViewFolds[i * 2] axesValues = self.valuesForAxe(offset, reverseValue: self.height / 2) leftToView.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) leftToView.layer.transform = CATransform3DIdentity leftToView.subviews[1].alpha = 0.0 let rightToView = toViewFolds[i * 2 + 1] axesValues = self.valuesForAxe(offset + self.foldSize * 2, reverseValue: self.height / 2) rightToView.layer.position = CGPoint(x: axesValues.0, y: axesValues.1) rightToView.layer.transform = CATransform3DIdentity rightToView.subviews[1].alpha = 0.0 } }, completion: { _ in toViewFolds.forEach { $0.removeFromSuperview() } fromViewFolds.forEach { $0.removeFromSuperview() } completion() }) } } // MARK: - Helpers private extension FoldAnimator { func valuesForAxe(initialValue: CGFloat, reverseValue: CGFloat) -> (CGFloat, CGFloat) { return horizontal ? (initialValue, reverseValue) : (reverseValue, initialValue) } }
1bac141cd09a68b3587089bb49ed2b0f
42.695652
145
0.709453
false
false
false
false
nikrad/ios
refs/heads/master
FiveCalls/FiveCalls/ContactLog.swift
mit
2
// // ContactLog.swift // FiveCalls // // Created by Ben Scheirman on 2/5/17. // Copyright © 2017 5calls. All rights reserved. // import Foundation import Pantry enum ContactOutcome : String { case contacted case voicemail = "vm" case unavailable // reserved for cases where we save something on disk that we later don't recognize case unknown } struct ContactLog { let issueId: String let contactId: String let phone: String let outcome: ContactOutcome let date: Date static var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter }() } extension ContactLog : Storable { init(warehouse: Warehouseable) { issueId = warehouse.get("issueId") ?? "" contactId = warehouse.get("contactId") ?? "" phone = warehouse.get("phone") ?? "" outcome = warehouse.get("outcome").flatMap(ContactOutcome.init) ?? .unknown date = ContactLog.dateFormatter.date(from: warehouse.get("date") ?? "") ?? Date() } func toDictionary() -> [String : Any] { return [ "issueId": issueId, "contactId": contactId, "phone": phone, "outcome": outcome.rawValue, "date": ContactLog.dateFormatter.string(from: date) ] } } extension ContactLog : Hashable { var hashValue: Int { return (issueId + contactId + phone + outcome.rawValue).hash } static func ==(lhs: ContactLog, rhs: ContactLog) -> Bool { return lhs.issueId == rhs.issueId && lhs.contactId == rhs.contactId && lhs.phone == rhs.phone && lhs.outcome == rhs.outcome } } struct ContactLogs { private static let persistenceKey = "ContactLogs" var all: [ContactLog] init() { all = [] } private init(logs: [ContactLog]) { all = logs } mutating func add(log: ContactLog) { all.append(log) save() NotificationCenter.default.post(name: .callMade, object: log) } func save() { Pantry.pack(all, key: ContactLogs.persistenceKey) } static func load() -> ContactLogs { return Pantry.unpack(persistenceKey).flatMap(ContactLogs.init) ?? ContactLogs() } func methodOfContact(to contactId: String, forIssue issueId: String) -> ContactOutcome? { return all.filter({$0.contactId == contactId && $0.issueId == issueId}).last?.outcome } func hasContacted(contactId: String, forIssue issueId: String) -> Bool { guard let method = methodOfContact(to: contactId, forIssue: issueId) else { return false } switch method { case .contacted, .voicemail: return true case .unknown, .unavailable: return false } } func hasCompleted(issue: String, allContacts: [Contact]) -> Bool { if (allContacts.count == 0) { return false } for contact in allContacts { if !hasContacted(contactId: contact.id, forIssue: issue) { return false } } return true } }
874b6fb21390d27d3257fc7ba30f2a68
25.503937
93
0.579323
false
false
false
false
scarlett2003/MRTSwift
refs/heads/master
MRT/ViewController.swift
mit
1
// // ViewController.swift // MRT // // Created by evan3rd on 2015/5/13. // Copyright (c) 2015年 evan3rd. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 每 60sec重新reload NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: Selector("routineSyncDepartureTime"), userInfo: nil, repeats: true) let background = UIImage(named: "bgkmrt.jpg") self.view.backgroundColor = UIColor(patternImage: background!) //var station = DepartureManager.sharedInstance.stations[0] //var platform = station.redLine[0] //var time = platform.arrivalTime //println(time) // 先印出所有中文站名即可 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - private func routineSyncDepartureTime() { DepartureManager.sharedInstance.syncMRTDepartureTime(completionBlock: { () -> Void in println("==========") for var i = 0; i < DepartureManager.sharedInstance.stations.count; ++i { var st = DepartureManager.sharedInstance.stations[i] println("\(st.cname) \(st.code)") for p:Platform in st.redLine { println("\(p.destination) \(p.arrivalTime) \(p.nextArrivalTime)") } for p:Platform in st.orangeLine { println("\(p.destination) \(p.arrivalTime) \(p.nextArrivalTime)") } println("==========") } self.tableView.reloadData() }, errorBlock: nil) } // MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return DepartureManager.sharedInstance.stations.count println("count = \(DepartureManager.sharedInstance.stations.count)") return DepartureManager.sharedInstance.stations.count //return 2 //呈現的行數.項 } // func stationData { // var station = DepartureManager.sharedInstance.stations[0] // var platform = station.redLine[0] // var time = platform.arrivalTime // } // 這行函數呈現的是,控制來源數據於每行呈現的樣子及效果 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("station") as! UITableViewCell var station = DepartureManager.sharedInstance.stations[indexPath.row] var label = cell.viewWithTag(101) as! UILabel label.text = station.cname //var station = DepartureManager.sharedInstance.stations[0] //var platform = station.redLine[0] //var time = platform.arrivalTime // var stationTitle: UILabel = cell.viewWithTag(101) as! UILabel // stationTitle.text = "\(station)" return cell } }
e1a9b0574b1d2f95487ff0f39d5317ed
32.673469
140
0.625758
false
false
false
false
amraboelela/swift
refs/heads/master
test/stdlib/ErrorBridged.swift
apache-2.0
8
// RUN: %empty-directory(%t) // RUN: %target-build-swift -o %t/ErrorBridged -DPTR_SIZE_%target-ptrsize -module-name main %s // RUN: %target-run %t/ErrorBridged // REQUIRES: executable_test // REQUIRES: objc_interop import StdlibUnittest import Foundation import CoreLocation import Darwin var ErrorBridgingTests = TestSuite("ErrorBridging") var NoisyErrorLifeCount = 0 var NoisyErrorDeathCount = 0 var CanaryHandle = 0 protocol OtherProtocol { var otherProperty: String { get } } protocol OtherClassProtocol : class { var otherClassProperty: String { get } } class NoisyError : Error, OtherProtocol, OtherClassProtocol { init() { NoisyErrorLifeCount += 1 } deinit { NoisyErrorDeathCount += 1 } let _domain = "NoisyError" let _code = 123 let otherProperty = "otherProperty" let otherClassProperty = "otherClassProperty" } @objc enum EnumError : Int, Error { case BadError = 9000 case ReallyBadError = 9001 } ErrorBridgingTests.test("NSError") { NoisyErrorLifeCount = 0 NoisyErrorDeathCount = 0 autoreleasepool { let ns = NSError(domain: "SomeDomain", code: 321, userInfo: nil) objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) let e: Error = ns expectEqual(e._domain, "SomeDomain") expectEqual(e._code, 321) let ns2 = e as NSError expectTrue(ns === ns2) expectEqual(ns2._domain, "SomeDomain") expectEqual(ns2._code, 321) } expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount) } ErrorBridgingTests.test("NSCopying") { autoreleasepool { let orig = EnumError.ReallyBadError as NSError let copy = orig.copy() as! NSError expectEqual(orig, copy) } } // Gated on the availability of NSKeyedArchiver.archivedData(withRootObject:). @available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) func archiveAndUnarchiveObject<T: NSCoding>( _ object: T ) -> T? where T: NSObject { let unarchiver = NSKeyedUnarchiver(forReadingWith: NSKeyedArchiver.archivedData(withRootObject: object) ) unarchiver.requiresSecureCoding = true return unarchiver.decodeObject(of: T.self, forKey: "root") } ErrorBridgingTests.test("NSCoding") { if #available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { autoreleasepool { let orig = EnumError.ReallyBadError as NSError let unarchived = archiveAndUnarchiveObject(orig)! expectEqual(orig, unarchived) expectTrue(type(of: unarchived) == NSError.self) } } } ErrorBridgingTests.test("NSError-to-enum bridging") { NoisyErrorLifeCount = 0 NoisyErrorDeathCount = 0 let testURL = URL(string: "https://swift.org")! autoreleasepool { let underlyingError = CocoaError(.fileLocking) as Error as NSError let ns = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ NSFilePathErrorKey: "/dev/null", NSStringEncodingErrorKey: /*ASCII=*/1, NSUnderlyingErrorKey: underlyingError, NSURLErrorKey: testURL ]) objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) let e: Error = ns let cocoaCode: Int? switch e { case let x as CocoaError: cocoaCode = x._code expectTrue(x.isFileError) expectEqual(x.code, .fileNoSuchFile) default: cocoaCode = nil } expectEqual(NSFileNoSuchFileError, cocoaCode) let cocoaCode2: Int? = (ns as? CocoaError)?._code expectEqual(NSFileNoSuchFileError, cocoaCode2) let isNoSuchFileError: Bool switch e { case CocoaError.fileNoSuchFile: isNoSuchFileError = true default: isNoSuchFileError = false } expectTrue(isNoSuchFileError) // Check the contents of the error. let cocoaError = e as! CocoaError expectEqual("/dev/null", cocoaError.filePath) expectEqual(String.Encoding.ascii, cocoaError.stringEncoding) expectEqual(underlyingError, cocoaError.underlying.map { $0 as NSError }) expectEqual(testURL, cocoaError.url) // URLError domain let nsURL = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSURLErrorFailingURLErrorKey: testURL]) let eURL: Error = nsURL let isBadURLError: Bool switch eURL { case URLError.badURL: isBadURLError = true default: isBadURLError = false } expectTrue(isBadURLError) let urlError = eURL as! URLError expectEqual(testURL, urlError.failingURL) expectNil(urlError.failureURLPeerTrust) // CoreLocation error domain let nsCL = NSError(domain: kCLErrorDomain, code: CLError.headingFailure.rawValue, userInfo: [NSURLErrorKey: testURL]) let eCL: Error = nsCL let isHeadingFailure: Bool switch eCL { case CLError.headingFailure: isHeadingFailure = true default: isHeadingFailure = false } let isCLError: Bool switch eCL { case let error as CLError: isCLError = true expectEqual(testURL, (error as NSError).userInfo[NSURLErrorKey] as? URL) expectEqual(testURL, error.userInfo[NSURLErrorKey] as? URL) default: isCLError = false } expectTrue(isCLError) // NSPOSIXError domain let nsPOSIX = NSError(domain: NSPOSIXErrorDomain, code: Int(EDEADLK), userInfo: [:]) let ePOSIX: Error = nsPOSIX let isDeadlock: Bool switch ePOSIX { case POSIXError.EDEADLK: isDeadlock = true default: isDeadlock = false } expectTrue(isDeadlock) // NSMachError domain let nsMach = NSError(domain: NSMachErrorDomain, code: Int(KERN_MEMORY_FAILURE), userInfo: [:]) let eMach: Error = nsMach let isMemoryFailure: Bool switch eMach { case MachError.memoryFailure: isMemoryFailure = true default: isMemoryFailure = false } expectTrue(isMemoryFailure) } expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount) } func opaqueUpcastToAny<T>(_ x: T) -> Any { return x } struct StructError: Error { var _domain: String { return "StructError" } var _code: Int { return 4812 } } ErrorBridgingTests.test("Error-to-NSError bridging") { NoisyErrorLifeCount = 0 NoisyErrorDeathCount = 0 autoreleasepool { let e: Error = NoisyError() let ns = e as NSError let ns2 = e as NSError expectTrue(ns === ns2) expectEqual(ns._domain, "NoisyError") expectEqual(ns._code, 123) let e3: Error = ns expectEqual(e3._domain, "NoisyError") expectEqual(e3._code, 123) let ns3 = e3 as NSError expectTrue(ns === ns3) let nativeNS = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil) objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) let nativeE: Error = nativeNS let nativeNS2 = nativeE as NSError expectTrue(nativeNS === nativeNS2) expectEqual(nativeNS2._domain, NSCocoaErrorDomain) expectEqual(nativeNS2._code, NSFileNoSuchFileError) let any: Any = NoisyError() let ns4 = any as! NSError expectEqual(ns4._domain, "NoisyError") expectEqual(ns4._code, 123) let ao: AnyObject = NoisyError() let ns5 = ao as! NSError expectEqual(ns5._domain, "NoisyError") expectEqual(ns5._code, 123) let any2: Any = StructError() let ns6 = any2 as! NSError expectEqual(ns6._domain, "StructError") expectEqual(ns6._code, 4812) } expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount) } ErrorBridgingTests.test("NSError-to-error bridging in bridged container") { autoreleasepool { let error = NSError(domain: "domain", code: 42, userInfo: nil) let nsdictionary = ["error": error] as NSDictionary let dictionary = nsdictionary as? Dictionary<String, Error> expectNotNil(dictionary) expectEqual(error, dictionary?["error"] as NSError?) } } ErrorBridgingTests.test("enum-to-NSError round trip") { autoreleasepool { // Emulate throwing an error from Objective-C. func throwNSError(_ error: EnumError) throws { throw NSError(domain: "main.EnumError", code: error.rawValue, userInfo: [:]) } var caughtError: Bool caughtError = false do { try throwNSError(.BadError) expectUnreachable() } catch let error as EnumError { expectEqual(.BadError, error) caughtError = true } catch _ { expectUnreachable() } expectTrue(caughtError) caughtError = false do { try throwNSError(.ReallyBadError) expectUnreachable() } catch EnumError.BadError { expectUnreachable() } catch EnumError.ReallyBadError { caughtError = true } catch _ { expectUnreachable() } expectTrue(caughtError) } } class SomeNSErrorSubclass: NSError {} ErrorBridgingTests.test("Thrown NSError identity is preserved") { do { let e = NSError(domain: "ClericalError", code: 219, userInfo: ["yeah": "yeah"]) do { throw e } catch let e2 as NSError { expectTrue(e === e2) expectTrue(e2.userInfo["yeah"] as? String == "yeah") } catch { expectUnreachable() } } do { let f = SomeNSErrorSubclass(domain: "ClericalError", code: 219, userInfo: ["yeah": "yeah"]) do { throw f } catch let f2 as NSError { expectTrue(f === f2) expectTrue(f2.userInfo["yeah"] as? String == "yeah") } catch { expectUnreachable() } } } // Check errors customized via protocol. struct MyCustomizedError : Error { let code: Int } extension MyCustomizedError : LocalizedError { var errorDescription: String? { return NSLocalizedString("something went horribly wrong", comment: "") } var failureReason: String? { return NSLocalizedString("because someone wrote 'throw'", comment: "") } var recoverySuggestion: String? { return NSLocalizedString("delete the 'throw'", comment: "") } var helpAnchor: String? { return NSLocalizedString("there is no help when writing tests", comment: "") } } extension MyCustomizedError : CustomNSError { static var errorDomain: String { return "custom" } /// The error code within the given domain. var errorCode: Int { return code } /// The user-info dictionary. var errorUserInfo: [String : Any] { return [NSURLErrorKey : URL(string: "https://swift.org")!] } } extension MyCustomizedError : RecoverableError { var recoveryOptions: [String] { return ["Delete 'throw'", "Disable the test" ] } func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool { return recoveryOptionIndex == 0 } } /// An error type that provides localization and recovery, but doesn't /// customize NSError directly. enum MySwiftCustomizedError : Error { case failed static var errorDescriptionCount = 0 } extension MySwiftCustomizedError : LocalizedError { var errorDescription: String? { MySwiftCustomizedError.errorDescriptionCount = MySwiftCustomizedError.errorDescriptionCount + 1 return NSLocalizedString("something went horribly wrong", comment: "") } var failureReason: String? { return NSLocalizedString("because someone wrote 'throw'", comment: "") } var recoverySuggestion: String? { return NSLocalizedString("delete the 'throw'", comment: "") } var helpAnchor: String? { return NSLocalizedString("there is no help when writing tests", comment: "") } } extension MySwiftCustomizedError : RecoverableError { var recoveryOptions: [String] { return ["Delete 'throw'", "Disable the test" ] } func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool { return recoveryOptionIndex == 0 } } /// Fake definition of the informal protocol /// "NSErrorRecoveryAttempting" that we use to poke at the object /// produced for a RecoverableError. @objc protocol FakeNSErrorRecoveryAttempting { @objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:) func attemptRecovery(fromError nsError: Error, optionIndex recoveryOptionIndex: Int, delegate: AnyObject?, didRecoverSelector: Selector, contextInfo: UnsafeMutableRawPointer?) @objc(attemptRecoveryFromError:optionIndex:) func attemptRecovery(fromError nsError: Error, optionIndex recoveryOptionIndex: Int) -> Bool } class RecoveryDelegate { let expectedSuccess: Bool let expectedContextInfo: UnsafeMutableRawPointer? var called = false init(expectedSuccess: Bool, expectedContextInfo: UnsafeMutableRawPointer?) { self.expectedSuccess = expectedSuccess self.expectedContextInfo = expectedContextInfo } @objc func recover(success: Bool, contextInfo: UnsafeMutableRawPointer?) { expectEqual(expectedSuccess, success) expectEqual(expectedContextInfo, contextInfo) called = true } } /// Helper for testing a customized error. func testCustomizedError(error: Error, nsError: NSError) { // LocalizedError if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSLocalizedDescriptionKey]) expectNil(nsError.userInfo[NSLocalizedFailureReasonErrorKey]) expectNil(nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey]) expectNil(nsError.userInfo[NSHelpAnchorErrorKey]) } else { expectEqual("something went horribly wrong", nsError.userInfo[NSLocalizedDescriptionKey] as? String) expectEqual("because someone wrote 'throw'", nsError.userInfo[NSLocalizedFailureReasonErrorKey] as? String) expectEqual("delete the 'throw'", nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String) expectEqual("there is no help when writing tests", nsError.userInfo[NSHelpAnchorErrorKey] as? String) } expectEqual("something went horribly wrong", error.localizedDescription) expectEqual("something went horribly wrong", nsError.localizedDescription) expectEqual("because someone wrote 'throw'", nsError.localizedFailureReason) expectEqual("delete the 'throw'", nsError.localizedRecoverySuggestion) expectEqual("there is no help when writing tests", nsError.helpAnchor) // RecoverableError if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey]) } else { expectEqual(["Delete 'throw'", "Disable the test" ], nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String]) } expectEqual(["Delete 'throw'", "Disable the test" ], nsError.localizedRecoveryOptions) // Directly recover. let ctx = UnsafeMutableRawPointer(bitPattern:0x1234567) let attempter: AnyObject if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSRecoveryAttempterErrorKey]) attempter = nsError.recoveryAttempter! as AnyObject } else { attempter = nsError.userInfo[NSRecoveryAttempterErrorKey]! as AnyObject } expectEqual(attempter.attemptRecovery(fromError: nsError, optionIndex: 0), true) expectEqual(attempter.attemptRecovery(fromError: nsError, optionIndex: 1), false) // Recover through delegate. let rd1 = RecoveryDelegate(expectedSuccess: true, expectedContextInfo: ctx) expectEqual(false, rd1.called) attempter.attemptRecovery( fromError: nsError, optionIndex: 0, delegate: rd1, didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)), contextInfo: ctx) expectEqual(true, rd1.called) let rd2 = RecoveryDelegate(expectedSuccess: false, expectedContextInfo: nil) expectEqual(false, rd2.called) attempter.attemptRecovery( fromError: nsError, optionIndex: 1, delegate: rd2, didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)), contextInfo: nil) expectEqual(true, rd2.called) } ErrorBridgingTests.test("Customizing NSError via protocols") { let error = MyCustomizedError(code: 12345) let nsError = error as NSError // CustomNSError expectEqual("custom", nsError.domain) expectEqual(12345, nsError.code) expectEqual(URL(string: "https://swift.org"), nsError.userInfo[NSURLErrorKey] as? URL) testCustomizedError(error: error, nsError: nsError) } ErrorBridgingTests.test("Customizing localization/recovery via protocols") { let error = MySwiftCustomizedError.failed let nsError = error as NSError testCustomizedError(error: error, nsError: nsError) } ErrorBridgingTests.test("Customizing localization/recovery laziness") { let countBefore = MySwiftCustomizedError.errorDescriptionCount let error = MySwiftCustomizedError.failed let nsError = error as NSError // RecoverableError if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey]) } else { expectEqual(["Delete 'throw'", "Disable the test" ], nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String]) } expectEqual(["Delete 'throw'", "Disable the test" ], nsError.localizedRecoveryOptions) // None of the operations above should affect the count if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectEqual(countBefore, MySwiftCustomizedError.errorDescriptionCount) } // This one does affect the count. expectEqual("something went horribly wrong", error.localizedDescription) // Check that we did get a call to errorDescription. if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectEqual(countBefore+1, MySwiftCustomizedError.errorDescriptionCount) } } enum DefaultCustomizedError1 : CustomNSError { case bad case worse } enum DefaultCustomizedError2 : Int, CustomNSError { case bad = 7 case worse = 13 } enum DefaultCustomizedError3 : UInt, CustomNSError { case bad = 9 case worse = 115 #if PTR_SIZE_64 case dreadful = 0xFFFFFFFFFFFFFFFF #elseif PTR_SIZE_32 case dreadful = 0xFFFFFFFF #else #error ("Unknown pointer size") #endif static var errorDomain: String { return "customized3" } } enum DefaultCustomizedParent { enum ChildError: CustomNSError { case foo } } ErrorBridgingTests.test("Default-customized via CustomNSError") { expectEqual(1, (DefaultCustomizedError1.worse as NSError).code) expectEqual(13, (DefaultCustomizedError2.worse as NSError).code) expectEqual(115, (DefaultCustomizedError3.worse as NSError).code) expectEqual(-1, (DefaultCustomizedError3.dreadful as NSError).code) expectEqual("main.DefaultCustomizedError1", (DefaultCustomizedError1.worse as NSError).domain) expectEqual("customized3", (DefaultCustomizedError3.worse as NSError).domain) expectEqual("main.DefaultCustomizedParent.ChildError", (DefaultCustomizedParent.ChildError.foo as NSError).domain) } class MyNSError : NSError { } ErrorBridgingTests.test("NSError subclass identity") { let myNSError: Error = MyNSError(domain: "MyNSError", code: 0, userInfo: [:]) let nsError = myNSError as NSError expectTrue(type(of: nsError) == MyNSError.self) } ErrorBridgingTests.test("Wrapped NSError identity") { let nsError = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ NSFilePathErrorKey : "/dev/null", NSStringEncodingErrorKey : /*ASCII=*/1, ]) let error: Error = nsError let nsError2: NSError = error as NSError expectTrue(nsError === nsError2) // Extracting the NSError via the runtime. let cocoaErrorAny: Any = error as! CocoaError let nsError3: NSError = cocoaErrorAny as! NSError expectTrue(nsError === nsError3) if let cocoaErrorAny2: Any = error as? CocoaError { let nsError4: NSError = cocoaErrorAny2 as! NSError expectTrue(nsError === nsError4) } else { expectUnreachable() } // Extracting the NSError via direct call. let cocoaError = error as! CocoaError let nsError5: NSError = cocoaError as NSError expectTrue(nsError === nsError5) if error is CocoaError { let nsError6: NSError = cocoaError as NSError expectTrue(nsError === nsError6) } else { expectUnreachable() } } extension Error { func asNSError() -> NSError { return self as NSError } } func unconditionalCast<T>(_ x: Any, to: T.Type) -> T { return x as! T } func conditionalCast<T>(_ x: Any, to: T.Type) -> T? { return x as? T } // SR-1562 ErrorBridgingTests.test("Error archetype identity") { let myError = NSError(domain: "myErrorDomain", code: 0, userInfo: [ "one" : 1 ]) expectTrue(myError === myError.asNSError()) expectTrue(unconditionalCast(myError, to: Error.self) as NSError === myError) expectTrue(conditionalCast(myError, to: Error.self)! as NSError === myError) let nsError = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ NSFilePathErrorKey : "/dev/null", NSStringEncodingErrorKey : /*ASCII=*/1, ]) let cocoaError = nsError as Error as! CocoaError expectTrue(cocoaError.asNSError() === nsError) expectTrue(unconditionalCast(cocoaError, to: Error.self) as NSError === nsError) expectTrue(conditionalCast(cocoaError, to: Error.self)! as NSError === nsError) } // SR-9389 class ParentA: NSObject { @objc(ParentAError) enum Error: Int, Swift.Error { case failed } } class ParentB: NSObject { @objc(ParentBError) enum Error: Int, Swift.Error { case failed } } private class NonPrintAsObjCClass: NSObject { @objc enum Error: Int, Swift.Error { case foo } } @objc private enum NonPrintAsObjCError: Int, Error { case bar } ErrorBridgingTests.test("@objc error domains for nested types") { // Domain strings should correspond to Swift types, including parent types. expectEqual(ParentA.Error.failed._domain, "main.ParentA.Error") expectEqual(ParentB.Error.failed._domain, "main.ParentB.Error") func makeNSError(like error: Error) -> NSError { return NSError(domain: error._domain, code: error._code) } // NSErrors corresponding to Error types with the same name but nested in // different enclosing types should not be castable to the wrong error type. expectTrue(makeNSError(like: ParentA.Error.failed) is ParentA.Error) expectFalse(makeNSError(like: ParentA.Error.failed) is ParentB.Error) expectFalse(makeNSError(like: ParentB.Error.failed) is ParentA.Error) expectTrue(makeNSError(like: ParentB.Error.failed) is ParentB.Error) // If an @objc enum error is not eligible for PrintAsObjC, we should treat it // as though it inherited the default implementation, which calls // String(reflecting:). expectEqual(NonPrintAsObjCClass.Error.foo._domain, String(reflecting: NonPrintAsObjCClass.Error.self)) expectEqual(NonPrintAsObjCError.bar._domain, String(reflecting: NonPrintAsObjCError.self)) } runAllTests()
5391f7e644ca72979b3f24a5cda3410b
29.383117
116
0.691344
false
true
false
false
jakubknejzlik/ChipmunkSwiftWrapper
refs/heads/master
Example/ChipmunkSwiftWrapper/Wall.swift
mit
1
// // Platform.swift // ChipmunkSwiftWrapper // // Created by Jakub Knejzlik on 17/11/15. // Copyright © 2015 CocoaPods. All rights reserved. // import SpriteKit import ChipmunkSwiftWrapper class Wall: SKSpriteNode { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let platformBody = ChipmunkBody.staticBody() let platformBox = ChipmunkShape(body: platformBody, size: self.size) platformBox.elasticity = 1 platformBox.friction = 0.2 platformBox.collisionType = Wall.self self.chipmunk_body = platformBody // this is veery slow, don't use this approach in-game UIGraphicsBeginImageContext(self.size) let context = UIGraphicsGetCurrentContext(); CGContextDrawTiledImage(context, CGRectMake(0, 0, self.size.width, self.size.height), UIImage(named: "wall")?.CGImage) let tiledBackground = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let texture = SKTexture(image: tiledBackground) let changeTexture = SKAction.setTexture(texture) self.runAction(changeTexture) print(self.texture) } }
b793f7719c6e98cfe87ea68c59ee1c26
32.777778
126
0.677366
false
false
false
false
ahoppen/swift
refs/heads/main
test/Constraints/lvalues.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift func f0(_ x: inout Int) {} func f1<T>(_ x: inout T) {} func f2(_ x: inout X) {} func f2(_ x: inout Double) {} class Reftype { var property: Double { get {} set {} } } struct X { subscript(i: Int) -> Float { get {} set {} } var property: Double { get {} set {} } func genuflect() {} } struct Y { subscript(i: Int) -> Float { get {} set {} } subscript(f: Float) -> Int { get {} set {} } } var i : Int var f : Float var x : X var y : Y func +=(lhs: inout X, rhs : X) {} prefix operator +++ prefix func +++(rhs: inout X) {} f0(&i) f1(&i) f1(&x[i]) f1(&x.property) f1(&y[i]) // Missing '&' f0(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{4-4=&}} f1(y[i]) // expected-error{{passing value of type 'Float' to an inout parameter requires explicit '&'}} {{4-4=&}} // Assignment operators x += x +++x var yi = y[i] // Non-settable lvalues var non_settable_x : X { return x } struct Z { var non_settable_x: X { get {} } var non_settable_reftype: Reftype { get {} } var settable_x : X subscript(i: Int) -> Double { get {} } subscript(_: (i: Int, j: Int)) -> X { get {} } } var z : Z func fz() -> Z {} func fref() -> Reftype {} // non-settable var is non-settable: // - assignment non_settable_x = x // expected-error{{cannot assign to value: 'non_settable_x' is a get-only property}} // - inout (mono) f2(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout (generic) f1(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout assignment non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} +++non_settable_x // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // non-settable property is non-settable: z.non_settable_x = x // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} +++z.non_settable_x // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // non-settable subscript is non-settable: z[0] = 0.0 // expected-error{{cannot assign through subscript: subscript is get-only}} f2(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} f1(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} z[0] += 0.0 // expected-error{{left side of mutating operator isn't mutable: subscript is get-only}} +++z[0] // expected-error{{cannot convert value of type 'Double' to expected argument type 'X'}} +++z[(i: 0, j: 0)] // expected-error{{cannot pass immutable value to mutating operator: subscript is get-only}} // settable property of an rvalue value type is non-settable: fz().settable_x = x // expected-error{{cannot assign to property: 'fz' returns immutable value}} f2(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} f1(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} fz().settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'fz' returns immutable value}} +++fz().settable_x // expected-error{{cannot pass immutable value to mutating operator: 'fz' returns immutable value}} // settable property of an rvalue reference type IS SETTABLE: fref().property = 0.0 f2(&fref().property) f1(&fref().property) fref().property += 0.0 fref().property += 1 // settable property of a non-settable value type is non-settable: z.non_settable_x.property = 1.0 // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x.property += 1.0 // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} +++z.non_settable_x.property // expected-error{{cannot convert value of type 'Double' to expected argument type 'X'}} // settable property of a non-settable reference type IS SETTABLE: z.non_settable_reftype.property = 1.0 f2(&z.non_settable_reftype.property) f1(&z.non_settable_reftype.property) z.non_settable_reftype.property += 1.0 z.non_settable_reftype.property += 1 // regressions with non-settable subscripts in value contexts _ = z[0] == 0 var d : Double d = z[0] // regressions with subscripts that return generic types var xs:[X] _ = xs[0].property struct A<T> { subscript(i: Int) -> T { get {} } } struct B { subscript(i: Int) -> Int { get {} } } var a:A<B> _ = a[0][0] // Instance members of struct metatypes. struct FooStruct { func instanceFunc0() {} } func testFooStruct() { FooStruct.instanceFunc0(FooStruct())() } // Don't load from explicit lvalues. func takesInt(_ x: Int) {} func testInOut(_ arg: inout Int) { var x : Int takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} } // Don't infer inout types. var ir = &i // expected-error {{'&' may only be used to pass an argument to inout parameter}} var ir2 = ((&i)) // expected-error {{'&' may only be used to pass an argument to inout parameter}} // <rdar://problem/17133089> func takeArrayRef(_ x: inout Array<String>) { } // rdar://22308291 takeArrayRef(["asdf", "1234"]) // expected-error{{cannot pass immutable value of type '[String]' as inout argument}} // <rdar://problem/19835413> Reference to value from array changed func rdar19835413() { func f1(_ p: UnsafeMutableRawPointer) {} func f2(_ a: [Int], i: Int, pi: UnsafeMutablePointer<Int>) { var a = a f1(&a) f1(&a[i]) f1(&a[0]) f1(pi) f1(pi) } } // <rdar://problem/21877598> Crash when accessing stored property without // setter from constructor protocol Radish { var root: Int { get } } public struct Kale : Radish { public let root : Int public init() { let _ = Kale().root self.root = 0 } } func testImmutableUnsafePointer(_ p: UnsafePointer<Int>) { p.pointee = 1 // expected-error {{cannot assign to property: 'pointee' is a get-only property}} p[0] = 1 // expected-error {{cannot assign through subscript: subscript is get-only}} } // <https://bugs.swift.org/browse/SR-7> Inferring closure param type to // inout crashes compiler let g = { x in f0(x) } // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{19-19=&}} // <rdar://problem/17245353> Crash with optional closure taking inout func rdar17245353() { typealias Fn = (inout Int) -> () func getFn() -> Fn? { return nil } let _: (inout UInt, UInt) -> Void = { $0 += $1 } } // <rdar://problem/23131768> Bugs related to closures with inout parameters func rdar23131768() { func f(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f { $0 += 1 } // Crashes compiler func f2(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f2 { $0 = $0 + 1 } // previously error: Cannot convert value of type '_ -> ()' to expected type '(inout Int) -> Void' func f3(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f3 { (v: inout Int) -> Void in v += 1 } } // <rdar://problem/23331567> Swift: Compiler crash related to closures with inout parameter. func r23331567(_ fn: (_ x: inout Int) -> Void) { var a = 0 fn(&a) } r23331567 { $0 += 1 } // <rdar://problem/30685195> Compiler crash with invalid assignment struct G<T> { subscript(x: Int) -> T { get { } nonmutating set { } } // expected-note@-1 {{'subscript(_:)' declared here}} } func wump<T>(to: T, _ body: (G<T>) -> ()) {} wump(to: 0, { $0[] = 0 }) // expected-error@-1 {{missing argument for parameter #1 in call}} // SR-13732 extension MutableCollection { public mutating func writePrefix<I: IteratorProtocol>(from source: inout I) -> (writtenCount: Int, afterLastWritten: Index) where I.Element == Element { fatalError() } public mutating func writePrefix<Source: Collection>(from source: Source) -> (writtenCount: Int, afterLastWritten: Index, afterLastRead: Source.Index) where Source.Element == Element { fatalError() } } func testWritePrefixIterator() { var a = Array(0..<10) var underflow = (1..<10).makeIterator() var (writtenCount, afterLastWritten) = a.writePrefix(from: underflow) // expected-error {{passing value of type 'IndexingIterator<(Range<Int>)>' to an inout parameter requires explicit '&'}} {{62-62=&}} } // rdar://problem/71356981 - wrong error message for state passed as inout with ampersand within parentheses func look_through_parens_when_checking_inout() { struct Point { var x: Int = 0 var y: Int = 0 } func modifyPoint(_ point: inout Point, _: Int = 42) {} func modifyPoint(_ point: inout Point, msg: String) {} func modifyPoint(source: inout Point) {} var point = Point(x: 0, y: 0) modifyPoint((&point)) // expected-error {{'&' may only be used to pass an argument to inout parameter}} {{16-17=(}} {{15-16=&}} modifyPoint(((&point))) // expected-error {{'&' may only be used to pass an argument to inout parameter}} {{17-18=(}} {{15-16=&}} modifyPoint(source: (&point)) // expected-error {{'&' may only be used to pass an argument to inout parameter}} {{24-25=(}} {{23-24=&}} modifyPoint(source: ((&point))) // expected-error {{'&' may only be used to pass an argument to inout parameter}} {{25-26=(}} {{23-24=&}} modifyPoint((&point), 0) // expected-error {{'&' may only be used to pass an argument to inout parameter}} {{16-17=(}} {{15-16=&}} modifyPoint((&point), msg: "") // expected-error {{'&' may only be used to pass an argument to inout parameter}} {{16-17=(}} {{15-16=&}} }
357a60ec7bd23726d16bd494acf11ae3
35.256944
204
0.666731
false
false
false
false
apple/swift-driver
refs/heads/main
Sources/SwiftDriver/Jobs/DarwinToolchain+LinkerSupport.swift
apache-2.0
1
//===--------------- DarwinToolchain+LinkerSupport.swift ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftOptions import struct TSCBasic.AbsolutePath import struct TSCBasic.RelativePath extension DarwinToolchain { internal func findXcodeClangPath() throws -> AbsolutePath? { let result = try executor.checkNonZeroExit( args: "xcrun", "-toolchain", "default", "-f", "clang", environment: env ).spm_chomp() return result.isEmpty ? nil : try AbsolutePath(validating: result) } internal func findXcodeClangLibPath(_ additionalPath: String) throws -> AbsolutePath? { let path = try getToolPath(.swiftCompiler) .parentDirectory // 'swift' .parentDirectory // 'bin' .appending(components: "lib", additionalPath) if fileSystem.exists(path) { return path } // If we don't have a 'lib/arc/' directory, find the "arclite" library // relative to the Clang in the active Xcode. if let clangPath = try? findXcodeClangPath() { return clangPath .parentDirectory // 'clang' .parentDirectory // 'bin' .appending(components: "lib", additionalPath) } return nil } internal func findARCLiteLibPath() throws -> AbsolutePath? { return try findXcodeClangLibPath("arc") } /// Adds the arguments necessary to link the files from the given set of /// options for a Darwin platform. public func addPlatformSpecificLinkerArgs( to commandLine: inout [Job.ArgTemplate], parsedOptions: inout ParsedOptions, linkerOutputType: LinkOutputType, inputs: [TypedVirtualPath], outputFile: VirtualPath, shouldUseInputFileList: Bool, lto: LTOKind?, sanitizers: Set<Sanitizer>, targetInfo: FrontendTargetInfo ) throws -> ResolvedTool { // Set up for linking. let linkerTool: Tool switch linkerOutputType { case .dynamicLibrary: // Same as an executable, but with the -dylib flag linkerTool = .dynamicLinker commandLine.appendFlag("-dynamiclib") addLinkInputs(shouldUseInputFileList: shouldUseInputFileList, commandLine: &commandLine, inputs: inputs, linkerOutputType: linkerOutputType) try addDynamicLinkerFlags(targetInfo: targetInfo, parsedOptions: &parsedOptions, commandLine: &commandLine, sanitizers: sanitizers, linkerOutputType: linkerOutputType, lto: lto) case .executable: linkerTool = .dynamicLinker addLinkInputs(shouldUseInputFileList: shouldUseInputFileList, commandLine: &commandLine, inputs: inputs, linkerOutputType: linkerOutputType) try addDynamicLinkerFlags(targetInfo: targetInfo, parsedOptions: &parsedOptions, commandLine: &commandLine, sanitizers: sanitizers, linkerOutputType: linkerOutputType, lto: lto) case .staticLibrary: linkerTool = .staticLinker(lto) commandLine.appendFlag(.static) addLinkInputs(shouldUseInputFileList: shouldUseInputFileList, commandLine: &commandLine, inputs: inputs, linkerOutputType: linkerOutputType) } // Add the output commandLine.appendFlag("-o") commandLine.appendPath(outputFile) return try resolvedTool(linkerTool) } private func addLinkInputs(shouldUseInputFileList: Bool, commandLine: inout [Job.ArgTemplate], inputs: [TypedVirtualPath], linkerOutputType: LinkOutputType) { // inputs LinkFileList if shouldUseInputFileList { commandLine.appendFlag(.filelist) var inputPaths = [VirtualPath]() var inputModules = [VirtualPath]() for input in inputs { if input.type == .swiftModule && linkerOutputType != .staticLibrary { inputPaths.append(input.file) inputModules.append(input.file) } else if input.type == .object { inputPaths.append(input.file) } else if input.type == .tbd { inputPaths.append(input.file) } else if input.type == .llvmBitcode { inputPaths.append(input.file) } } let fileList = VirtualPath.createUniqueFilelist(RelativePath("inputs.LinkFileList"), .list(inputPaths)) commandLine.appendPath(fileList) if linkerOutputType != .staticLibrary { for module in inputModules { commandLine.append(.joinedOptionAndPath("-Wl,-add_ast_path,", module)) } } // FIXME: Primary inputs need to check -index-file-path } else { // Add inputs. commandLine.append(contentsOf: inputs.flatMap { (path: TypedVirtualPath) -> [Job.ArgTemplate] in if path.type == .swiftModule && linkerOutputType != .staticLibrary { return [.joinedOptionAndPath("-Wl,-add_ast_path,", path.file)] } else if path.type == .object { return [.path(path.file)] } else if path.type == .tbd { return [.path(path.file)] } else if path.type == .llvmBitcode { return [.path(path.file)] } else { return [] } }) } } private func addDynamicLinkerFlags(targetInfo: FrontendTargetInfo, parsedOptions: inout ParsedOptions, commandLine: inout [Job.ArgTemplate], sanitizers: Set<Sanitizer>, linkerOutputType: LinkOutputType, lto: LTOKind?) throws { if let lto = lto { switch lto { case .llvmFull: commandLine.appendFlag("-flto=full") case .llvmThin: commandLine.appendFlag("-flto=thin") } if let arg = parsedOptions.getLastArgument(.ltoLibrary)?.asSingle { commandLine.append(.joinedOptionAndPath("-Wl,-lto_library,", try VirtualPath(path: arg))) } } if let arg = parsedOptions.getLastArgument(.useLd) { commandLine.appendFlag("-fuse-ld=\(arg.asSingle)") } let fSystemArgs = parsedOptions.arguments(for: .F, .Fsystem) for opt in fSystemArgs { commandLine.appendFlag(.F) commandLine.appendPath(try VirtualPath(path: opt.argument.asSingle)) } if parsedOptions.contains(.enableAppExtension) { commandLine.appendFlag("-fapplication-extension") } // Linking sanitizers will add rpaths, which might negatively interact when // other rpaths are involved, so we should make sure we add the rpaths after // all user-specified rpaths. if linkerOutputType == .executable && !sanitizers.isEmpty { let sanitizerNames = sanitizers .map { $0.rawValue } .sorted() // Sort so we get a stable, testable order .joined(separator: ",") commandLine.appendFlag("-fsanitize=\(sanitizerNames)") } if parsedOptions.contains(.embedBitcode) { commandLine.appendFlag("-fembed-bitcode") } else if parsedOptions.contains(.embedBitcodeMarker) { commandLine.appendFlag("-fembed-bitcode=marker") } // Add the SDK path if let sdkPath = targetInfo.sdkPath?.path { commandLine.appendFlag("--sysroot") commandLine.appendPath(VirtualPath.lookup(sdkPath)) } commandLine.appendFlags( "-fobjc-link-runtime", "-lobjc", "-lSystem" ) let targetTriple = targetInfo.target.triple commandLine.appendFlag("--target=\(targetTriple.triple)") if let variantTriple = targetInfo.targetVariant?.triple { assert(targetTriple.isValidForZipperingWithTriple(variantTriple)) commandLine.appendFlag("-darwin-target-variant=\(variantTriple.triple)") } // On Darwin, we only support libc++. if parsedOptions.contains(.enableExperimentalCxxInterop) { commandLine.appendFlag("-lc++") } try addArgsToLinkStdlib( to: &commandLine, parsedOptions: &parsedOptions, targetInfo: targetInfo, linkerOutputType: linkerOutputType, fileSystem: fileSystem ) if parsedOptions.hasArgument(.profileGenerate) { commandLine.appendFlag("-fprofile-generate") } // These custom arguments should be right before the object file at the // end. try commandLine.appendAllExcept( includeList: [.linkerOption], excludeList: [.l], from: &parsedOptions ) addLinkedLibArgs(to: &commandLine, parsedOptions: &parsedOptions) // Because we invoke `clang` as the linker executable, we must still // use `-Xlinker` for linker-specific arguments. for linkerOpt in parsedOptions.arguments(for: .Xlinker) { commandLine.appendFlag(.Xlinker) commandLine.appendFlag(linkerOpt.argument.asSingle) } try commandLine.appendAllArguments(.XclangLinker, from: &parsedOptions) } } private extension DarwinPlatform { var profileLibraryNameSuffixes: [String] { switch self { case .macOS, .iOS(.catalyst): return ["osx"] case .iOS(.device): return ["ios"] case .iOS(.simulator): return ["iossim", "ios"] case .tvOS(.device): return ["tvos"] case .tvOS(.simulator): return ["tvossim", "tvos"] case .watchOS(.device): return ["watchos"] case .watchOS(.simulator): return ["watchossim", "watchos"] } } }
ffcdef1978cfd6025195f596cd8c83a9
34.679577
97
0.61808
false
false
false
false
evgenyneu/Auk
refs/heads/master
Auk/Utils/AutoCancellingTimer.swift
mit
1
// // Creates a timer that executes code after delay. The timer lives in an instance of `AutoCancellingTimer` class and is automatically canceled when this instance is deallocated. // This is an auto-canceling alternative to timer created with `dispatch_after` function. // // Source: https://gist.github.com/evgenyneu/516f7dcdb5f2f73d7923 // // Usage // ----- // // class MyClass { // var timer: AutoCancellingTimer? // Timer will be cancelled with MyCall is deallocated // // func runTimer() { // timer = AutoCancellingTimer(interval: delaySeconds, repeats: true) { // ... code to run // } // } // } // // // Cancel the timer // -------------------- // // Timer is canceled automatically when it is deallocated. You can also cancel it manually: // // timer.cancel() // import UIKit final class AutoCancellingTimer { private var timer: AutoCancellingTimerInstance? init(interval: TimeInterval, repeats: Bool = false, callback: @escaping ()->()) { timer = AutoCancellingTimerInstance(interval: interval, repeats: repeats, callback: callback) } deinit { timer?.cancel() } func cancel() { timer?.cancel() } } final class AutoCancellingTimerInstance: NSObject { private let repeats: Bool private var timer: Timer? private var callback: ()->() init(interval: TimeInterval, repeats: Bool = false, callback: @escaping ()->()) { self.repeats = repeats self.callback = callback super.init() timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(AutoCancellingTimerInstance.timerFired(_:)), userInfo: nil, repeats: repeats) } func cancel() { timer?.invalidate() } @objc func timerFired(_ timer: Timer) { self.callback() if !repeats { cancel() } } }
9582bee586577e450d3a4cdf59e6725a
25.642857
177
0.64504
false
false
false
false
yichizhang/JCTiledScrollView
refs/heads/master
Demo-Swift/Demo-Swift/ViewController.swift
bsd-2-clause
1
// // ViewController.swift // Demo-Swift // // Created by Yichi on 13/12/2014. // Copyright (c) 2014 Yichi Zhang. All rights reserved. // import UIKit enum JCDemoType { case PDF case Image } let annotationReuseIdentifier = "JCAnnotationReuseIdentifier"; let SkippingGirlImageName = "SkippingGirl" let SkippingGirlImageSize = CGSizeMake(432, 648) class ViewController: UIViewController, JCTiledScrollViewDelegate, JCTileSource { var scrollView: JCTiledScrollView! var infoLabel: UILabel! var searchField: UITextField! var mode: JCDemoType! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if(mode == JCDemoType.PDF){ scrollView = JCTiledPDFScrollView(frame: self.view.bounds, URL: NSBundle.mainBundle().URLForResource("Map", withExtension: "pdf")) }else{ scrollView = JCTiledScrollView(frame: self.view.bounds, contentSize: SkippingGirlImageSize); } scrollView.tiledScrollViewDelegate = self scrollView.dataSource = self; scrollView.tiledScrollViewDelegate = self; scrollView.tiledView.shouldAnnotateRect = true; // totals 4 sets of tiles across all devices, retina devices will miss out on the first 1x set scrollView.levelsOfZoom = 3; scrollView.levelsOfDetail = 3; view.addSubview(scrollView) let paddingX:CGFloat = 20; let paddingY:CGFloat = 30; infoLabel = UILabel(frame: CGRectMake(paddingX, paddingY, self.view.bounds.size.width - 2*paddingX, 30)); infoLabel.backgroundColor = UIColor.blackColor() infoLabel.textColor = UIColor.whiteColor() infoLabel.textAlignment = NSTextAlignment.Center view.addSubview(infoLabel) addRandomAnnotations() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) scrollView.zoomScale = 1.01 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addRandomAnnotations() { for index in 0...4 { let a:JCAnnotation = DemoAnnotation(); a.contentPosition = CGPointMake( //This is ridiculous!! Hahaha CGFloat(UInt(arc4random_uniform(UInt32(UInt(scrollView.tiledView.bounds.width))))), CGFloat(UInt(arc4random_uniform(UInt32(UInt(scrollView.tiledView.bounds.height))))) ); scrollView.addAnnotation(a); } } func tiledScrollViewDidZoom(scrollView: JCTiledScrollView!) { let infoString = "zoomScale=\(scrollView.zoomScale)" infoLabel.text = infoString } func tiledScrollView(scrollView: JCTiledScrollView!, didReceiveSingleTap gestureRecognizer: UIGestureRecognizer!) { let tapPoint:CGPoint = gestureRecognizer.locationInView(scrollView.tiledView) //Doesn't work!!! //let infoString:String = String(format: "zoomScale: %0.2f, x: %0.0f y: %0.0f", scrollView.zoomScale, tapPoint.x, tapPoint.y) let infoString = "(\(tapPoint.x), \(tapPoint.y)), zoomScale=\(scrollView.zoomScale)" infoLabel.text = infoString } func tiledScrollView(scrollView: JCTiledScrollView!, viewForAnnotation annotation: JCAnnotation!) -> JCAnnotationView! { var view:DemoAnnotationView? = scrollView.dequeueReusableAnnotationViewWithReuseIdentifier(annotationReuseIdentifier) as? DemoAnnotationView; if ( (view) == nil ) { view = DemoAnnotationView(frame:CGRectZero, annotation:annotation, reuseIdentifier:"Identifier"); view!.imageView.image = UIImage(named: "marker-red.png"); view!.sizeToFit(); } return view; } func tiledScrollView(scrollView: JCTiledScrollView!, imageForRow row: Int, column: Int, scale: Int) -> UIImage! { let fileName:String = "\(SkippingGirlImageName)_\(scale)x_\(row)_\(column).png"; print(fileName); return UIImage(named: fileName) /* It's been doing weird stuff!!! SkippingGirl_8x_17_10.png SkippingGirl_8x_13_11.png SkippingGirl_8x_13_11.png SkippingGirl_8x_13_9.png SkippingGirl_8x_13_9.png SSkkiippppiinnggGGiirrll__88xx__1165__88..ppnngg SkippingGirl_8x_17_9.png SkippingGirl_8x_17_9.png SkippingGirl_8x_17_8.png SkippingGirl_8x_14_8.png SSkkiippppiinnggGGiirrll__88xx__1167__77..ppnngg SkippingGirl_8x_15_7.png SkippingGirl_8x_15_7.png SSkkippingGirl_8x_18_8.png ippingGirl_8x_18_7.png SSkkiippppiinnggGGiirrll__88xx__1187__66..ppnngg SSkkiippppiinnggGGiirrll__88xx__1165__66..ppnngg SSkkiippppiinnggGGiirrll__88xx__1178__55..ppnngg */ } }
692b11dc07e4d11f4e7a2e8120c0ebc8
28.852349
143
0.736286
false
false
false
false
pjcau/LocalNotifications_Over_iOS10
refs/heads/master
LocalNotifications_Over_iOS10/NotificationManager/NotificationManager.swift
mit
1
// // NotificationManager.swift // iOS10_LocalNotifications // // Created by Cau Pierre Jonny on 2017-09-26. // Copyright © 2017 Cau Pierre Jonny . All rights reserved. // import Foundation import UserNotifications import CoreLocation import UIKit import SwiftDate public protocol NotificationManagerDelegate: class { @available(iOS 10.0, *) func userNotificationManager(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) @available(iOS 10.0, *) func userNotificationManager(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) } @objc public class NotificationManager: NSObject { weak var delegate: NotificationManagerDelegate? private static let singletonInstance = { return NotificationManager() }() @objc public static func shared() -> NotificationManager { if #available(iOS 10.0, *) { if UNUserNotificationCenter.current().delegate == nil { UNUserNotificationCenter.current().delegate = NotificationManager.singletonInstance } } else { // Fallback on earlier versions } return NotificationManager.singletonInstance } public override init() { //This prevents others from using the default '()' initializer for this class. } // MARK: Public @objc public func setDelegate(_ object:AnyObject) { if #available(iOS 10.0, *) { delegate = object as? NotificationManagerDelegate } } public func getDelegate() -> NotificationManagerDelegate? { if let delegate = delegate { if #available(iOS 10.0, *) { return delegate } } return nil } @objc public func scheduleNotification(notificationObj notificationObject:NotificationObject) { if #available(iOS 10.0, *) { NotificationManager.shared().scheduleUNUserNotification(notificationObj:notificationObject) } else { NotificationManager.shared().scheduleUILocalNotification(body: notificationObject.body) } } @available(iOS 10.0, *) @objc public func requestAuthorization(completion: ((_ granted: Bool) -> Void)? = nil) { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted, _) in if granted { completion?(true) } else { center.getNotificationSettings(completionHandler: { settings in if settings.authorizationStatus != .authorized { //User has not authorized notifications } if settings.lockScreenSetting != .enabled { //User has either disabled notifications on the lock screen for this app or it is not supported } completion?(false) }) } } } @available(iOS 10.0, *) @objc public func setupCategories(_ categories: Set<UNNotificationCategory>) { let center = UNUserNotificationCenter.current() center.setNotificationCategories(categories) } @available(iOS 10.0, *) @objc public func getNotificationSettings(completion: ((_ value: UNAuthorizationStatus) -> Void)? = nil) { let center = UNUserNotificationCenter.current() center.getNotificationSettings { (settings) in completion?(settings.authorizationStatus) } } @available(iOS 10.0, *) @objc public func pending(completion: @escaping (_ pendingCount: [UNNotificationRequest]) -> Void) { UNUserNotificationCenter.current().getPendingNotificationRequests { requests in completion(requests) } } @available(iOS 10.0, *) @objc public func delivered(completion: @escaping (_ deliveredCount: [UNNotification]) -> Void) { UNUserNotificationCenter.current().getDeliveredNotifications { notifications in completion(notifications) } } @available(iOS 10.0, *) @objc public func removePending(withIdentifiers identifiers: [String]) { UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers) } @available(iOS 10.0, *) @objc public func removeAllPending() { UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } @available(iOS 10.0, *) @objc public func removeDelivery(withIdentifiers identifiers: [String]) { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiers) } @available(iOS 10.0, *) @objc public func removeAlldelivery() { UNUserNotificationCenter.current().removeAllDeliveredNotifications() } @available(iOS 10.0, *) @objc public func checkStatus() { } @available(iOS 10.0, *) @objc public func action(id: String, title: String, options: UNNotificationActionOptions = []) -> UNNotificationAction { let action = UNNotificationAction(identifier: id, title: title, options: options) return action } @available(iOS 10.0, *) @objc public func category(identifier: String, action:[UNNotificationAction], intentIdentifiers: [String], options: UNNotificationCategoryOptions = []) -> UNNotificationCategory { let category = UNNotificationCategory(identifier: identifier, actions: action, intentIdentifiers: intentIdentifiers, options: options) return category } // MARK: Private @available(iOS 10.0, *) private func scheduleUNUserNotification(notificationObj:NotificationObject) { requestAuthorization { _ in var content = NotificationManager.shared().createNotificationContent(notificationObj: notificationObj) let trigger = NotificationManager.shared().calendarNotificationTrigger(notificationObj.notification, notificationObj.date,notificationObj.repeats) content = NotificationManager.shared().customCategory(notificationObj, content) let request = UNNotificationRequest(identifier: notificationObj.id, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in // Use this block to determine if the notification request was added successfully. if error == nil { Logger.log(message: "Notification scheduled", event: .info) } else { Logger.log(message: "Error scheduling notification", event: .info) } } } } @available(iOS 10.0, *) private func createNotificationContent(notificationObj:NotificationObject) -> UNMutableNotificationContent { let content = UNMutableNotificationContent() content.title = notificationObj.title content.subtitle = notificationObj.subtitle content.body = notificationObj.body content.sound = UNNotificationSound.default() content.badge = notificationObj.badgeCount content.userInfo = notificationObj.userInfo if let attachementFiles = notificationObj.attachment { content.attachments = attachementFiles as! [UNNotificationAttachment] } return content } // MARK: iOS 9 UILocalNotification support private func scheduleUILocalNotification(body: String) { let localNotification = UILocalNotification() localNotification.fireDate = Date().addingTimeInterval(1) localNotification.alertBody = body localNotification.timeZone = TimeZone.current UIApplication.shared.scheduleLocalNotification(localNotification) } // MARK: Sample triggers @available(iOS 10.0, *) private func createTimeIntervalNotificationTrigger() -> UNTimeIntervalNotificationTrigger { return UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) } @available(iOS 10.0, *) private func calendarNotificationTrigger(_ notificationType:NotificationType, _ date:Date, _ repeatDate:Repeats) -> UNCalendarNotificationTrigger? { var repeatBool:Bool = false var triggerDate :DateComponents? = nil var updateDate = date switch notificationType { case .twoWeekReminderType: updateDate = updateDate + 2.week case .slideShowWillExpiredType: updateDate = updateDate + 2.day - 3.hour default: break } if repeatDate != .none { repeatBool = true switch repeatDate { case .minutely: triggerDate = Calendar.current.dateComponents([.second], from: updateDate) case .hourly: triggerDate = Calendar.current.dateComponents([.minute,.second], from: updateDate) case .daily: triggerDate = Calendar.current.dateComponents([.hour,.minute,.second], from: updateDate) case .weekly: triggerDate = Calendar.current.dateComponents([.day,.hour,.minute,.second], from: updateDate) case .monthly: triggerDate = Calendar.current.dateComponents([.weekday,.day,.hour,.minute,.second], from: updateDate) case .yearly: triggerDate = Calendar.current.dateComponents([.month,.weekday, .day,.hour,.minute,.second], from: updateDate) default: break } return UNCalendarNotificationTrigger(dateMatching: triggerDate!, repeats: repeatBool) } else { let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: updateDate) return UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: repeatBool) } } @available(iOS 10.0, *) private func customCategory( _ notificationObj:NotificationObject , _ content : UNMutableNotificationContent ) -> UNMutableNotificationContent { if let name = notificationObj.mediaUrl, let media = notificationObj.media, let url = NotificationHelper.saveImage(name: name,path: notificationObj.mediaPath ) { Logger.log(message: "url is \(url)", event: .info) let attachment = try? UNNotificationAttachment(identifier: media, url: url, options: [:]) if let attachment = attachment { content.attachments.removeAll(keepingCapacity: true) content.attachments.append(attachment) } } content.categoryIdentifier = notificationObj.categoryType return content } @available(iOS 10.0, *) private func createLocationNotificationTrigger() -> UNLocationNotificationTrigger { let cynnyOfficeRegion = CLCircularRegion(center: CLLocationCoordinate2D(latitude:43.7825, longitude: 11.2594), radius: 10, identifier: "Cynny") cynnyOfficeRegion.notifyOnEntry = true cynnyOfficeRegion.notifyOnExit = true return UNLocationNotificationTrigger(region: cynnyOfficeRegion, repeats: true) } } extension String { var length: Int { return self.count } } extension NotificationManager: UNUserNotificationCenterDelegate { @available(iOS 10.0, *) public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { if let delegate = delegate { delegate.userNotificationManager(center, didReceive: response, withCompletionHandler: completionHandler) return } } @available(iOS 10.0, *) public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { if let delegate = delegate { delegate.userNotificationManager(center, willPresent: notification, withCompletionHandler: completionHandler) return } completionHandler( [.alert, .badge, .sound]) } }
5d5fd6ceb3302e1611d357e3b8e1e944
37.786164
214
0.668964
false
false
false
false
jamy0801/LGWeChatKit
refs/heads/master
LGWeChatKit/LGChatKit/conversion/video/LGAVPlayView.swift
mit
1
// // LGAVPlayView.swift // player // // Created by jamy on 11/4/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit import AVFoundation @IBDesignable class LGAVPlayView: UIView { var playView: UIView! var slider: UISlider! var timerIndicator: UILabel! // MARK: - lifecycle override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } deinit { NSLog("deinit") } func setup() { backgroundColor = UIColor.blackColor() playView = UIView() slider = UISlider() slider.setThumbImage(UIImage.imageWithColor(UIColor.redColor()), forState: .Normal) timerIndicator = UILabel() timerIndicator.font = UIFont.systemFontOfSize(12.0) timerIndicator.textColor = UIColor.whiteColor() addSubview(playView) addSubview(slider) addSubview(timerIndicator) playView.translatesAutoresizingMaskIntoConstraints = false slider.translatesAutoresizingMaskIntoConstraints = false timerIndicator.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: playView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: playView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: playView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: playView, attribute: .Bottom, relatedBy: .Equal, toItem: slider, attribute: .Top, multiplier: 1, constant: -5)) addConstraint(NSLayoutConstraint(item: slider, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 10)) addConstraint(NSLayoutConstraint(item: slider, attribute: .Right, relatedBy: .Equal, toItem: timerIndicator, attribute: .Left, multiplier: 1, constant: -5)) addConstraint(NSLayoutConstraint(item: slider, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: -5)) addConstraint(NSLayoutConstraint(item: timerIndicator, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: -5)) addConstraint(NSLayoutConstraint(item: timerIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: slider, attribute: .CenterY, multiplier: 1, constant: 0)) } override class func layerClass() -> AnyClass { return AVPlayerLayer.self } }
b2edf4db6698607d82f2960e10319855
39.5
168
0.674074
false
false
false
false
zhangao0086/DKImageBrowserVC
refs/heads/develop
DKPhotoGallery/Preview/DKPhotoProgressIndicator.swift
mit
2
// // DKPhotoProgressIndicator.swift // DKPhotoGallery // // Created by ZhangAo on 08/09/2017. // Copyright © 2017 ZhangAo. All rights reserved. // import UIKit class DKPhotoProgressIndicator: UIView, DKPhotoProgressIndicatorProtocol { private var progress: Float = 0 required init(with view: UIView) { super.init(frame: view.bounds) view.addSubview(self) self.isHidden = true self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } let lineWidth = CGFloat(2.0) let circleDiameter = CGFloat(37) let circleRect = CGRect(x: (self.bounds.width - circleDiameter) / 2, y: (self.bounds.height - circleDiameter) / 2, width: circleDiameter, height: circleDiameter) UIColor.white.setStroke() context.setLineWidth(lineWidth) context.strokeEllipse(in: circleRect) let processPath = UIBezierPath() processPath.lineCapStyle = .butt processPath.lineWidth = lineWidth * 2 let radius = circleDiameter / 2 - lineWidth / 2 let startAngle = -CGFloat.pi / 2.0 let endAngle = CGFloat(self.progress) * CGFloat(2.0) * CGFloat.pi + startAngle let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) processPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) context.setBlendMode(.copy) UIColor.white.set() processPath.stroke() } // MARK: - DKPhotoProgressIndicatorProtocol func startIndicator() { self.progress = 0 self.isHidden = false } func stopIndicator() { self.isHidden = true } func setIndicatorProgress(_ progress: Float) { self.progress = progress self.setNeedsDisplay() } }
e7822bffb4cb687a1f43e6025ba2a13b
27.766234
123
0.590971
false
false
false
false
cxpyear/SPDBDemo
refs/heads/master
spdbapp/spdbapp/Classes/Controller/DocViewController.swift
bsd-3-clause
1
// // DocViewController.swift // spdbapp // // Created by tommy on 15/5/8. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit import Alamofire class DocViewController: UIViewController,UIWebViewDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate, UIScrollViewDelegate, UIAlertViewDelegate { @IBOutlet weak var middleView: UIView! @IBOutlet weak var btnLeftBottom: UIButton! @IBOutlet weak var btnRightBottom: UIButton! @IBOutlet weak var topView: UIView! @IBOutlet weak var txtShowTotalPage: UITextField! @IBOutlet weak var txtShowCurrentPape: UITextField! @IBOutlet weak var btnPrevious: UIButton! @IBOutlet weak var btnAfter: UIButton! var isScreenLocked: Bool = false var fileIDInfo: String? var fileNameInfo: String? var timer = Poller() var topBarView = TopbarView() var bottomBarView = BottomBarView() var totalPage = 0 var currentPage = 0 // var docPath = String() @IBOutlet weak var docView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // docPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(fileIDInfo!).pdf") loadLocalPDFFile() totalPage = initfile() topBarView = TopbarView.getTopBarView(self) topBarView.backgroundColor = UIColor.clearColor() self.view.addSubview(topBarView) bottomBarView = BottomBarView().getBottomInstance(self) self.view.addSubview(bottomBarView) txtShowCurrentPape.delegate = self txtShowTotalPage.text = "共\(totalPage)页" self.currentPage = 1 self.docView.scrollView.delegate = self var tapGesture = UITapGestureRecognizer(target: self, action: "hideOrShowBottomBar:") tapGesture.cancelsTouchesInView = false self.view.addGestureRecognizer(tapGesture) } // override func viewWillAppear(animated: Bool) { // super.viewWillAppear(animated) // NSNotificationCenter.defaultCenter().addObserver(self, selector: "backToMainVC", name: HistoryInfoDidDeleteNotification, object: nil) // } // // func backToMainVC(){ // var storyBoard = UIStoryboard(name: "Main", bundle: nil) // var registerVC = storyBoard.instantiateViewControllerWithIdentifier("view") as! RegisViewController // self.presentViewController(registerVC, animated: true, completion: nil) // } // // override func viewWillDisappear(animated: Bool) { // super.viewWillDisappear(animated) // NSNotificationCenter.defaultCenter().removeObserver(self, name: HistoryInfoDidDeleteNotification, object: nil) // } func helpClick(){ var newVC = NewFeatureViewController() self.presentViewController(newVC, animated: true, completion: nil) } func shareClick(){ var shareVC = ShareViewController() self.presentViewController(shareVC, animated: true, completion: nil) } func backClick(){ self.dismissViewControllerAnimated(true, completion: nil) } func hideOrShowBottomBar(gesture: UITapGestureRecognizer){ self.bottomBarView.hidden = !self.bottomBarView.hidden } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == self.txtShowCurrentPape{ self.txtShowCurrentPape.endEditing(true) } return false } func textFieldDidEndEditing(textField: UITextField){ if textField == self.txtShowCurrentPape{ if textField.text.isEmpty{ return } var value = self.txtShowCurrentPape.text var temp = String(value) var page = temp.toInt()! if page <= 0{ return } skipToPage(page) currentPage = page } } /** 跳转到pdf指定的页码 :param: num 指定的pdf跳转页码位置 */ func skipToPage(num: Int){ var totalPDFheight = docView.scrollView.contentSize.height var pageHeight = CGFloat(totalPDFheight / CGFloat(totalPage)) var specificPageNo = num if specificPageNo <= totalPage{ var value2 = CGFloat(pageHeight * CGFloat(specificPageNo - 1)) var offsetPage = CGPointMake(0, value2) docView.scrollView.setContentOffset(offsetPage, animated: true) } println("currentpage = \(currentPage)") } /** 跳转到pdf文档第一页 */ @IBAction func btnToFirstPageClick(sender: UIButton) { skipToPage(1) currentPage = 1 self.txtShowCurrentPape.text = String(currentPage) } /** 跳转到pdf文档最后一页 */ @IBAction func btnToLastPageClick(sender: UIButton) { skipToPage(totalPage) currentPage = totalPage self.txtShowCurrentPape.text = String(currentPage) } /** 跳转到pdf文档下一页 */ @IBAction func btnToNextPageClick(sender: UIButton) { if currentPage < totalPage { ++currentPage skipToPage(currentPage) self.txtShowCurrentPape.text = String(currentPage) } } /** 跳转到pdf文档上一页 */ @IBAction func btnToPreviousPageClick(sender: UIButton) { if currentPage > 1 { --currentPage skipToPage(currentPage) self.txtShowCurrentPape.text = String(currentPage) } println("==============1") } func autoHideBottomBarView(timer: NSTimer){ if self.bottomBarView.hidden == false{ self.bottomBarView.hidden = true } } /** 返回当前pdf文件的总页数 :returns: 当前pdf文档总页数 */ func initfile() -> Int { var dataPathFromApp = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(fileIDInfo!).pdf") var path: CFString = CFStringCreateWithCString(nil, dataPathFromApp, CFStringEncoding(CFStringBuiltInEncodings.UTF8.rawValue)) var url: CFURLRef = CFURLCreateWithFileSystemPath(nil , path, CFURLPathStyle.CFURLPOSIXPathStyle, 0) if let document = CGPDFDocumentCreateWithURL(url){ var totalPages = CGPDFDocumentGetNumberOfPages(document) return totalPages }else{ self.docView.hidden = true self.topView.hidden = true UIAlertView(title: "提示", message: "当前服务器中不存在该文件", delegate: self, cancelButtonTitle: "确定").show() return 0 } } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { self.dismissViewControllerAnimated(true, completion: nil) } func scrollViewDidScroll(scrollView: UIScrollView){ var pdfHeight = scrollView.contentSize.height var onePageHeight = pdfHeight / CGFloat(totalPage) var page = (scrollView.contentOffset.y) / onePageHeight var p = Int(page + 0.5) self.txtShowCurrentPape.text = "\(p + 1)" } override func prefersStatusBarHidden() -> Bool { return true } //加锁 @IBAction func addLock(sender: UIButton) { self.isScreenLocked = !self.isScreenLocked var imageName = (self.isScreenLocked == true) ? "Lock-50" : "Unlock-50" sender.setBackgroundImage(UIImage(named: imageName), forState: UIControlState.Normal) topBarView.lblIsLocked.text = (self.isScreenLocked == true) ? "当前屏幕已锁定" : "" } override func shouldAutorotate() -> Bool { return !self.isScreenLocked } /** 加载当前pdf文档 */ func loadLocalPDFFile(){ var filePath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(self.fileIDInfo!).pdf") var urlString = NSURL(fileURLWithPath: "\(filePath)") var request = NSURLRequest(URL: urlString!) self.docView.loadRequest(request) skipToPage(1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
097f2d684929db4b7335b0cefd2cf300
29.464945
154
0.626575
false
false
false
false
CodaFi/swift
refs/heads/master
test/SILGen/default_arguments_inherited.swift
apache-2.0
21
// RUN: %target-swift-emit-silgen %s | %FileCheck %s // When we synthesize an inherited designated initializer, the default // arguments are still conceptually rooted on the base declaration. // When we call such an initializer, we have to construct substitutions // in terms of the base class generic signature, rather than the // derived class generic signature. class Puppy<T, U> { init(t: T? = nil, u: U? = nil) {} } class Chipmunk : Puppy<Int, String> {} class Kitten<V> : Puppy<Int, V> {} class Goldfish<T> { class Shark<U> : Puppy<T, U> {} } // CHECK-LABEL: sil hidden [ossa] @$s27default_arguments_inherited4doItyyF : $@convention(thin) () -> () { func doIt() { // CHECK: [[ARG1:%.*]] = function_ref @$s27default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA_ // CHECK: apply [[ARG1]]<Int, String>({{.*}}) // CHECK: [[ARG2:%.*]] = function_ref @$s27default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA0_ // CHECK: apply [[ARG2]]<Int, String>({{.*}}) _ = Chipmunk() // CHECK: [[ARG1:%.*]] = function_ref @$s27default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA_ // CHECK: apply [[ARG1]]<Int, String>(%{{.*}}) // CHECK: [[ARG2:%.*]] = function_ref @$s27default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA0_ // CHECK: apply [[ARG2]]<Int, String>(%{{.*}}) _ = Kitten<String>() // CHECK: [[ARG1:%.*]] = function_ref @$s27default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA_ // CHECK: apply [[ARG1]]<String, Int>(%{{.*}}) // CHECK: [[ARG2:%.*]] = function_ref @$s27default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA0_ // CHECK: apply [[ARG2]]<String, Int>(%{{.*}}) _ = Goldfish<String>.Shark<Int>() }
e347a5fde3e261091c90eb41c6fa42f5
41.275
106
0.659373
false
false
false
false
PayPal-Opportunity-Hack-Chennai-2015/No-Food-Waste
refs/heads/master
ios/NoFoodWaster/NoFoodWaster/ConfirmationViewController.swift
apache-2.0
2
// // ConfirmationViewController.swift // NoFoodWaste // // Created by Ravi Shankar on 29/11/15. // Copyright © 2015 Ravi Shankar. All rights reserved. // import UIKit class ConfirmationViewController: UIViewController { @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var donationDetails: UILabel! @IBOutlet weak var deliveryDetails: UILabel! @IBOutlet weak var volunteerDetails: UILabel! @IBOutlet weak var donationTextView: UITextView! @IBOutlet weak var deliveryTextView: UITextView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var containerView: UIView! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Confirmation" applyStyle() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.navigationItem.setHidesBackButton(true, animated: false) navigationItem.title = "" let barButtonItem = UIBarButtonItem.init(title: "Home", style: .Done, target: self, action: "callHome") self.navigationItem.leftBarButtonItem = barButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func deliver(sender: AnyObject) { } func applyStyle() { descriptionLabel.backgroundColor = backgroundColor view.backgroundColor = backgroundColor donationDetails.backgroundColor = backgroundColor deliveryDetails.backgroundColor = backgroundColor volunteerDetails.backgroundColor = backgroundColor donationTextView.backgroundColor = backgroundColor deliveryTextView.backgroundColor = backgroundColor nameLabel.backgroundColor = backgroundColor phoneLabel.backgroundColor = backgroundColor containerView.backgroundColor = backgroundColor } func callHome() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewControllerWithIdentifier("MainViewController") navigationController?.pushViewController(controller, animated: true) } }
890a35060b3044a6e1e40c149128df8b
29.240506
111
0.673922
false
false
false
false
rnystrom/GitHawk
refs/heads/master
Classes/Issues/Commit/IssueCommitCell.swift
mit
1
// // IssueCommitCell.swift // Freetime // // Created by Ryan Nystrom on 7/26/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit import SDWebImage protocol IssueCommitCellDelegate: class { func didTapAvatar(cell: IssueCommitCell) } final class IssueCommitCell: UICollectionViewCell { weak var delegate: IssueCommitCellDelegate? private let commitImageView = UIImageView(image: UIImage(named: "git-commit-small").withRenderingMode(.alwaysTemplate)) private let avatarImageView = UIImageView() private let messageLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) isAccessibilityElement = true accessibilityTraits = UIAccessibilityTraitButton commitImageView.contentMode = .scaleAspectFit commitImageView.tintColor = Styles.Colors.Gray.light.color contentView.addSubview(commitImageView) commitImageView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalToSuperview() make.size.equalTo(Styles.Sizes.icon) } avatarImageView.contentMode = .scaleAspectFill avatarImageView.backgroundColor = Styles.Colors.Gray.lighter.color avatarImageView.layer.cornerRadius = Styles.Sizes.avatarCornerRadius avatarImageView.layer.borderColor = Styles.Colors.Gray.light.color.cgColor avatarImageView.layer.borderWidth = 1.0 / UIScreen.main.scale avatarImageView.clipsToBounds = true avatarImageView.isUserInteractionEnabled = true avatarImageView.addGestureRecognizer(UITapGestureRecognizer( target: self, action: #selector(IssueCommitCell.onAvatar)) ) avatarImageView.accessibilityIgnoresInvertColors = true contentView.addSubview(avatarImageView) avatarImageView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalTo(commitImageView.snp.right).offset(Styles.Sizes.columnSpacing) make.size.equalTo(Styles.Sizes.icon) } messageLabel.backgroundColor = .clear messageLabel.font = Styles.Text.secondaryCode.preferredFont messageLabel.textColor = Styles.Colors.Gray.medium.color contentView.addSubview(messageLabel) messageLabel.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalTo(avatarImageView.snp.right).offset(Styles.Sizes.columnSpacing) make.right.lessThanOrEqualToSuperview() } // always collapse and truncate messageLabel.lineBreakMode = .byTruncatingMiddle messageLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentView() } // MARK: Public API func configure(_ model: IssueCommitModel) { avatarImageView.sd_setImage(with: model.avatarURL) messageLabel.text = model.message let labelFormat = NSLocalizedString("%@ committed \"%@\"", comment: "") accessibilityLabel = String(format: labelFormat, arguments: [model.login, model.message]) } // MARK: Private API @objc func onAvatar() { delegate?.didTapAvatar(cell: self) } }
15ea4a73fb4657802a108a835da87ae1
34.191919
123
0.698622
false
false
false
false
mattwelborn/HSTracker
refs/heads/master
HSTracker/Logging/Enums/PlayState.swift
mit
1
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 19/02/16. */ import Foundation enum PlayState: Int { case INVALID = 0, PLAYING = 1, WINNING = 2, LOSING = 3, WON = 4, LOST = 5, TIED = 6, DISCONNECTED = 7, CONCEDED = 8 init?(rawString: String) { for _enum in PlayState.allValues() { if "\(_enum)" == rawString { self = _enum return } } if let value = Int(rawString), _enum = PlayState(rawValue: value) { self = _enum return } self = .INVALID } static func allValues() -> [PlayState] { return [.INVALID, .PLAYING, .WINNING, .LOSING, .WON, .LOST, .TIED, .DISCONNECTED, .CONCEDED] } }
f66af1180bf8960732faf3d6a46b8711
22.439024
100
0.548387
false
false
false
false
lojals/curiosity_reader
refs/heads/master
curiosity_reader/curiosity_reader/src/components/QuestionComponent.swift
gpl-2.0
1
// // QuestionComponent.swift // curiosity_reader // // Created by Jorge Raul Ovalle Zuleta on 5/17/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit @objc protocol QuestionComponentDelegate{ optional func tapInQuestion() } class QuestionComponent: UIView { var tapGesture:UITapGestureRecognizer! var delegate:QuestionComponentDelegate! var question:UILabel! var arrow:UIImageView! var answers:UILabel! var data:JSON! init(frame: CGRect, data:JSON) { super.init(frame: frame) self.data = data self.layer.borderColor = UIColor.themeGreyMedium().CGColor self.layer.borderWidth = 0.5 tapGesture = UITapGestureRecognizer(target: self, action: Selector("goToQuesiton:")) self.addGestureRecognizer(tapGesture) arrow = UIImageView(image: UIImage(named: "arrow")) arrow.center = CGPoint(x: frame.width - 30, y: frame.height/2) self.addSubview(arrow) var src = "¿Abrahams era el adecuado para dirigir episodio VII?" question = UILabel(frame: CGRectMake(24, 15, frame.width - 81, heightForView(src, font: UIFont.fontRegular(17.5), width: frame.width - 81))) question.font = UIFont.fontRegular(17.5) question.text = src question.numberOfLines = 0 question.textAlignment = NSTextAlignment.Left question.textColor = UIColor.blackColor() self.addSubview(question) var answers_logo = UIImageView(image: UIImage(named: "iconAns")) answers_logo.center = CGPoint(x: 30, y: frame.height-16) self.addSubview(answers_logo) answers = UILabel(frame: CGRectMake(answers_logo.frame.maxX + 5, 0, 100, 13)) answers.textColor = UIColor.themeGreyDark() answers.font = UIFont.fontRegular(13) answers.center.y = answers_logo.center.y answers.text = "72" self.addSubview(answers) } func goToQuesiton(sender:UIView){ delegate.tapInQuestion!() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{ let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.font = font label.text = text label.sizeToFit() return label.frame.height } }
40bbfb876f88e46adf855952d1b090ab
32.736842
148
0.646646
false
false
false
false
justinsandhu/myChat
refs/heads/master
Firechat/SwiftCrypter.swift
mit
1
// // SwiftCrypter.swift // Firechat // // Created by Justin Sandhu on 6/25/14. // Copyright (c) 2014 Firebase. All rights reserved. // import Foundation class Swyfter { func scramble(scrambleMessage message: String, withKey key: Int) -> Int[] { var numericMesssage = Int[]() var scambledMesssage = Int[]() for codeUnit in message.utf8 { numericMesssage += Int(codeUnit) } var newNumber:Int for number in numericMesssage { newNumber = number * key scambledMesssage += newNumber } return scambledMesssage } }
9a47f2e0506d2f6f9dbeae9f9c1687ce
15.52381
79
0.540346
false
false
false
false
piwik/piwik-sdk-ios
refs/heads/develop
Example/ios/iOS Example/UserDefaultsQueue.swift
mit
1
import Foundation import MatomoTracker public final class UserDefaultsQueue: NSObject, Queue { private var items: [Event] { didSet { if autoSave { try? UserDefaultsQueue.write(items, to: userDefaults) } } } private let userDefaults: UserDefaults private let autoSave: Bool init(_ userDefaults: UserDefaults, autoSave: Bool = false) { self.userDefaults = userDefaults self.autoSave = autoSave self.items = (try? UserDefaultsQueue.readEvents(from: userDefaults)) ?? [] super.init() } public var eventCount: Int { return items.count } public func enqueue(events: [Event], completion: (()->())?) { items.append(contentsOf: events) completion?() } public func first(limit: Int, completion: (_ items: [Event])->()) { let amount = [limit,eventCount].min()! let dequeuedItems = Array(items[0..<amount]) completion(dequeuedItems) } public func remove(events: [Event], completion: ()->()) { items = items.filter({ event in !events.contains(where: { eventToRemove in eventToRemove.uuid == event.uuid })}) completion() } public func save() throws { try UserDefaultsQueue.write(items, to: userDefaults) } } extension UserDefaultsQueue { private static let userDefaultsKey = "UserDefaultsQueue.items" private static func readEvents(from userDefaults: UserDefaults) throws -> [Event] { guard let data = userDefaults.data(forKey: userDefaultsKey) else { return [] } let decoder = JSONDecoder() return try decoder.decode([Event].self, from: data) } private static func write(_ events: [Event], to userDefaults: UserDefaults) throws { let encoder = JSONEncoder() let data = try encoder.encode(events) userDefaults.set(data, forKey: userDefaultsKey) } }
3639215068fa53125de63e6568e9c6c6
30.412698
120
0.619505
false
false
false
false
FTChinese/iPhoneApp
refs/heads/master
Pods/FolioReaderKit/Source/Models/Highlight+Helper.swift
mit
2
// // Highlight+Helper.swift // FolioReaderKit // // Created by Heberti Almeida on 06/07/16. // Copyright (c) 2015 Folio Reader. All rights reserved. // import Foundation import RealmSwift /** HighlightStyle type, default is .Yellow. */ public enum HighlightStyle: Int { case yellow case green case blue case pink case underline public init () { self = .yellow } /** Return HighlightStyle for CSS class. */ public static func styleForClass(_ className: String) -> HighlightStyle { switch className { case "highlight-yellow": return .yellow case "highlight-green": return .green case "highlight-blue": return .blue case "highlight-pink": return .pink case "highlight-underline": return .underline default: return .yellow } } /** Return CSS class for HighlightStyle. */ public static func classForStyle(_ style: Int) -> String { switch style { case HighlightStyle.yellow.rawValue: return "highlight-yellow" case HighlightStyle.green.rawValue: return "highlight-green" case HighlightStyle.blue.rawValue: return "highlight-blue" case HighlightStyle.pink.rawValue: return "highlight-pink" case HighlightStyle.underline.rawValue: return "highlight-underline" default: return "highlight-yellow" } } /** Return CSS class for HighlightStyle. */ public static func colorForStyle(_ style: Int, nightMode: Bool = false) -> UIColor { switch style { case HighlightStyle.yellow.rawValue: return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.green.rawValue: return UIColor(red: 192/255, green: 237/255, blue: 114/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.blue.rawValue: return UIColor(red: 173/255, green: 216/255, blue: 255/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.pink.rawValue: return UIColor(red: 255/255, green: 176/255, blue: 202/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.underline.rawValue: return UIColor(red: 240/255, green: 40/255, blue: 20/255, alpha: nightMode ? 0.6 : 1) default: return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1) } } } /// Completion block public typealias Completion = (_ error: NSError?) -> () extension Highlight { /** Save a Highlight with completion block - parameter completion: Completion block */ public func persist(_ completion: Completion? = nil) { do { let realm = try! Realm() realm.beginWrite() realm.add(self, update: true) try realm.commitWrite() completion?(nil) } catch let error as NSError { print("Error on persist highlight: \(error)") completion?(error) } } /** Remove a Highlight */ public func remove() { do { let realm = try! Realm() realm.beginWrite() realm.delete(self) try realm.commitWrite() } catch let error as NSError { print("Error on remove highlight: \(error)") } } /** Remove a Highlight by ID - parameter highlightId: The ID to be removed */ public static func removeById(_ highlightId: String) { var highlight: Highlight? let predicate = NSPredicate(format:"highlightId = %@", highlightId) let realm = try! Realm() highlight = realm.objects(Highlight.self).filter(predicate).toArray(Highlight.self).first highlight?.remove() } /** Update a Highlight by ID - parameter highlightId: The ID to be removed - parameter type: The `HighlightStyle` */ public static func updateById(_ highlightId: String, type: HighlightStyle) { var highlight: Highlight? let predicate = NSPredicate(format:"highlightId = %@", highlightId) do { let realm = try! Realm() highlight = realm.objects(Highlight.self).filter(predicate).toArray(Highlight.self).first realm.beginWrite() highlight?.type = type.hashValue try realm.commitWrite() } catch let error as NSError { print("Error on updateById : \(error)") } } /** Return a list of Highlights with a given ID - parameter bookId: Book ID - parameter page: Page number - returns: Return a list of Highlights */ public static func allByBookId(_ bookId: String, andPage page: NSNumber? = nil) -> [Highlight] { var highlights: [Highlight]? let predicate = (page != nil) ? NSPredicate(format: "bookId = %@ && page = %@", bookId, page!) : NSPredicate(format: "bookId = %@", bookId) let realm = try! Realm() highlights = realm.objects(Highlight.self).filter(predicate).toArray(Highlight.self) return highlights! } /** Return all Highlights - returns: Return all Highlights */ public static func all() -> [Highlight] { var highlights: [Highlight]? let realm = try! Realm() highlights = realm.objects(Highlight.self).toArray(Highlight.self) return highlights! } // MARK: HTML Methods /** Match a highlight on string. */ public static func matchHighlight(_ text: String!, andId id: String, startOffset: String, endOffset: String) -> Highlight? { let pattern = "<highlight id=\"\(id)\" onclick=\".*?\" class=\"(.*?)\">((.|\\s)*?)</highlight>" let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count)) let str = (text as NSString) let mapped = matches.map { (match) -> Highlight in var contentPre = str.substring(with: NSRange(location: match.range.location-kHighlightRange, length: kHighlightRange)) var contentPost = str.substring(with: NSRange(location: match.range.location + match.range.length, length: kHighlightRange)) // Normalize string before save if contentPre.range(of: ">") != nil { let regex = try! NSRegularExpression(pattern: "((?=[^>]*$)(.|\\s)*$)", options: []) let searchString = regex.firstMatch(in: contentPre, options: .reportProgress, range: NSRange(location: 0, length: contentPre.characters.count)) if searchString!.range.location != NSNotFound { contentPre = (contentPre as NSString).substring(with: searchString!.range) } } if contentPost.range(of: "<") != nil { let regex = try! NSRegularExpression(pattern: "^((.|\\s)*?)(?=<)", options: []) let searchString = regex.firstMatch(in: contentPost, options: .reportProgress, range: NSRange(location: 0, length: contentPost.characters.count)) if searchString!.range.location != NSNotFound { contentPost = (contentPost as NSString).substring(with: searchString!.range) } } let highlight = Highlight() highlight.highlightId = id highlight.type = HighlightStyle.styleForClass(str.substring(with: match.rangeAt(1))).rawValue highlight.date = Foundation.Date() highlight.content = Highlight.removeSentenceSpam(str.substring(with: match.rangeAt(2))) highlight.contentPre = Highlight.removeSentenceSpam(contentPre) highlight.contentPost = Highlight.removeSentenceSpam(contentPost) highlight.page = currentPageNumber highlight.bookId = (kBookId as NSString).deletingPathExtension highlight.startOffset = Int(startOffset) ?? -1 highlight.endOffset = Int(endOffset) ?? -1 return highlight } return mapped.first } /** Remove a Highlight from HTML by ID - parameter highlightId: The ID to be removed - returns: The removed id */ @discardableResult public static func removeFromHTMLById(_ highlightId: String) -> String? { guard let currentPage = FolioReader.shared.readerCenter?.currentPage else { return nil } if let removedId = currentPage.webView.js("removeHighlightById('\(highlightId)')") { return removedId } else { print("Error removing Higlight from page") return nil } } /** Remove span tag before store the highlight, this span is added on JavaScript. <span class=\"sentence\"></span> - parameter text: Text to analise - returns: Striped text */ public static func removeSentenceSpam(_ text: String) -> String { // Remove from text func removeFrom(_ text: String, withPattern pattern: String) -> String { var locator = text let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: locator, options: [], range: NSRange(location: 0, length: locator.utf16.count)) let str = (locator as NSString) var newLocator = "" for match in matches { newLocator += str.substring(with: match.rangeAt(1)) } if matches.count > 0 && !newLocator.isEmpty { locator = newLocator } return locator } let pattern = "<span class=\"sentence\">((.|\\s)*?)</span>" let cleanText = removeFrom(text, withPattern: pattern) return cleanText } }
91e478c82e35b40a0d47b6215533163a
34.684028
161
0.578671
false
false
false
false
adtrevor/GeneKit
refs/heads/master
Sources/GeneKit/GAAutomaticCrosser.swift
apache-2.0
1
import Foundation enum GACrossoverOperator { case singlePoint case partiallyMatchedCrossover } final class GAAutomaticCrosser<Chromosome>:GACrosser<Chromosome> { public init<Gene: Hashable>(crossoverOperator: GACrossoverOperator, decomposer: @escaping (Chromosome)->([Gene]), recomposer:@escaping ([Gene])->(Chromosome)) { let automaticCrosser:([Chromosome])->([Chromosome]) = { parents in var children = [Chromosome]() var offset = 0 repeat { let parentA = decomposer(parents[offset]) let parentB = decomposer(parents[offset+1]) let childrensGenes = GAAutomaticCrosser.crossed(parentA: parentA, parentB: parentB, crossoverOperator: crossoverOperator) for childrenGenes in childrensGenes { children.append(recomposer(childrenGenes)) } offset += 2 } while offset < parents.count-1 return children } super.init(parentsCount: 2, crosser: automaticCrosser) } // The general crossed function private class func crossed<Gene: Hashable>(parentA: [Gene], parentB: [Gene], crossoverOperator: GACrossoverOperator) -> [[Gene]] { // We first check if it is valid or not to perform the cross /* Right now, we do not allow the cross to happen between two chromosoms of different size, this will probably change in the future as new kind of crossover operators are added, but it would be tricky and not really useful to do that with our current crossover operators. */ if parentA.count != parentB.count { fatalError("The size of the two genomes doesn't match") } /* Most crossovers require at least two points, so we can't allow chromosoms of size < 3 to cross, again, this might change in the future */ if parentA.count < 3 || parentB.count < 3 { fatalError("The size of the chromosoms must be superior or equal to 3 !") } // Now that we have ensured that everything is ok, let's do the crossover switch crossoverOperator { case .singlePoint: return singlePointCrossover(parentA, parentB) case .partiallyMatchedCrossover: return partiallyMatchedCrossover(parentA, parentB) } } // MARK: - PMX /* Implementation of crossover operators, it is assumed that passed mates have already been checked as conform to this kind of crossover */ private class func partiallyMatchedCrossover<Gene: Hashable>(_ parent1:[Gene], _ parent2:[Gene]) -> [[Gene]] { let randomCrossoverPoints = crossoverPoints(genomeSize: parent1.count, pointsCount: 2) // The selected points let point1 = randomCrossoverPoints[0] let point2 = randomCrossoverPoints[1] // We make points with more explicit names let beginningPoint = 0 let endOfFirstPart = point1 let startOfSecondPart = point1 + 1 let endOfSecondPart = point2 let startOfLastPart = point2 + 1 let endPoint = parent1.count-1 var child1Representation = [Gene]() var child2Representation = [Gene]() /* Swapping the genes */ // First part, before the swap child1Representation += parent1[beginningPoint...endOfFirstPart] child2Representation += parent2[beginningPoint...endOfFirstPart] // Second part, the one that's swapped child1Representation += parent2[startOfSecondPart...endOfSecondPart] child2Representation += parent1[startOfSecondPart...endOfSecondPart] // Third part, this one isn't swapped child1Representation += parent1[startOfLastPart...endPoint] child2Representation += parent2[startOfLastPart...endPoint] func map(_ childToMap:[Gene], with mapSource:[Gene]) -> [Gene] { func genomeIsValid(_ genomeRepresentation:[Gene]) -> Bool { return genomeRepresentation.count == Set(genomeRepresentation).count } var childToMapCopy = childToMap // While genome isn't valid while !genomeIsValid(childToMapCopy) { // We make the correspondance map var correspondanceMap = Dictionary<Gene,Gene>() // We give values to the correspondance map for i in startOfSecondPart...endOfSecondPart { correspondanceMap[childToMap[i]] = mapSource[i] } // We replace non swapped values if appropriate for i in (Array(beginningPoint...endOfFirstPart) + Array(startOfLastPart...endPoint)) { childToMapCopy[i] = correspondanceMap[childToMapCopy[i]] ?? childToMapCopy[i] } } return childToMapCopy } let c1 = map(child1Representation, with: child2Representation) let c2 = map(child2Representation, with: child1Representation) return [c1, c2] } /** An array containing random, unique, sorted integers generated using the Knuth algorithm (best suited when abs(upperBound-lowerBound) is close to count) */ private static func makeAscendingUniqueRandomIntegersArray(lowerBound: Int, upperBound:Int, count:Int) -> [Int] { var selectedNumbers = [Int]() selectedNumbers.reserveCapacity(count) for i in lowerBound...upperBound where selectedNumbers.count < count { if Double.random0to1() <= Double(count - selectedNumbers.count)/Double(upperBound - i + 1) { selectedNumbers.append(i) } } return selectedNumbers } private class func crossoverPoints(genomeSize:Int, pointsCount:Int) -> [Int] { return makeAscendingUniqueRandomIntegersArray(lowerBound: 1, upperBound: genomeSize-2, count: pointsCount) } //MARK: - Single point private class func singlePointCrossover<Gene>(_ parent1:[Gene], _ parent2:[Gene]) -> [[Gene]] { let randomCrossoverPoint = Int.randomIn(min: 1, max: parent1.count-1) var child1Representation = [Gene]() var child2Representation = [Gene]() child1Representation += parent1[0...randomCrossoverPoint] child1Representation += parent2[(randomCrossoverPoint+1)..<parent1.count] child2Representation += parent2[0...randomCrossoverPoint] child2Representation += parent1[(randomCrossoverPoint+1)..<parent1.count] return [child1Representation, child2Representation] } }
ff8074bd2cd826f29f50ce81e17bf185
35.614213
277
0.591848
false
false
false
false