repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
borglab/SwiftFusion
Sources/SwiftFusion/Inference/AllVectors.swift
1
3815
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import _Differentiation import PenguinStructures /// A heterogeneous collection of vectors. /// /// TODO: This really should be a different type from `VariableAssignments` because (1) we know /// statically that `AllVectors` only contains vector values, and (2) we use `AllVectors` in some /// places for things other than variable assignments (e.g. a collection of error vectors is one /// error vector per factor). public typealias AllVectors = VariableAssignments /// Vector operations. // TODO: There are some mutating operations here that copy, mutate, and write back. Make these // more efficient. extension AllVectors { /// Returns the squared norm of `self`, where `self` is viewed as a vector in the vector space /// direct sum of all the variables. /// /// Precondition: All the variables in `self` are vectors. public var squaredNorm: Double { return storage.values.reduce(into: 0) { (result, value) in let v = AnyVectorArrayBuffer(unsafelyCasting: value) result += v.dot(v) } } /// Returns the scalar product of `lhs` with `rhs`, where `rhs` is viewed as a vector in the /// vector space direct sum of all the variables. /// /// Precondition: All the variables in `rhs` are vectors. public static func * (_ lhs: Double, _ rhs: Self) -> Self { VariableAssignments(storage: rhs.storage.mapValues { value in var vector = AnyArrayBuffer<VectorArrayDispatch>(unsafelyCasting: value) vector.scale(by: lhs) // Note: This is a safe upcast. return AnyElementArrayBuffer(unsafelyCasting: vector) }) } /// Returns the vector sum of `lhs` with `rhs`, where `lhs` and `rhs` are viewed as vectors in the /// vector space direct sum of all the variables. /// /// Precondition: All the elements in `lhs` and `rhs` are vectors. `lhs` and `rhs` have /// assignments for exactly the same sets of variables. public static func + (_ lhs: Self, _ rhs: Self) -> Self { let r = Dictionary(uniqueKeysWithValues: lhs.storage.map { (key, value) -> (ObjectIdentifier, AnyElementArrayBuffer) in var resultVector = AnyArrayBuffer<VectorArrayDispatch>(unsafelyCasting: value) let rhsVector = rhs.storage[key].unsafelyUnwrapped resultVector.add(rhsVector) // Note: This is a safe upcast. return (key, AnyElementArrayBuffer(unsafelyCasting: resultVector)) }) return VariableAssignments(storage: r) } /// Stores an `ErrorVector` for a factor of type `F`. public mutating func store<F: LinearizableFactor>(_ value: F.ErrorVector, factorType _: F.Type) { _ = storage[ ObjectIdentifier(F.self), // Note: This is a safe upcast. default: AnyElementArrayBuffer( unsafelyCasting: AnyVectorArrayBuffer(ArrayBuffer<F.ErrorVector>())) ].unsafelyAppend(value) } /// Returns the `ErrorVector` from the `perFactorID`-th factor of type `F`. public subscript<F: VectorFactor>(_ perFactorID: Int, factorType _: F.Type) -> F.ErrorVector { let array = storage[ObjectIdentifier(F.self)].unsafelyUnwrapped return ArrayBuffer<F.ErrorVector>(unsafelyDowncasting: array).withUnsafeBufferPointer { b in b[perFactorID] } } }
apache-2.0
70f841fca9b8ee45206765e796a98b28
41.388889
100
0.708519
4.151251
false
false
false
false
waterskier2007/NVActivityIndicatorView
NVActivityIndicatorView/NVActivityIndicatorView.swift
1
19596
// // NVActivityIndicatorView.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 <<<<<<< HEAD public enum NVActivityIndicatorType { case Blank case BallPulse case BallGridPulse case BallClipRotate case SquareSpin case BallClipRotatePulse case BallClipRotateMultiple case BallPulseRise case BallRotate case CubeTransition case BallZigZag case BallZigZagDeflect case BallTrianglePath case BallScale case LineScale case LineScaleParty case BallScaleMultiple case BallPulseSync case BallBeat case LineScalePulseOut case LineScalePulseOutRapid case BallScaleRipple case BallScaleRippleMultiple case BallSpinFadeLoader case LineSpinFadeLoader case TriangleSkewSpin case Pacman case BallGridBeat case SemiCircleSpin case BallCirclePath private func animation() -> NVActivityIndicatorAnimationDelegate { ======= /** Enum of animation types used for activity indicator view. - Blank: Blank animation. - BallPulse: BallPulse animation. - BallGridPulse: BallGridPulse animation. - BallClipRotate: BallClipRotate animation. - SquareSpin: SquareSpin animation. - BallClipRotatePulse: BallClipRotatePulse animation. - BallClipRotateMultiple: BallClipRotateMultiple animation. - BallPulseRise: BallPulseRise animation. - BallRotate: BallRotate animation. - CubeTransition: CubeTransition animation. - BallZigZag: BallZigZag animation. - BallZigZagDeflect: BallZigZagDeflect animation. - BallTrianglePath: BallTrianglePath animation. - BallScale: BallScale animation. - LineScale: LineScale animation. - LineScaleParty: LineScaleParty animation. - BallScaleMultiple: BallScaleMultiple animation. - BallPulseSync: BallPulseSync animation. - BallBeat: BallBeat animation. - LineScalePulseOut: LineScalePulseOut animation. - LineScalePulseOutRapid: LineScalePulseOutRapid animation. - BallScaleRipple: BallScaleRipple animation. - BallScaleRippleMultiple: BallScaleRippleMultiple animation. - BallSpinFadeLoader: BallSpinFadeLoader animation. - LineSpinFadeLoader: LineSpinFadeLoader animation. - TriangleSkewSpin: TriangleSkewSpin animation. - Pacman: Pacman animation. - BallGridBeat: BallGridBeat animation. - SemiCircleSpin: SemiCircleSpin animation. - BallRotateChase: BallRotateChase animation. - Orbit: Orbit animation. - AudioEqualizer: AudioEqualizer animation. */ public enum NVActivityIndicatorType: Int { /** Blank. - returns: Instance of NVActivityIndicatorAnimationBlank. */ case blank /** BallPulse. - returns: Instance of NVActivityIndicatorAnimationBallPulse. */ case ballPulse /** BallGridPulse. - returns: Instance of NVActivityIndicatorAnimationBallGridPulse. */ case ballGridPulse /** BallClipRotate. - returns: Instance of NVActivityIndicatorAnimationBallClipRotate. */ case ballClipRotate /** SquareSpin. - returns: Instance of NVActivityIndicatorAnimationSquareSpin. */ case squareSpin /** BallClipRotatePulse. - returns: Instance of NVActivityIndicatorAnimationBallClipRotatePulse. */ case ballClipRotatePulse /** BallClipRotateMultiple. - returns: Instance of NVActivityIndicatorAnimationBallClipRotateMultiple. */ case ballClipRotateMultiple /** BallPulseRise. - returns: Instance of NVActivityIndicatorAnimationBallPulseRise. */ case ballPulseRise /** BallRotate. - returns: Instance of NVActivityIndicatorAnimationBallRotate. */ case ballRotate /** CubeTransition. - returns: Instance of NVActivityIndicatorAnimationCubeTransition. */ case cubeTransition /** BallZigZag. - returns: Instance of NVActivityIndicatorAnimationBallZigZag. */ case ballZigZag /** BallZigZagDeflect - returns: Instance of NVActivityIndicatorAnimationBallZigZagDeflect */ case ballZigZagDeflect /** BallTrianglePath. - returns: Instance of NVActivityIndicatorAnimationBallTrianglePath. */ case ballTrianglePath /** BallScale. - returns: Instance of NVActivityIndicatorAnimationBallScale. */ case ballScale /** LineScale. - returns: Instance of NVActivityIndicatorAnimationLineScale. */ case lineScale /** LineScaleParty. - returns: Instance of NVActivityIndicatorAnimationLineScaleParty. */ case lineScaleParty /** BallScaleMultiple. - returns: Instance of NVActivityIndicatorAnimationBallScaleMultiple. */ case ballScaleMultiple /** BallPulseSync. - returns: Instance of NVActivityIndicatorAnimationBallPulseSync. */ case ballPulseSync /** BallBeat. - returns: Instance of NVActivityIndicatorAnimationBallBeat. */ case ballBeat /** LineScalePulseOut. - returns: Instance of NVActivityIndicatorAnimationLineScalePulseOut. */ case lineScalePulseOut /** LineScalePulseOutRapid. - returns: Instance of NVActivityIndicatorAnimationLineScalePulseOutRapid. */ case lineScalePulseOutRapid /** BallScaleRipple. - returns: Instance of NVActivityIndicatorAnimationBallScaleRipple. */ case ballScaleRipple /** BallScaleRippleMultiple. - returns: Instance of NVActivityIndicatorAnimationBallScaleRippleMultiple. */ case ballScaleRippleMultiple /** BallSpinFadeLoader. - returns: Instance of NVActivityIndicatorAnimationBallSpinFadeLoader. */ case ballSpinFadeLoader /** LineSpinFadeLoader. - returns: Instance of NVActivityIndicatorAnimationLineSpinFadeLoader. */ case lineSpinFadeLoader /** TriangleSkewSpin. - returns: Instance of NVActivityIndicatorAnimationTriangleSkewSpin. */ case triangleSkewSpin /** Pacman. - returns: Instance of NVActivityIndicatorAnimationPacman. */ case pacman /** BallGridBeat. - returns: Instance of NVActivityIndicatorAnimationBallGridBeat. */ case ballGridBeat /** SemiCircleSpin. - returns: Instance of NVActivityIndicatorAnimationSemiCircleSpin. */ case semiCircleSpin /** BallRotateChase. - returns: Instance of NVActivityIndicatorAnimationBallRotateChase. */ case ballRotateChase /** Orbit. - returns: Instance of NVActivityIndicatorAnimationOrbit. */ case orbit /** AudioEqualizer. - returns: Instance of NVActivityIndicatorAnimationAudioEqualizer. */ case audioEqualizer static let allTypes = (blank.rawValue ... audioEqualizer.rawValue).map { NVActivityIndicatorType(rawValue: $0)! } func animation() -> NVActivityIndicatorAnimationDelegate { >>>>>>> ninjaprox/master switch self { case .blank: return NVActivityIndicatorAnimationBlank() case .ballPulse: return NVActivityIndicatorAnimationBallPulse() case .ballGridPulse: return NVActivityIndicatorAnimationBallGridPulse() case .ballClipRotate: return NVActivityIndicatorAnimationBallClipRotate() case .squareSpin: return NVActivityIndicatorAnimationSquareSpin() case .ballClipRotatePulse: return NVActivityIndicatorAnimationBallClipRotatePulse() case .ballClipRotateMultiple: return NVActivityIndicatorAnimationBallClipRotateMultiple() case .ballPulseRise: return NVActivityIndicatorAnimationBallPulseRise() case .ballRotate: return NVActivityIndicatorAnimationBallRotate() case .cubeTransition: return NVActivityIndicatorAnimationCubeTransition() case .ballZigZag: return NVActivityIndicatorAnimationBallZigZag() case .ballZigZagDeflect: return NVActivityIndicatorAnimationBallZigZagDeflect() case .ballTrianglePath: return NVActivityIndicatorAnimationBallTrianglePath() case .ballScale: return NVActivityIndicatorAnimationBallScale() case .lineScale: return NVActivityIndicatorAnimationLineScale() case .lineScaleParty: return NVActivityIndicatorAnimationLineScaleParty() case .ballScaleMultiple: return NVActivityIndicatorAnimationBallScaleMultiple() case .ballPulseSync: return NVActivityIndicatorAnimationBallPulseSync() case .ballBeat: return NVActivityIndicatorAnimationBallBeat() case .lineScalePulseOut: return NVActivityIndicatorAnimationLineScalePulseOut() case .lineScalePulseOutRapid: return NVActivityIndicatorAnimationLineScalePulseOutRapid() case .ballScaleRipple: return NVActivityIndicatorAnimationBallScaleRipple() case .ballScaleRippleMultiple: return NVActivityIndicatorAnimationBallScaleRippleMultiple() case .ballSpinFadeLoader: return NVActivityIndicatorAnimationBallSpinFadeLoader() case .lineSpinFadeLoader: return NVActivityIndicatorAnimationLineSpinFadeLoader() case .triangleSkewSpin: return NVActivityIndicatorAnimationTriangleSkewSpin() case .pacman: return NVActivityIndicatorAnimationPacman() case .ballGridBeat: return NVActivityIndicatorAnimationBallGridBeat() case .semiCircleSpin: return NVActivityIndicatorAnimationSemiCircleSpin() <<<<<<< HEAD case .BallCirclePath: return NVActivityIndicatorAnimationBallCirclePath() ======= case .ballRotateChase: return NVActivityIndicatorAnimationBallRotateChase() case .orbit: return NVActivityIndicatorAnimationOrbit() case .audioEqualizer: return NVActivityIndicatorAnimationAudioEqualizer() >>>>>>> ninjaprox/master } } } <<<<<<< HEAD public class NVActivityIndicatorView: UIView { private static let DEFAULT_TYPE: NVActivityIndicatorType = .Pacman private static let DEFAULT_COLOR = UIColor.whiteColor() private static let DEFAULT_SIZE: CGSize = CGSize(width: 40, height: 40) private var type: NVActivityIndicatorType private var color: UIColor private var size: CGSize var animating: Bool = false var hidesWhenStopped: Bool = true /** Create a activity indicator view with default type, color and size This is used by storyboard to initiate the view - Default type is pacman\n - Default color is white\n - Default size is 40 :param: decoder :returns: The activity indicator view */ required public init(coder aDecoder: NSCoder) { self.type = NVActivityIndicatorView.DEFAULT_TYPE self.color = NVActivityIndicatorView.DEFAULT_COLOR self.size = NVActivityIndicatorView.DEFAULT_SIZE super.init(coder: aDecoder); } /** Create a activity indicator view with specified type, color, size and size :param: frame view's frame :param: type animation type, value of NVActivityIndicatorType enum. Default type is pacman. :param: color color of activity indicator view. Default color is white. :param: size actual size of animation in view. Default size is 40 :returns: The activity indicator view */ public init(frame: CGRect, type: NVActivityIndicatorType = DEFAULT_TYPE, color: UIColor = DEFAULT_COLOR, size: CGSize = DEFAULT_SIZE) { self.type = type self.color = color self.size = size ======= /// Activity indicator view with nice animations public final class NVActivityIndicatorView: UIView { /// Default type. Default value is .BallSpinFadeLoader. public static var DEFAULT_TYPE: NVActivityIndicatorType = .ballSpinFadeLoader /// Default color of activity indicator. Default value is UIColor.white. public static var DEFAULT_COLOR = UIColor.white /// Default color of text. Default value is UIColor.white. public static var DEFAULT_TEXT_COLOR = UIColor.white /// Default padding. Default value is 0. public static var DEFAULT_PADDING: CGFloat = 0 /// Default size of activity indicator view in UI blocker. Default value is 60x60. public static var DEFAULT_BLOCKER_SIZE = CGSize(width: 60, height: 60) /// Default display time threshold to actually display UI blocker. Default value is 0 ms. public static var DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD = 0 /// Default minimum display time of UI blocker. Default value is 0 ms. public static var DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME = 0 /// Default message displayed in UI blocker. Default value is nil. public static var DEFAULT_BLOCKER_MESSAGE: String? /// Default font of message displayed in UI blocker. Default value is bold system font, size 20. public static var DEFAULT_BLOCKER_MESSAGE_FONT = UIFont.boldSystemFont(ofSize: 20) /// Default background color of UI blocker. Default value is UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) public static var DEFAULT_BLOCKER_BACKGROUND_COLOR = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) /// Animation type. public var type: NVActivityIndicatorType = NVActivityIndicatorView.DEFAULT_TYPE @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'type' instead.") @IBInspectable var typeName: String { get { return getTypeName() } set { _setTypeName(newValue) } } /// Color of activity indicator view. @IBInspectable public var color: UIColor = NVActivityIndicatorView.DEFAULT_COLOR /// Padding of activity indicator view. @IBInspectable public var padding: CGFloat = NVActivityIndicatorView.DEFAULT_PADDING /// Current status of animation, read-only. @available(*, deprecated: 3.1) public var animating: Bool { return isAnimating } /// Current status of animation, read-only. private(set) public var isAnimating: Bool = false /** Returns an object initialized from data in a given unarchiver. self, initialized using the data in decoder. - parameter decoder: an unarchiver object. - returns: self, initialized using the data in decoder. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.clear isHidden = true } /** Create a activity indicator view. Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params. - parameter frame: view's frame. - parameter type: animation type. - parameter color: color of activity indicator view. - parameter padding: padding of activity indicator view. - returns: The activity indicator view. */ public init(frame: CGRect, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil) { self.type = type ?? NVActivityIndicatorView.DEFAULT_TYPE self.color = color ?? NVActivityIndicatorView.DEFAULT_COLOR self.padding = padding ?? NVActivityIndicatorView.DEFAULT_PADDING >>>>>>> ninjaprox/master super.init(frame: frame) isHidden = true } // Fix issue #62 // Intrinsic content size is used in autolayout // that causes mislayout when using with MBProgressHUD. /** <<<<<<< HEAD Start animation */ public func startAnimation() { if hidesWhenStopped && hidden { hidden = false } if (self.layer.sublayers == nil) { setUpAnimation() } self.layer.speed = 1 self.animating = true } /** Stop animation */ public func stopAnimation() { self.layer.speed = 0 self.animating = false if hidesWhenStopped && !hidden { hidden = true ======= Returns the natural size for the receiving view, considering only properties of the view itself. A size indicating the natural size for the receiving view based on its intrinsic properties. - returns: A size indicating the natural size for the receiving view based on its intrinsic properties. */ public override var intrinsicContentSize: CGSize { return CGSize(width: bounds.width, height: bounds.height) } /** Start animating. */ public final func startAnimating() { isHidden = false isAnimating = true layer.speed = 1 setUpAnimation() } /** Stop animating. */ public final func stopAnimating() { isHidden = true isAnimating = false layer.sublayers?.removeAll() } // MARK: Internal func _setTypeName(_ typeName: String) { for item in NVActivityIndicatorType.allTypes { if String(describing: item).caseInsensitiveCompare(typeName) == ComparisonResult.orderedSame { type = item break } >>>>>>> ninjaprox/master } } func getTypeName() -> String { return String(describing: type) } // MARK: Privates <<<<<<< HEAD private func setUpAnimation() { let animation: protocol<NVActivityIndicatorAnimationDelegate> = self.type.animation() self.layer.sublayers = nil animation.setUpAnimationInLayer(self.layer, size: self.size, color: self.color) ======= private final func setUpAnimation() { let animation: NVActivityIndicatorAnimationDelegate = type.animation() var animationRect = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(padding, padding, padding, padding)) let minEdge = min(animationRect.width, animationRect.height) layer.sublayers = nil animationRect.size = CGSize(width: minEdge, height: minEdge) animation.setUpAnimation(in: layer, size: animationRect.size, color: color) >>>>>>> ninjaprox/master } }
mit
0ebc838e75ba701d3d23d69148780774
31.390083
139
0.684068
5.422247
false
false
false
false
supertommy/craft
craft/Deferred.swift
1
3347
// // Deferred.swift // craft // // Created by Tommy Leung on 6/28/14. // Copyright (c) 2014 Tommy Leung. All rights reserved. // import Foundation class Deferred { class Child { var onResolved: Result? var onRejected: Result? var promise: Promise init(promise: Promise) { self.promise = promise } } var promise: Promise! var children: [Child] class func create() -> Deferred { let d = Deferred() d.promise = Promise(deferred: d) return d } init() { children = Array() } func addChild(resolve: Result?, reject: Result?, p: Promise) { let c = Child(promise: p) c.onResolved = resolve c.onRejected = reject children.append(c) } func resolve(value: Value) { promise.state = PromiseState.FULFILLED for c in children { resolveChild(c, value: value) } } func reject(value: Value) { promise.state = PromiseState.REJECTED for c in children { if let r = c.onRejected { let v: Value? = r(value: value) //only fire once c.onRejected = nil c.promise.deffered.reject(v) continue; } c.promise.deffered.reject(value) } } //MARK: private methods private func resolveChild(child: Child, value: Value) { if let r = child.onResolved { let v: Value = r(value: value) //only fire once child.onResolved = nil if (resolutionIsTypeError(v)) { //TODO: perhaps better rejection value here reject("Type error") return } if (valueIsPromise(v)) { //see 2.3.2 let x = v as! Promise promise.state = x.state x.then({ (value: Value) -> Value in print(value) self.resolve(value) return nil }, reject: { (value: Value) -> Value in self.reject(value) return nil }) return } //TODO: consider how/if to handle 2.3.3 child.promise.deffered.resolve(v) return } child.promise.deffered.resolve(value) } private func valueIsPromise(value: Value) -> Bool { if let val: Any = value { return val is Promise } return false } private func resolutionIsTypeError(value: Value) -> Bool { if (valueIsPromise(value)) { if (value as! Promise === promise) { return true } } return false } }
mit
bd1189ce700e7724877a0a4a44257e43
21.026316
64
0.414401
5.102134
false
false
false
false
themonki/onebusaway-iphone
OneBusAway/ui/debugging/UserDefaultsBrowserViewController.swift
1
2219
// // UserDefaultsBrowserViewController.swift // org.onebusaway.iphone // // Created by Aaron Brethorst on 4/10/17. // Copyright © 2017 OneBusAway. All rights reserved. // import UIKit import OBAKit // swiftlint:disable force_cast class UserDefaultsBrowserViewController: OBAStaticTableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("user_defaults_browser_controller.title", comment: "Title for the user defaults browser") self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .refresh, target: self, action: #selector(reloadData)) self.reloadData() } @objc func reloadData() { let section = OBATableSection.init(title: nil) let dictionaryRep = OBAApplication.shared().userDefaults.dictionaryRepresentation() section.rows = dictionaryRep.keys.sorted().map { key -> OBATableRow in let value = dictionaryRep[key] let row = OBATableRow.init(title: key) { _ in self.visualizeKey(key, value: value) } row.subtitle = (value as! NSObject).description row.style = .subtitle return row } self.sections = [section] self.tableView.reloadData() } private func visualizeKey(_ key: String, value: Any?) { guard let value = value else { return } if value is Data { let unarchiver = NSKeyedUnarchiver.init(forReadingWith: value as! Data) let obj = unarchiver.decodeObject(forKey: key) unarchiver.finishDecoding() let msg = (obj as! NSObject).description self.showAlert(title: key, message: msg) } else { self.showAlert(title: key, message: (value as! NSObject).description) } } private func showAlert(title: String, message: String) { let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: OBAStrings.dismiss, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
apache-2.0
e2cd4e4dd9168b9c8fdc088f5133286b
30.685714
145
0.642922
4.63048
false
false
false
false
azimin/Rainbow
Rainbow/ColorNamesCollection.swift
1
1576
// // ColorNamesCollection.swift // Rainbow // // Created by Alex Zimin on 11/04/16. // Copyright © 2016 Alex Zimin. All rights reserved. // import Foundation private struct ColorInCollection { var name: String var rgb: Vector3D } class ColorNamesCollection { private static var colors: [ColorInCollection] = { var result = [ColorInCollection]() var error: NSError? let url = NSBundle.mainBundle().URLForResource("colors", withExtension: "csv")! let fileText = try! String(contentsOfURL: url, encoding: NSUTF8StringEncoding) let colors = fileText.componentsSeparatedByString("\n") for colorLine in colors { let colorInfo = colorLine.componentsSeparatedByString(",") if colorInfo.count != 6 { continue } let red = Float(colorInfo[3])! / 255 let green = Float(colorInfo[4])! / 255 let blue = Float(colorInfo[5])! / 255 let color = ColorInCollection(name: colorInfo[1], rgb: Vector3D(x: red, y: green, z: blue)) result.append(color) } return result }() static func getColorName(color: Color) -> String { let colorVector = Vector3D(tuple: color.RGBVector.toFloatTuple()) let distanceFunc = distanceForAccuracy(.Low) var minIndex = 0 var minValue: Float = Float(Int.max) for (index, color) in colors.enumerate() { let distance = distanceFunc(color.rgb, colorVector) if distance < minValue { minIndex = index minValue = distance } } return colors[minIndex].name } }
mit
70608ca11ca02a2a76101b8c8470aa85
25.711864
97
0.645079
4.233871
false
false
false
false
makezwl/zhao
NimbleTests/Helpers/utils.swift
80
2049
import Foundation import Nimble import XCTest func failsWithErrorMessage(message: String, closure: () -> Void, file: String = __FILE__, line: UInt = __LINE__, preferOriginalSourceLocation: Bool = false) { var filePath = file var lineNumber = line let recorder = AssertionRecorder() withAssertionHandler(recorder, closure) var lastFailure: AssertionRecord? if recorder.assertions.count > 0 { lastFailure = recorder.assertions[recorder.assertions.endIndex - 1] if lastFailure!.message == message { return } } if preferOriginalSourceLocation { if let failure = lastFailure { filePath = failure.location.file lineNumber = failure.location.line } } if lastFailure != nil { let msg = "Got failure message: \"\(lastFailure!.message)\", but expected \"\(message)\"" XCTFail(msg, file: filePath, line: lineNumber) } else { XCTFail("expected failure message, but got none", file: filePath, line: lineNumber) } } func failsWithErrorMessageForNil(message: String, closure: () -> Void, file: String = __FILE__, line: UInt = __LINE__, preferOriginalSourceLocation: Bool = false) { failsWithErrorMessage("\(message) (use beNil() to match nils)", closure, file: file, line: line, preferOriginalSourceLocation: preferOriginalSourceLocation) } func deferToMainQueue(action: () -> Void) { dispatch_async(dispatch_get_main_queue()) { NSThread.sleepForTimeInterval(0.01) action() } } public class NimbleHelper : NSObject { class func expectFailureMessage(message: NSString, block: () -> Void, file: String, line: UInt) { failsWithErrorMessage(message as String, block, file: file, line: line, preferOriginalSourceLocation: true) } class func expectFailureMessageForNil(message: NSString, block: () -> Void, file: String, line: UInt) { failsWithErrorMessageForNil(message as String, block, file: file, line: line, preferOriginalSourceLocation: true) } }
apache-2.0
36d0f3ef38f74c717e8976696fdb50d5
36.944444
164
0.676916
4.743056
false
false
false
false
Johennes/firefox-ios
Storage/ThirdParty/SwiftData.swift
1
40545
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ public class SwiftData { let filename: String static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// Used for testing. static var ReuseConnections = true /// For thread-safe access to the shared connection. private let sharedConnectionQueue: dispatch_queue_t /// Shared connection to this database. private var sharedConnection: ConcreteSQLiteDBConnection? private var key: String? = nil private var prevKey: String? = nil /// A simple state flag to track whether we should accept new connection requests. /// If a connection request is made while the database is closed, a /// FailedSQLiteDBConnection will be returned. private var closed = false init(filename: String, key: String? = nil, prevKey: String? = nil) { self.filename = filename self.sharedConnectionQueue = dispatch_queue_create("SwiftData queue: \(filename)", DISPATCH_QUEUE_SERIAL) // Ensure that multi-thread mode is enabled by default. // See https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() == 2) self.key = key self.prevKey = prevKey } private func getSharedConnection() -> ConcreteSQLiteDBConnection? { var connection: ConcreteSQLiteDBConnection? dispatch_sync(sharedConnectionQueue) { if self.closed { log.warning(">>> Database is closed for \(self.filename)") return } if self.sharedConnection == nil { log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(NSThread.currentThread()).") self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.ReadWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey) } connection = self.sharedConnection } return connection } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ func withConnection(flags: SwiftData.Flags, synchronous: Bool=true, cb: (db: SQLiteDBConnection) -> NSError?) -> NSError? { let conn: ConcreteSQLiteDBConnection? if SwiftData.ReuseConnections { conn = getSharedConnection() } else { log.debug(">>> Creating non-shared SQLiteDBConnection for \(self.filename) on thread \(NSThread.currentThread()).") conn = ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) } guard let connection = conn else { // Run the callback with a fake failed connection. // Yeah, that means we have an error return value but we still run the callback. let failed = FailedSQLiteDBConnection() let queue = self.sharedConnectionQueue let noConnection = NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]) if synchronous { var error: NSError? = nil dispatch_sync(queue) { error = cb(db: failed) } return error ?? noConnection } dispatch_async(queue) { cb(db: failed) } return noConnection } if synchronous { var error: NSError? = nil dispatch_sync(connection.queue) { error = cb(db: connection) } return error } dispatch_async(connection.queue) { cb(db: connection) } return nil } func transaction(transactionClosure: (db: SQLiteDBConnection) -> Bool) -> NSError? { return self.transaction(synchronous: true, transactionClosure: transactionClosure) } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ func transaction(synchronous synchronous: Bool=true, transactionClosure: (db: SQLiteDBConnection) -> Bool) -> NSError? { return withConnection(SwiftData.Flags.ReadWriteCreate, synchronous: synchronous) { db in if let err = db.executeChange("BEGIN EXCLUSIVE") { log.warning("BEGIN EXCLUSIVE failed.") return err } if transactionClosure(db: db) { log.verbose("Op in transaction succeeded. Committing.") if let err = db.executeChange("COMMIT") { log.error("COMMIT failed. Rolling back.") db.executeChange("ROLLBACK") return err } } else { log.debug("Op in transaction failed. Rolling back.") if let err = db.executeChange("ROLLBACK") { return err } } return nil } } /// Don't use this unless you know what you're doing. The deinitializer /// should be used to achieve refcounting semantics. func forceClose() { dispatch_sync(sharedConnectionQueue) { self.closed = true self.sharedConnection = nil } } /// Reopens a database that had previously been force-closed. /// Does nothing if this database is already open. func reopenIfClosed() { dispatch_sync(sharedConnectionQueue) { self.closed = false } } public enum Flags { case ReadOnly case ReadWrite case ReadWriteCreate private func toSQL() -> Int32 { switch self { case .ReadOnly: return SQLITE_OPEN_READONLY case .ReadWrite: return SQLITE_OPEN_READWRITE case .ReadWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: COpaquePointer = nil private let connection: ConcreteSQLiteDBConnection init(connection: ConcreteSQLiteDBConnection, query: String, args: [AnyObject?]?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. private func bind(objects: [AnyObject?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if (count < objects.count) { return connection.createErr("During: Bind", status: 202) } if (count > objects.count) { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerate() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutablePointer<()>) -> Void let transient = unsafeBitCast(-1, CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cStringUsingEncoding(NSUTF8StringEncoding)!, -1, transient) } else if obj is NSData { status = sqlite3_bind_blob(pointer, Int32(index+1), (obj as! NSData).bytes, -1, nil) } else if obj is NSDate { let timestamp = (obj as! NSDate).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj === nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } protocol SQLiteDBConnection { var lastInsertedRowID: Int { get } var numberOfRowsModified: Int { get } func executeChange(sqlStr: String) -> NSError? func executeChange(sqlStr: String, withArgs args: [AnyObject?]?) -> NSError? func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T)) -> Cursor<T> func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]?) -> Cursor<T> func executeQueryUnsafe<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]?) -> Cursor<T> func interrupt() func checkpoint() func checkpoint(mode: Int32) func vacuum() -> NSError? } // Represents a failure to open. class FailedSQLiteDBConnection: SQLiteDBConnection { private func fail(str: String) -> NSError { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str]) } var lastInsertedRowID: Int { return 0 } var numberOfRowsModified: Int { return 0 } func executeChange(sqlStr: String) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeChange(sqlStr: String, withArgs args: [AnyObject?]?) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQueryUnsafe<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func interrupt() {} func checkpoint() {} func checkpoint(mode: Int32) {} func vacuum() -> NSError? { return self.fail("Non-open connection; can't vacuum.") } } public class ConcreteSQLiteDBConnection: SQLiteDBConnection { private var sqliteDB: COpaquePointer = nil private let filename: String private let debug_enabled = false private let queue: dispatch_queue_t public var version: Int { get { return pragma("user_version", factory: IntFactory) ?? 0 } set { executeChange("PRAGMA user_version = \(newValue)") } } private func setKey(key: String?) -> NSError? { sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil) if cursor.status != .Success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"]) } return nil } private func reKey(oldKey: String?, newKey: String?) -> NSError? { sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count)) sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) // Check that the new key actually works sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil) if cursor.status != .Success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"]) } return nil } func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } private func pragma<T: Equatable>(pragma: String, expected: T?, factory: SDRow -> T, message: String) throws { let cursorResult = self.pragma(pragma, factory: factory) if cursorResult != expected { log.error("\(message): \(cursorResult), \(expected)") throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."]) } } private func pragma<T>(pragma: String, factory: SDRow -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: nil) defer { cursor.close() } return cursor[0] } private func prepareShared() { if SwiftData.EnableForeignKeys { pragma("foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout) } private func prepareEncrypted(flags: Int32, key: String?, prevKey: String? = nil) throws { // Setting the key needs to be the first thing done with the database. if let _ = setKey(key) { if let err = closeCustomConnection(immediately: true) { log.error("Couldn't close connection: \(err). Failing to open.") throw err } if let err = openWithFlags(flags) { throw err } if let err = reKey(prevKey, newKey: key) { log.error("Unable to encrypt database") throw err } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") try pragma("journal_mode=WAL", expected: "wal", factory: StringFactory, message: "WAL journal mode set") } self.prepareShared() } private func prepareCleartext() throws { // If we just created the DB -- i.e., no tables have been created yet -- then // we can set the page size right now and save a vacuum. // // For where these values come from, see Bug 1213623. // // Note that sqlcipher uses cipher_page_size instead, but we don't set that // because it needs to be set from day one. let desiredPageSize = 32 * 1024 pragma("page_size=\(desiredPageSize)", factory: IntFactory) let currentPageSize = pragma("page_size", factory: IntFactory) // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { try pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") try pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize) to \(desiredPageSize).") if let err = self.vacuum() { log.error("Vacuuming failed: \(err).") } else { log.debug("Vacuuming succeeded.") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize /* * With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the * compiler seems to eagerly discard these queries if they're simply * inlined, causing a crash in `pragma`. * * Hackily hold on to them. */ let journalModeQuery = "journal_mode=WAL" let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)" let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)" try withExtendedLifetime(journalModeQuery, { try pragma(journalModeQuery, expected: "wal", factory: StringFactory, message: "WAL journal mode set") }) try withExtendedLifetime(autoCheckpointQuery, { try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") }) try withExtendedLifetime(journalSizeQuery, { try pragma(journalSizeQuery, expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") }) } self.prepareShared() } init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil) { log.debug("Opening connection to \(filename).") self.filename = filename self.queue = dispatch_queue_create("SQLite connection: \(filename)", DISPATCH_QUEUE_SERIAL) if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return nil } if key == nil && prevKey == nil { do { try self.prepareCleartext() } catch { return nil } } else { do { try self.prepareEncrypted(flags, key: key, prevKey: prevKey) } catch { return nil } } } deinit { log.debug("deinit: closing connection on thread \(NSThread.currentThread()).") dispatch_sync(self.queue) { self.closeCustomConnection() } } public var lastInsertedRowID: Int { return Int(sqlite3_last_insert_rowid(sqliteDB)) } public var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } func checkpoint() { self.checkpoint(SQLITE_CHECKPOINT_FULL) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ func checkpoint(mode: Int32) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(NSThread.currentThread()).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } func vacuum() -> NSError? { return self.executeChange("VACUUM") } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. private func createErr(description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if (debug_enabled) { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String.fromCString(sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if (debug_enabled) { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. private func openWithFlags(flags: Int32) -> NSError? { let status = sqlite3_open_v2(filename.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. private func closeCustomConnection(immediately immediately: Bool=false) -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(NSThread.currentThread()).") // TODO: add a lock here? let db = self.sqliteDB self.sqliteDB = nil // Don't bother trying to call sqlite3_close multiple times. guard db != nil else { log.warning("Connection was nil.") return nil } let status = immediately ? sqlite3_close(db) : sqlite3_close_v2(db) // Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if // there are outstanding prepared statements if status != SQLITE_OK { log.error("Got status \(status) while attempting to close.") return createErr("During: closing database with flags", status: Int(status)) } log.debug("Closed \(self.filename).") return nil } public func executeChange(sqlStr: String) -> NSError? { return self.executeChange(sqlStr, withArgs: nil) } /// Executes a change on the database. public func executeChange(sqlStr: String, withArgs args: [AnyObject?]?) -> NSError? { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil log.error("SQL error: \(error1.localizedDescription) for SQL \(sqlStr).") } // Close, not reset -- this isn't going to be reused. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription) for SQL \(sqlStr).") return error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { error = createErr("During: SQL Step \(sqlStr)", status: Int(status)) } return error } func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor // consumes everything. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription).") return Cursor<T>(err: error) } return FilledSQLiteCursor<T>(statement: statement!, factory: factory) } func writeCorruptionInfoForDBNamed(dbFilename: String, toLogger logger: XCGLogger) { dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB detected! DB filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") logger.error("Integrity check:") let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: nil) defer { messages.close() } if messages.status == CursorStatus.Success { for message in messages { logger.error(message) } logger.error("----") } else { logger.error("Couldn't run integrity check: \(messages.statusMessage).") } // Write call stack. logger.error("Call stack: ") for message in NSThread.callStackSymbols() { logger.error(" >> \(message)") } logger.error("----") // Write open file handles. let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: ") for (k, v) in openDescriptors { logger.error(" \(k): \(v)") } logger.error("----") SwiftData.corruptionLogsWritten.insert(dbFilename) } } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ func executeQueryUnsafe<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } } /// Helper for queries that return a single integer result. func IntFactory(row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. class SDRow: SequenceType { // The sqlite statement this row came from. private let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. private let columnNames: [String] private init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row private func getValue(index: Int) -> AnyObject? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: AnyObject? = nil switch type { case SQLITE_NULL, SQLITE_INTEGER: ret = NSNumber(longLong: sqlite3_column_int64(statement.pointer, i)) case SQLITE_TEXT: let text = UnsafePointer<Int8>(sqlite3_column_text(statement.pointer, i)) ret = String.fromCString(text) case SQLITE_BLOB: let blob = sqlite3_column_blob(statement.pointer, i) if blob != nil { let size = sqlite3_column_bytes(statement.pointer, i) ret = NSData(bytes: blob, length: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row subscript(key: Int) -> AnyObject? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. subscript(key: String) -> AnyObject? { get { if let index = columnNames.indexOf(key) { return getValue(index) } return nil } } // Allow iterating through the row. This is currently broken. func generate() -> AnyGenerator<Any> { let nextIndex = 0 return AnyGenerator() { // This crashes the compiler. Yay! if (nextIndex < self.columnNames.count) { return nil // self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { private static func errorMessageFromCode(errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { private init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { var status = CursorStatus.Success var statusMessage = "" let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. private class func getValues(statement: SQLiteDBStatement, factory: (SDRow) -> T, inout status: CursorStatus, inout statusMessage: String) -> [T] { var rows = [T]() var count = 0 status = CursorStatus.Success statusMessage = "Success" var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String.fromCString(sqlite3_column_name(statement.pointer, i))! columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.Failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count += 1 let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return rows } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { private var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. private let factory: (SDRow) -> T // Status of the previous fetch request. private var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. private var _count: Int = 0 override var count: Int { get { if status != .Success { return 0 } return _count } } private var position: Int = -1 { didSet { // If we're already there, shortcut out. if (oldValue == position) { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if (position < oldValue) { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count += 1 self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .Success, msg: "success") } // Helper for finding all the column names in this statement. private lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for i: Int32 in 0 ..< columnCount { let columnName = String.fromCString(sqlite3_column_name(self.statement.pointer, i))! columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .Success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
87d6cc3eae9256af74bfd9867aa6ad03
36.231405
177
0.599778
4.776744
false
false
false
false
noppefoxwolf/SCNVideoWriter
SCNVideoWriter/Classes/SCNVideoWriter.swift
1
4659
// // SCNVideoWriter.swift // Pods-SCNVideoWriter_Example // // Created by Tomoya Hirano on 2017/07/31. // import UIKit import SceneKit import ARKit import AVFoundation public class SCNVideoWriter { private let writer: AVAssetWriter private let input: AVAssetWriterInput private let pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor private let renderer: SCNRenderer private let options: Options private let frameQueue = DispatchQueue(label: "com.noppelabs.SCNVideoWriter.frameQueue") private static let renderQueue = DispatchQueue(label: "com.noppelabs.SCNVideoWriter.renderQueue") private static let renderSemaphore = DispatchSemaphore(value: 3) private var displayLink: CADisplayLink? = nil private var initialTime: CFTimeInterval = 0.0 private var currentTime: CFTimeInterval = 0.0 public var updateFrameHandler: ((_ image: UIImage, _ time: CMTime) -> Void)? = nil private var finishedCompletionHandler: ((_ url: URL) -> Void)? = nil @available(iOS 11.0, *) public convenience init?(withARSCNView view: ARSCNView, options: Options = .default) throws { var options = options options.renderSize = CGSize(width: view.bounds.width * view.contentScaleFactor, height: view.bounds.height * view.contentScaleFactor) try self.init(scene: view.scene, options: options) } public init?(scene: SCNScene, options: Options = .default) throws { self.options = options self.renderer = SCNRenderer(device: nil, options: nil) renderer.scene = scene self.writer = try AVAssetWriter(outputURL: options.outputUrl, fileType: AVFileType(rawValue: options.fileType)) self.input = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: options.assetWriterInputSettings) self.pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: options.sourcePixelBufferAttributes) prepare(with: options) } private func prepare(with options: Options) { if options.deleteFileIfExists { FileController.delete(file: options.outputUrl) } writer.add(input) } public func startWriting() { SCNVideoWriter.renderQueue.async { [weak self] in SCNVideoWriter.renderSemaphore.wait() self?.startDisplayLink() self?.startInputPipeline() } } public func finishWriting(completionHandler: (@escaping (_ url: URL) -> Void)) { let outputUrl = options.outputUrl input.markAsFinished() writer.finishWriting(completionHandler: { [weak self] in completionHandler(outputUrl) self?.stopDisplayLink() SCNVideoWriter.renderSemaphore.signal() }) } private func startDisplayLink() { currentTime = 0.0 initialTime = CFAbsoluteTimeGetCurrent() displayLink = CADisplayLink(target: self, selector: #selector(updateDisplayLink)) displayLink?.preferredFramesPerSecond = options.fps displayLink?.add(to: .main, forMode: .commonModes) } @objc private func updateDisplayLink() { frameQueue.async { [weak self] in guard let input = self?.input, input.isReadyForMoreMediaData else { return } guard let pool = self?.pixelBufferAdaptor.pixelBufferPool else { return } guard let renderSize = self?.options.renderSize else { return } guard let videoSize = self?.options.videoSize else { return } self?.renderSnapshot(with: pool, renderSize: renderSize, videoSize: videoSize) } } private func startInputPipeline() { writer.startWriting() writer.startSession(atSourceTime: kCMTimeZero) input.requestMediaDataWhenReady(on: frameQueue, using: {}) } private func renderSnapshot(with pool: CVPixelBufferPool, renderSize: CGSize, videoSize: CGSize) { autoreleasepool { currentTime = CFAbsoluteTimeGetCurrent() - initialTime let image = renderer.snapshot(atTime: currentTime, with: renderSize, antialiasingMode: .multisampling4X) guard let croppedImage = image.fill(at: videoSize) else { return } guard let pixelBuffer = PixelBufferFactory.make(with: videoSize, from: croppedImage, usingBuffer: pool) else { return } let value: Int64 = Int64(currentTime * CFTimeInterval(options.timeScale)) let presentationTime = CMTimeMake(value, options.timeScale) pixelBufferAdaptor.append(pixelBuffer, withPresentationTime: presentationTime) updateFrameHandler?(croppedImage, presentationTime) } } private func stopDisplayLink() { displayLink?.invalidate() displayLink = nil } }
mit
d0a3b8fb9793dfc291d6c519730a8ef9
38.151261
137
0.714316
4.668337
false
false
false
false
huangboju/Moots
UICollectionViewLayout/MagazineLayout-master/Example/MagazineLayoutExample/Views/Header.swift
1
1771
// Created by bryankeller on 11/30/18. // Copyright © 2018 Airbnb, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import MagazineLayout import UIKit final class Header: MagazineLayoutCollectionReusableView { // MARK: Lifecycle override init(frame: CGRect) { label = UILabel(frame: .zero) super.init(frame: frame) backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.95, alpha: 1) label.font = UIFont.systemFont(ofSize: 48) label.textColor = .black label.numberOfLines = 0 addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 4), label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4), label.topAnchor.constraint(equalTo: topAnchor), label.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Internal override func prepareForReuse() { super.prepareForReuse() label.text = nil } func set(_ headerInfo: HeaderInfo) { label.text = headerInfo.title } // MARK: Private private let label: UILabel }
mit
f9a6b2928c07abe6542fdbf5b18238e1
26.65625
80
0.719209
4.296117
false
false
false
false
vegather/A-World-of-Circles
A World of Circles.playgroundbook/Contents/Sources/SineView.swift
1
4147
// // SineView.swift // Sine Demo // // Created by Vegard Solheim Theriault on 07/03/2017. // Copyright © 2017 Vegard Solheim Theriault. All rights reserved. // import UIKit public class SineView: UIView { private var circlesView: CirclesView? public var periodsToDraw = 2.0 { didSet { circlesView?.periodsToDraw = periodsToDraw } } internal var radiusMultiplier: CGFloat = 60 { didSet { setNeedsDisplay() circlesView?.radiusMultiplier = radiusMultiplier } } public var circles: [Circle]? { didSet { if let circles = circles { setNeedsDisplay() circlesView?.circles = circles circlesView?.reset() } } } public var shouldDrawIndividualSines = false { didSet { setNeedsDisplay() } } private struct Ratios { static let circlesCenter : CGFloat = 0.18 static let graphStartX : CGFloat = 0.4 static let graphEndX : CGFloat = 0.99 } // ------------------------------- // MARK: Initialization // ------------------------------- override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = UIColor(white: 0.95, alpha: 1) contentMode = .redraw circlesView = CirclesView(frame: bounds) if let circles = circles { circlesView?.circles = circles } circlesView?.radiusMultiplier = radiusMultiplier circlesView?.periodsToDraw = periodsToDraw circlesView?.graphStartX = Ratios.graphStartX circlesView?.graphEndX = Ratios.graphEndX circlesView?.circlesCenterX = Ratios.circlesCenter if let circlesView = circlesView { addSubview(circlesView) } } public override func layoutSubviews() { circlesView?.frame = bounds } // ------------------------------- // MARK: Drawing // ------------------------------- public override func draw(_ rect: CGRect) { let circlesCenter = CGPoint(x: bounds.width * Ratios.circlesCenter, y: bounds.midY) drawGrid(withCenterPoint: circlesCenter) guard let circles = circles, circles.count > 0 else { return } let graphRect = CGRect( x: bounds.width * Ratios.graphStartX, y: 0, width: bounds.width * (Ratios.graphEndX - Ratios.graphStartX), height: bounds.height ) if shouldDrawIndividualSines { UIColor(white: 0, alpha: 0.1).setStroke() circles.forEach { graphPath( from: [$0], in: graphRect, withRadiusMultiplier: radiusMultiplier, periodsToDraw: ($0.frequency / circles[0].frequency) * periodsToDraw, lineWidth: 1 ).stroke() } } UIColor(white: 0, alpha: 0.6).setStroke() graphPath( from: circles, in: graphRect, withRadiusMultiplier: radiusMultiplier, periodsToDraw: periodsToDraw, lineWidth: 2 ).stroke() } private func drawGrid(withCenterPoint point: CGPoint) { UIColor(white: 0.9, alpha: 1).setStroke() let horizontalGridLine = UIBezierPath() horizontalGridLine.move(to: CGPoint(x: 0, y: bounds.midY)) horizontalGridLine.addLine(to: CGPoint(x: bounds.width, y: bounds.midY)) horizontalGridLine.stroke() let verticalGridLine = UIBezierPath() verticalGridLine.move(to: CGPoint(x: point.x, y: 0)) verticalGridLine.addLine(to: CGPoint(x: point.x, y: bounds.height)) verticalGridLine.stroke() } }
mit
d276db2b083b2236c69a82f2ef8017fa
28.614286
91
0.539074
4.906509
false
false
false
false
russellladd/CardsAgainstHumanity
CardsAgainstHumanity/Deck.swift
1
846
// // Deck.swift // CardsAgainstHumanity // // Created by Russell Ladd on 10/18/14. // Copyright (c) 2014 GRL5. All rights reserved. // import Foundation struct BlackCard { let text: String } struct WhiteCard { let text: String } struct Deck { static let sharedDeck = Deck() let blackCards: [BlackCard] let whiteCards: [WhiteCard] private init() { let url = NSBundle.mainBundle().URLForResource("Cards", withExtension: "plist")! let dictionary = NSDictionary(contentsOfURL: url) blackCards = map(dictionary["Black Cards"] as [String]) { text in return BlackCard(text: text) } whiteCards = map(dictionary["White Cards"] as [String]) { text in return WhiteCard(text: text) } } }
mit
fb4ee5e39f2505518e23d80978874ae0
19.142857
88
0.583924
4.147059
false
false
false
false
nakiostudio/EasyPeasy
EasyPeasy/UIView+Easy.swift
1
3611
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(iOS) || os(tvOS) import UIKit infix operator <- /** Apply operator definitions */ public extension UIView { /** Operator which applies the attribute given to the view located in the left hand side of it - parameter lhs: `UIView` the attributes will apply to - parameter rhs: Attribute applied to the `UIView` - returns: The array of `NSLayoutConstraints` applied */ @available(iOS, deprecated: 1.5.1, message: "Use easy.layout(_:) instead") @discardableResult static func <- (lhs: UIView, rhs: Attribute) -> [NSLayoutConstraint] { return lhs <- [rhs] } /** Opeator which applies the attributes given to the view located in the left hand side of it - parameter lhs: UIView the attributes will apply to - parameter rhs: Attributes applied to the UIView - returns: The array of `NSLayoutConstraints` applied */ @available(iOS, deprecated: 1.5.1, message: "Use easy.layout(_:) instead") @discardableResult static func <- (lhs: UIView, rhs: [Attribute]) -> [NSLayoutConstraint] { // Disable autoresizing to constraints translation lhs.translatesAutoresizingMaskIntoConstraints = false // Apply attributes and return the installed `NSLayoutConstraints` return lhs.apply(attributes: rhs) } } #endif #if os(iOS) && EASY_RELOAD /** Method that sets up the swizzling of `traitCollectionDidChange` if the compiler flag `EASY_RELOAD` has been defined */ private let traitCollectionDidChangeSwizzling: (UIView.Type) -> () = { view in let originalSelector = #selector(view.traitCollectionDidChange(_:)) let swizzledSelector = #selector(view.easy_traitCollectionDidChange(_:)) let originalMethod = class_getInstanceMethod(view, originalSelector) let swizzledMethod = class_getInstanceMethod(view, swizzledSelector) method_exchangeImplementations(originalMethod, swizzledMethod) } /** `UIView` extension that swizzles `traitCollectionDidChange` if the compiler flag `EASY_RELOAD` has been defined */ extension UIView { /** `traitCollectionDidChange` swizzling */ open override class func initialize() { guard self === UIView.self else { return } traitCollectionDidChangeSwizzling(self) } /** Performs `easy_reload` when the `UITraitCollection` has changed for the current `UIView`, triggering the re-evaluation of the `Attributes` applied */ func easy_traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { self.easy_traitCollectionDidChange(previousTraitCollection) // If at least one `Attribute has been applied to the current // `UIView` then perform `easy_reload` if self.traitCollection.containsTraits(in: previousTraitCollection) == false && self.nodes.values.count > 0 { self.easy.reload() } } } #endif
mit
3513e9a79807698632c47f70b2a02786
34.058252
117
0.675713
4.919619
false
false
false
false
SirapatBoonyasiwapong/grader
Sources/App/ViewRenderers/ViewWrapper.swift
1
1125
import Vapor func render(_ viewName: String, _ data: [String: NodeRepresentable] = [:], for request: HTTP.Request, with renderer: ViewRenderer) throws -> View { var wrappedData = wrap(data, request: request) if let user = request.user { wrappedData = wrap(wrappedData, user: user) } return try renderer.make(viewName, wrappedData, for: request) } fileprivate func wrap(_ data: [String: NodeRepresentable], user: User) -> [String: NodeRepresentable] { var result = data result["authenticated"] = true result["authenticatedUser"] = user result["authenticatedUserHasTeacherRole"] = user.has(role: .teacher) result["acceptUserHasTeacherRole"] = user.has(role: .teacher) result["authenticatedUserHasAdminRole"] = user.has(role: .admin) return result } fileprivate func wrap(_ data: [String: NodeRepresentable], request: HTTP.Request) -> [String: NodeRepresentable] { var result = data let path: String = request.uri.path let pathComponents: [String] = path.components(separatedBy: "/").filter { $0 != "" } result["path"] = pathComponents return result }
mit
0db2bd08e86c8d7312b363c701c34960
39.178571
147
0.694222
4.090909
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/02138-swift-modulefile-maybereadpattern.swift
65
648
// 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 // RUN: not %target-swift-frontend %s -typecheck protocol a { protocol a { typealias b = B)? typealias B : b() { } } } func d: b<T) -> Any) { var d : a { } class func b> { for (self.E == Swift.d == i: NSObject { } protocol b { class B, y: T? { protocol A { switch x } } } } } var d = b(Any) + seq l
apache-2.0
d4e7af934d809120bce51df90d210e0a
19.903226
79
0.669753
3.100478
false
false
false
false
lp1994428/TextKitch
TextKitchen/TextKitchen/classes/Ingredients/Recommend/View/IngreLikeCell.swift
1
2532
// // IngreLikeCell.swift // TextKitchen // // Created by 罗平 on 2016/10/25. // Copyright © 2016年 罗平. All rights reserved. // import UIKit class IngreLikeCell: UITableViewCell { var jumpClosure :(String -> Void)? var listModel :IngreRecommendWidgeList? { didSet{ shwoData() } } private func shwoData() { if listModel?.widget_data?.count > 1 { for var i in 0..<((listModel?.widget_data?.count)!-1){ let imageData = listModel?.widget_data![i] if imageData?.type == "image"{ let imageTag = 200 + i/2 let imageView = contentView.viewWithTag(imageTag) if imageView?.isKindOfClass(UIImageView) == true{ let tmpImageView = imageView as! UIImageView tmpImageView.kf_setImageWithURL(NSURL(string: (imageData?.content)!)) } } //文字 let textData = listModel?.widget_data![i+1] if textData?.type == "text"{ let label = contentView.viewWithTag(300+i/2) if label?.isKindOfClass(UILabel) == true{ let tempLabel = label as! UILabel tempLabel.text = textData?.content } } i += 1 } } } @IBAction func clickBtn(sender: UIButton) { let index = sender.tag-100 let data = listModel?.widget_data![index*2] if data! .link != nil && jumpClosure != nil{ jumpClosure!(data!.link!) } } override func awakeFromNib() { super.awakeFromNib() } //创建cell 的方法 class func createLikeCellFor(tableView:UITableView,atIndexPath:NSIndexPath,listModel:IngreRecommendWidgeList?)->IngreLikeCell { // let cellID = "IngreLikeCell" var cell = tableView.dequeueReusableCellWithIdentifier("cellld") as? IngreLikeCell if nil == cell{ cell = NSBundle.mainBundle().loadNibNamed("IngreLikeCell", owner: nil, options: nil).last as? IngreLikeCell cell!.listModel = listModel } return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
mit
075c2270e841d344c2060cdb84c9f453
31.558442
132
0.516953
5.003992
false
false
false
false
MerrickSapsford/CocoaBar
Example/CocoaBar-Example/Source/Model/BarStyle.swift
1
1456
// // BarStyle.swift // CocoaBar Example // // Created by Merrick Sapsford on 06/06/2016. // Copyright © 2016 Merrick Sapsford. All rights reserved. // import Foundation struct BarStyle: Any { var title: String var styleDescription: String var backgroundStyle: CocoaBarLayout.BackgroundStyle var displayStyle: CocoaBarLayout.DisplayStyle var barStyle: CocoaBar.Style? var layout: CocoaBarLayout? var duration: CocoaBar.DisplayDuration init(title: String, description: String, backgroundStyle: CocoaBarLayout.BackgroundStyle, displayStyle: CocoaBarLayout.DisplayStyle, barStyle:CocoaBar.Style, duration: CocoaBar.DisplayDuration) { self.title = title self.styleDescription = description self.backgroundStyle = backgroundStyle self.displayStyle = displayStyle self.barStyle = barStyle self.duration = duration } init(title: String, description: String, backgroundStyle: CocoaBarLayout.BackgroundStyle, displayStyle: CocoaBarLayout.DisplayStyle, layout: CocoaBarLayout, duration: CocoaBar.DisplayDuration) { self.title = title self.styleDescription = description self.backgroundStyle = backgroundStyle self.displayStyle = displayStyle self.layout = layout self.duration = duration } }
mit
53df9514373713b285d4e11d3a85b24d
27.54902
59
0.665979
4.982877
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCUI/_New_KYC/Limits/LimitedTradeFeature+Conveniences.swift
1
2785
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import Localization import PlatformKit private typealias LocalizedStrings = LocalizationConstants.KYC.LimitsOverview.Feature extension LimitedTradeFeature { var icon: Icon { switch id { case .send: return Icon.send case .receive: return Icon.qrCode case .swap: return Icon.swap case .sell: return Icon.sell case .buyWithCard: return Icon.creditcard case .buyWithBankAccount: return Icon.bank case .withdraw: return Icon.bank case .rewards: return Icon.interest } } var title: String { switch id { case .send: return LocalizedStrings.featureName_send case .receive: return LocalizedStrings.featureName_receive case .swap: return LocalizedStrings.featureName_swap case .sell: return LocalizedStrings.featureName_sell case .buyWithCard: return LocalizedStrings.featureName_buyWithCard case .buyWithBankAccount: return LocalizedStrings.featureName_buyWithBankAccount case .withdraw: return LocalizedStrings.featureName_withdraw case .rewards: return LocalizedStrings.featureName_rewards } } var message: String? { let text: String? switch id { case .send: text = LocalizedStrings.toTradingAccountsOnlyNote case .receive: text = LocalizedStrings.fromTradingAccountsOnlyNote default: text = nil } return text } var valueDisplayString: String { guard enabled else { return LocalizedStrings.disabled } guard let limit = limit else { return LocalizedStrings.enabled } return limit.displayString } var timeframeDisplayString: String? { guard enabled, limit?.value != nil else { return nil } return limit?.timeframeDisplayString } } extension LimitedTradeFeature.PeriodicLimit { var displayString: String { guard let value = value else { return LocalizedStrings.unlimited } return value.shortDisplayString } var timeframeDisplayString: String { let format: String switch period { case .day: format = LocalizedStrings.limitedPerDay case .month: format = LocalizedStrings.limitedPerMonth case .year: format = LocalizedStrings.limitedPerYear } return format } }
lgpl-3.0
bd993c7fac6fa4479e1346c4614b1974
25.514286
85
0.600216
5.635628
false
false
false
false
theMedvedev/eduConnect
eduConnect/SponsorViewController.swift
1
7506
// // SponsorViewController.swift // eduConnect // // Created by Alexey Medvedev on 1/14/17. // Copyright © 2017 #nyc1-2devsandarussian. All rights reserved. // import UIKit class SponsorViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } // Demo Data struct boardMember { var name: String var title: String var bio: String } let allenBlue = boardMember(name: "Allen Blue", title: "Co-Founder, LinkedIn", bio: "Product innovator and generalist, focused on early-stage social internet projects. Experienced product executive, manager and designer, with broad technical and design skills. Greatest strengths in large-scale, integrative problem solving. Interested in enabling users to grow, succeed, and contribute, while building powerful products at the center of successful businesses.") let judySpitz = boardMember(name: "Judy Spitz", title: "Founding Program Director: Women in Technology and Entrepreneurship in New York (WiTNY) at Cornell Tech", bio: "Dr. Judith Spitz is a recognized leader with over 20 years of advanced technology experience in the communications industry. She is a proven senior executive with a track record of leading and successfully delivering complex transformational programs that require both technology and business process innovation.") let fredWilson = boardMember(name: "Fred Wilson", title: "Managing Partner, Union Square Ventures", bio: "Associate, Euclid Partners, 1987-1991 General Partner; Euclid Partners, 1991-1996; Founder and Managing Partner, Flatiron Partners, 1996-PresentFounder and Partner, Union Square Ventures, 2003-Present") let kevinRyan = boardMember(name: "Kevin Ryan", title: "Chairman, Gilt Groupe; Founder, MongoDB, Business Insider, Zola", bio: "Kevin P. Ryan is an American Internet entrepreneur in the United States who has founded several New York-based businesses, including Gilt Groupe, Business Insider, Zola Registry and MongoDB, and helped build DoubleClick from 1996 to 2005, first as president and later as CEO. He fostered DoubleClick's growth from a 20-person startup to a global leader with over 1,500 employees. Ryan built DoubleClick into a multi-billion dollar global industry leader. Under his direction, DoubleClick was awarded the title of New York Company of the Year by Silicon Alley Reporter.") let donDuet = boardMember(name: "Don Duet", title: "Co-Head of Technology, Goldman Sachs", bio: "Don is head of the Technology Division. He serves on the Firmwide Risk Committee, Firmwide Technology Risk Committee the Technology Executive Leadership Group and is co-chair of the Investment Banking Division's Technology Investment Committee.") let serkanPiantino = boardMember(name: "Serkan Piantino", title: "Director of Engineering, Facebook AI Research", bio: "I co-lead the Facebook AI Research team with Yann LeCun, and specifically oversee our software and hardware infrastructure efforts for deep learning and parallel GPU and CPU training of Artificial Neural Networks.") let chadDickerson = boardMember(name: "Chad Dickerson", title: "CEO, Etsy", bio: "Internet executive with 20 years experience, including engineering, product development, general management, business operations, and strategy.Currently CEO at Etsy. Prior to that, Yahoo!, IDG, and Salon.com.") let jonOringer = boardMember(name: "Jon Oringer", title: "CEO, Shutterstock", bio: "") let yanceyStrickler = boardMember(name: "Yancey Strickler", title: "CEO, Kickstarter", bio: "") let charlesPhillips = boardMember(name: "Charles Phillips", title: "CEO, Infor", bio: "") let williamFloyd = boardMember(name: "William Floyd", title: "Head of External Affairs, Google NY", bio: "") let marissaShorenstein = boardMember(name: "Marissa Shorenstein", title: "President, AT&T New York", bio: "") let oliverKharraz = boardMember(name: "Oliver Kharraz", title: "Co-Founder & President, ZocDoc", bio: "") let jesseHertzberg = boardMember(name: "Jesse Hertzberg", title: "CEO, Livestream", bio: "") let davidFullerton = boardMember(name: "David Fullerton", title: "VP of Engineering, Stack Exchange ", bio: "") let eliotHorowitz = boardMember(name: "Eliot Horowitz", title: "Co-Founder and CTO, MongoDB", bio: "") let jonWilliams = boardMember(name: "Jon Williams", title: "Co-founder, CTO Club", bio: "") let johnPaulFarmer = boardMember(name: "John Paul Farmer", title: "Director of Tech & Civic Innovation, Microsoft NY", bio: "") let andrewPile = boardMember(name: "Andrew Pile", title: "CTO, Vimeo", bio: "") let davidTisch = boardMember(name: "David Tisch", title: "Co-founder, Techstars; Head of Startup Studio, Cornell Tech;", bio: "") let chrisHughes = boardMember(name: "Chris Hughes", title: "Managing Partner, BoxGroup", bio: "") let aliMarano = boardMember(name: "Ali Marano", title: "Co-Founder, Facebook; Publisher, The New Republic", bio: "") let brandonAtkinson = boardMember(name: "Brandon Atkinson", title: "Head of Technology and Social Good, JP Morgan", bio: "") let jocelynLeavitt = boardMember(name: "Jocelyn Leavitt", title: "Chief People Officer, AppNexus", bio: "") let shankarArumugavelu = boardMember(name: "Shankar Arumugavelu", title: "Co-Founder and CEO, Hopscotch", bio: "") let antoineVeliz = boardMember(name: "Antoine Veliz", title: "CIO, Verizon Wireless", bio: "") func getSponsorData() { } }
mit
eeadd5b5d8c534678aa31c36d803cebf
55.007463
609
0.544437
5.030161
false
false
false
false
collegboi/DIT-Timetable-iOS
DIT-Timetable-V2/Controller/Database.swift
1
11900
// // Database.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 18/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import Foundation import Realm class Database { var backgroundQueue: DispatchQueue? var realm : RLMRealm? init() { let directory: NSURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.barnard.dit-timetable.today")! as NSURL let realmPath = directory.appendingPathComponent("default.realm") let realmConfig = RLMRealmConfiguration.default() realmConfig.fileURL = realmPath realmConfig.schemaVersion = 3 realmConfig.migrationBlock = { migration, oldSchemaVersion in if (oldSchemaVersion < 3) { } } self.realm = try! RLMRealm(configuration: realmConfig) RLMRealmConfiguration.setDefault(realmConfig) } private func createNewRealmInstance() -> RLMRealm? { let directory: NSURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.barnard.dit-timetable.today")! as NSURL let realmPath = directory.appendingPathComponent("default.realm") let realmConfig = RLMRealmConfiguration.default() realmConfig.fileURL = realmPath realmConfig.schemaVersion = 3 realmConfig.migrationBlock = { migration, oldSchemaVersion in if (oldSchemaVersion < 3) { } } return try! RLMRealm(configuration: realmConfig) } @discardableResult func saveClass( myClass : Class ) -> Int { if(myClass.id == -1 ) { myClass.id = self.getNextPrimaryKeyID() } if let realm = self.createNewRealmInstance() { realm.beginWriteTransaction() realm.add(myClass) do { try realm.commitWriteTransaction() } catch { print("not commiting transaction") } } return myClass.id } func removeAll() { if let realm = realm { realm.beginWriteTransaction() realm.deleteAllObjects() try! realm.commitWriteTransaction() } } func updateTimetable( timetable : Timetable) { let updateClass = Class() updateClass.id = timetable.id updateClass.lecture = timetable.lecture updateClass.room = timetable.room updateClass.timeStart = timetable.timeStart updateClass.timeEnd = timetable.timeEnd updateClass.notifOn = timetable.notifOn updateClass.name = timetable.name updateClass.groups = timetable.groups updateClass.day = timetable.dayNo self.editClass( myClass: updateClass) } func makeClass( timetable : Timetable) -> Class { let updateClass = Class() updateClass.id = timetable.id updateClass.lecture = timetable.lecture updateClass.room = timetable.room updateClass.timeStart = timetable.timeStart updateClass.timeEnd = timetable.timeEnd updateClass.notifOn = timetable.notifOn updateClass.name = timetable.name updateClass.groups = timetable.groups updateClass.day = timetable.dayNo return updateClass } func deleteClass( classID : Int ) { let predicate = NSPredicate(format: "id = %d", classID) guard let realm = self.createNewRealmInstance() else { return } let dataSource: RLMResults = Class.objects(in: realm, with: predicate) if(Int(dataSource.count) > 0) { guard let deleteClass = dataSource[UInt(0)] as? Class else { return } if(realm.inWriteTransaction) { realm.cancelWriteTransaction() } realm.beginWriteTransaction() realm.delete(deleteClass) do { try realm.commitWriteTransaction() } catch { print("edit: not commiting transaction") } } } func getClass( classID : Int) -> Class { let predicate = NSPredicate(format: "id = %d", classID) guard let realm = self.createNewRealmInstance() else { return Class() } let dataSource: RLMResults = Class.objects(in: realm, with: predicate) if(Int(dataSource.count) > 0) { guard let curClass = dataSource[UInt(0)] as? Class else { return Class() } return curClass } else { return Class() } } func getSavedClassesCount() -> Int { let results: RLMResults = Class.allObjects() return Int(results.count) } func editClass( myClass: Class ) { if let realm = self.createNewRealmInstance() { if(realm.inWriteTransaction) { realm.cancelWriteTransaction() } realm.beginWriteTransaction() realm.addOrUpdate(myClass) do { try realm.commitWriteTransaction() } catch { print("edit: not commiting transaction") } } } func getNextPrimaryKeyID() -> Int { var id = 0 guard let realm = self.realm else { return id } let dataSource: RLMResults = Class.allObjects(in: realm).sortedResults(usingKeyPath: "id", ascending: true) if (dataSource.count) > 0 { let curClass = dataSource[(dataSource.count)-1] as! Class id = curClass.id } return id + 1 } func parseTimetable(module: String, room: String) -> (name: String, code: String, room: String) { var name: String = module var code: String = "" var roomVal: String = room let moduleParts = module.components(separatedBy: " ") if(moduleParts.count >= 3 ) { code = moduleParts[moduleParts.count-2] + " " + moduleParts[moduleParts.count-1] let moduleNameParts = module.components(separatedBy: code) if(moduleNameParts.count >= 2) { name = moduleNameParts[0] } } let roomsParts = room.components(separatedBy: ",") if(roomsParts.count >= 2) { let roomNo = roomsParts[1] let roomNameParts = roomsParts[0].components(separatedBy: " ") for roomPart in roomNameParts { roomVal += roomPart[0] } roomVal += " " + roomNo } else { roomVal = room } return(name, code, roomVal) } func makeTimetablFormClass(curClass: Class) -> Timetable { let newClass = Timetable() newClass.id = curClass.id newClass.lecture = curClass.lecture newClass.timeStart = curClass.timeStart newClass.timeEnd = curClass.timeEnd newClass.dayNo = curClass.day newClass.name = curClass.name newClass.groups = curClass.groups newClass.room = curClass.room newClass.notifOn = curClass.notifOn newClass.timeStartDate = newClass.timeStart.convertToDate() newClass.timeEndDate = newClass.timeEnd.convertToDate() let timetableParts = parseTimetable(module: newClass.name, room: newClass.room) newClass.moduleCode = timetableParts.code newClass.moduleName = timetableParts.name newClass.roomNo = timetableParts.room return newClass } func getDayTimetable( dayNo : Int ) ->[Timetable] { var dayTimetable = [Timetable]() let predicate = NSPredicate(format: "day = %d", dayNo) guard let realm = self.realm else { return [Timetable]() } let dataSource: RLMResults = Class.objects(in: realm, with: predicate).sortedResults(usingKeyPath: "timeStart", ascending: true) for index in 0..<Int(dataSource.count) { let curClass = dataSource[UInt(index)] as! Class let timetable = self.makeTimetablFormClass(curClass: curClass) dayTimetable.append(timetable) } return dayTimetable } func getClassNow() -> Timetable? { let today = Date() let day = today.weekday() let indexVal = (day+5) % 7 let predicate = NSPredicate(format: "day = %d", indexVal) guard let realm = self.realm else { return nil } let dataSource: RLMResults = Class.objects(in: realm, with: predicate).sortedResults(usingKeyPath: "timeStart", ascending: true) for index in 0..<Int(dataSource.count) { let curClass = dataSource[UInt(index)] as! Class let timetable = self.makeTimetablFormClass(curClass: curClass) let startHour = timetable.timeStartDate.hour() let endHour = timetable.timeEndDate.hour() let nowHour = today.hour() if(nowHour >= startHour && nowHour <= endHour ) { return timetable } } return nil } func getDayTimetableAfterNow( dayNo : Int ) ->[Timetable] { var dayTimetable = [Timetable]() let predicate = NSPredicate(format: "day = %d", dayNo) guard let realm = self.realm else { return [Timetable]() } let dataSource: RLMResults = Class.objects(in: realm, with: predicate).sortedResults(usingKeyPath: "timeStart", ascending: true) for index in 0..<Int(dataSource.count) { let curClass = dataSource[UInt(index)] as! Class let nowTime = Date() let hour = nowTime.hour() let classTimeParts = curClass.timeStart.components(separatedBy: ":") let classTimeEndParts = curClass.timeEnd.components(separatedBy: ":") guard let classTimeHr = Int(classTimeParts[0]) else { continue } guard let classTimeEndHr = Int(classTimeEndParts[0]) else { continue } if(classTimeHr >= hour || hour < classTimeEndHr ) { let timetable = self.makeTimetablFormClass(curClass: curClass) dayTimetable.append(timetable) } } return dayTimetable } func getAllTimetables() -> [AllTimetables] { var allTimetables = [AllTimetables]() guard let realm = self.realm else { return [AllTimetables]() } for _ in 1...7 { let newTimetable = AllTimetables() allTimetables.append(newTimetable) } let dataSource = Class.allObjects(in: realm).sortedResults(usingKeyPath: "timeStart", ascending: true) for index in 0..<Int(dataSource.count) { let curClass = dataSource[UInt(index)] as! Class let timetable = self.makeTimetablFormClass(curClass: curClass) allTimetables[curClass.day].timetable.append(timetable) } return allTimetables } }
mit
2aaa310f931d9a41dda46cbcb77016e2
30.067885
149
0.549962
5.117849
false
false
false
false
luckymore0520/GreenTea
Loyalty/Vendor/ExSwift/Float.swift
3
1622
// // Float.swift // ExSwift // // Created by pNre on 04/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension Float { /** Absolute value. - returns: fabs(self) */ func abs () -> Float { return fabsf(self) } /** Squared root. - returns: sqrtf(self) */ func sqrt () -> Float { return sqrtf(self) } /** Rounds self to the largest integer <= self. - returns: floorf(self) */ func floor () -> Float { return floorf(self) } /** Rounds self to the smallest integer >= self. - returns: ceilf(self) */ func ceil () -> Float { return ceilf(self) } /** Rounds self to the nearest integer. - returns: roundf(self) */ func round () -> Float { return roundf(self) } /** Clamps self to a specified range. - parameter min: Lower bound - parameter max: Upper bound - returns: Clamped value */ func clamp (min: Float, _ max: Float) -> Float { return Swift.max(min, Swift.min(max, self)) } /** Random float between min and max (inclusive). - parameter min: - parameter max: - returns: Random number */ static func random(min: Float = 0, max: Float) -> Float { let diff = max - min; let rand = Float(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Float(RAND_MAX)) * diff) + min; } }
mit
67552b3f840c7856ffc9246b8665e8c3
18.542169
63
0.493218
4.075377
false
false
false
false
VikingDen/actor-platform
actor-apps/app-ios/ActorApp/Resources/AppTheme.swift
10
14870
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation var MainAppTheme = AppTheme() class AppTheme { var navigation: AppNavigationBar { get { return AppNavigationBar() } } var tab: AppTabBar { get { return AppTabBar() } } var search: AppSearchBar { get { return AppSearchBar() } } var list: AppList { get { return AppList() } } var bubbles: ChatBubbles { get { return ChatBubbles() } } var text: AppText { get { return AppText() } } var chat: AppChat { get { return AppChat() } } var common: AppCommon { get { return AppCommon() } } var placeholder: AppPlaceholder { get { return AppPlaceholder() } } func applyAppearance(application: UIApplication) { navigation.applyAppearance(application) tab.applyAppearance(application) search.applyAppearance(application) list.applyAppearance(application) } } class AppText { var textPrimary: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var bigAvatarPrimary: UIColor { get { return UIColor.whiteColor() } } var bigAvatarSecondary: UIColor { get { return UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1) } } } class AppPlaceholder { var textTitle: UIColor { get { return UIColor.RGB(0x5085CB) } } var textHint: UIColor { get { return UIColor(red: 80/255.0, green: 80/255.0, blue: 80/255.0, alpha: 1.0) } } } class AppChat { var chatField: UIColor { get { return UIColor.whiteColor() } } var attachColor: UIColor { get { return UIColor.RGB(0x5085CB) } } var sendEnabled: UIColor { get { return UIColor.RGB(0x50A1D6) } } var sendDisabled: UIColor { get { return UIColor.alphaBlack(0.56) } } var profileBgTint: UIColor { get { return UIColor.RGB(0x5085CB) } } var autocompleteHighlight: UIColor { get { return UIColor.RGB(0x5085CB) } } } class AppCommon { var isDarkKeyboard: Bool { get { return false } } var tokenFieldText: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldTextSelected: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldBg: UIColor { get { return UIColor.RGB(0x5085CB) } } var placeholders: [UIColor] { get { return [UIColor.RGB(0x59b7d3), UIColor.RGB(0x1d4e6f), UIColor.RGB(0x995794), UIColor.RGB(0xff506c), UIColor.RGB(0xf99341), UIColor.RGB(0xe4d027), UIColor.RGB(0x87c743)] } } } class ChatBubbles { // Basic colors var text : UIColor { get { return UIColor.RGB(0x141617) } } var textUnsupported : UIColor { get { return UIColor.RGB(0x50b1ae) } } var bgOut: UIColor { get { return UIColor.RGB(0xD2FEFD) } } var bgOutBorder: UIColor { get { return UIColor.RGB(0x99E4E3) } } var bgIn : UIColor { get { return UIColor.whiteColor() } } var bgInBorder:UIColor { get { return UIColor.RGB(0xCCCCCC) } } var statusActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDanger : UIColor { get { return UIColor.redColor() } } var statusMediaActive : UIColor { get { return UIColor.RGB(0x1ed2f9) } } var statusMediaPassive : UIColor { get { return UIColor.whiteColor() } } // TODO: Fix var statusMediaDanger : UIColor { get { return UIColor.redColor() } } var statusDialogActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusDialogPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDialogDanger : UIColor { get { return UIColor.redColor() } } // Dialog-based colors var statusDialogSending : UIColor { get { return statusDialogPassive } } var statusDialogSent : UIColor { get { return statusDialogPassive } } var statusDialogReceived : UIColor { get { return statusDialogPassive } } var statusDialogRead : UIColor { get { return statusDialogActive } } var statusDialogError : UIColor { get { return statusDialogDanger } } // Text-based bubble colors var statusSending : UIColor { get { return statusPassive } } var statusSent : UIColor { get { return statusPassive } } var statusReceived : UIColor { get { return statusPassive } } var statusRead : UIColor { get { return statusActive } } var statusError : UIColor { get { return statusDanger } } var textBgOut: UIColor { get { return bgOut } } var textBgOutBorder : UIColor { get { return bgOutBorder } } var textBgIn : UIColor { get { return bgIn } } var textBgInBorder : UIColor { get { return bgInBorder } } var textDateOut : UIColor { get { return UIColor.alphaBlack(0.27) } } var textDateIn : UIColor { get { return UIColor.RGB(0x979797) } } var textOut : UIColor { get { return text } } var textIn : UIColor { get { return text } } var textUnsupportedOut : UIColor { get { return textUnsupported } } var textUnsupportedIn : UIColor { get { return textUnsupported } } // Media-based bubble colors var statusMediaSending : UIColor { get { return statusMediaPassive } } var statusMediaSent : UIColor { get { return statusMediaPassive } } var statusMediaReceived : UIColor { get { return statusMediaPassive } } var statusMediaRead : UIColor { get { return statusMediaActive } } var statusMediaError : UIColor { get { return statusMediaDanger } } var mediaBgOut: UIColor { get { return UIColor.whiteColor() } } var mediaBgOutBorder: UIColor { get { return UIColor.RGB(0xCCCCCC) } } var mediaBgIn: UIColor { get { return mediaBgOut } } var mediaBgInBorder: UIColor { get { return mediaBgOutBorder } } var mediaDateBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.54) } } var mediaDate: UIColor { get { return UIColor.whiteColor() } } // Service-based bubble colors var serviceBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.56) } } var chatBgTint: UIColor { get { return UIColor.RGB(0xe7e0c4) } } } class AppList { var actionColor : UIColor { get { return UIColor.RGB(0x5085CB) } } var bgColor: UIColor { get { return UIColor.whiteColor() } } var bgSelectedColor : UIColor { get { return UIColor.RGB(0xd9d9d9) } } var backyardColor : UIColor { get { return UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1) } } var separatorColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x1e/255.0) } } var textColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var hintColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } var sectionColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } // var arrowColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogText: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var dialogDate: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var unreadText: UIColor { get { return UIColor.whiteColor() } } var unreadBg: UIColor { get { return UIColor.RGB(0x50A1D6) } } var contactsTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var contactsShortTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } func applyAppearance(application: UIApplication) { UITableViewHeaderFooterView.appearance().tintColor = sectionColor } } class AppSearchBar { var statusBarLightContent : Bool { get { return false } } var backgroundColor : UIColor { get { return UIColor.RGB(0xf1f1f1) } } var cancelColor : UIColor { get { return UIColor.RGB(0x8E8E93) } } var fieldBackgroundColor: UIColor { get { return UIColor.whiteColor() } } var fieldTextColor: UIColor { get { return UIColor.blackColor().alpha(0.56) } } func applyAppearance(application: UIApplication) { // SearchBar Text Color var textField = UITextField.my_appearanceWhenContainedIn(UISearchBar.self) // textField.tintColor = UIColor.redColor() var font = UIFont(name: "HelveticaNeue", size: 14.0) textField.defaultTextAttributes = [NSFontAttributeName: font!, NSForegroundColorAttributeName : fieldTextColor] } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func styleSearchBar(searchBar: UISearchBar) { // SearchBar Minimal Style searchBar.searchBarStyle = UISearchBarStyle.Default // SearchBar Transculent searchBar.translucent = false // SearchBar placeholder animation fix searchBar.placeholder = ""; // SearchBar background color searchBar.barTintColor = backgroundColor.forTransparentBar() searchBar.setBackgroundImage(Imaging.imageWithColor(backgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) searchBar.backgroundColor = backgroundColor // SearchBar field color var fieldBg = Imaging.imageWithColor(fieldBackgroundColor, size: CGSize(width: 14,height: 28)) .roundCorners(14, h: 28, roundSize: 4) searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal) // SearchBar cancel color searchBar.tintColor = cancelColor } } class AppTabBar { private let mainColor = UIColor.RGB(0x5085CB) var backgroundColor : UIColor { get { return UIColor.whiteColor() } } var showText : Bool { get { return true } } var selectedIconColor: UIColor { get { return mainColor } } var selectedTextColor : UIColor { get { return mainColor } } var unselectedIconColor:UIColor { get { return mainColor.alpha(0.56) } } var unselectedTextColor : UIColor { get { return mainColor.alpha(0.56) } } var barShadow : String? { get { return "CardTop2" } } func createSelectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(selectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func createUnselectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(unselectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func applyAppearance(application: UIApplication) { var tabBar = UITabBar.appearance() // TabBar Background color tabBar.barTintColor = backgroundColor; // TabBar Shadow if (barShadow != nil) { tabBar.shadowImage = UIImage(named: barShadow!); } else { tabBar.shadowImage = nil } var tabBarItem = UITabBarItem.appearance() // TabBar Unselected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: unselectedTextColor], forState: UIControlState.Normal) // TabBar Selected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: selectedTextColor], forState: UIControlState.Selected) } } class AppNavigationBar { var statusBarLightContent : Bool { get { return true } } var barColor:UIColor { get { return /*UIColor.RGB(0x5085CB)*/ UIColor.RGB(0x3576cc) } } var barSolidColor:UIColor { get { return UIColor.RGB(0x5085CB) } } var titleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleActiveColor: UIColor { get { return UIColor.whiteColor() } } var shadowImage : String? { get { return nil } } var progressPrimary: UIColor { get { return UIColor.RGB(0x1484ee) } } var progressSecondary: UIColor { get { return UIColor.RGB(0xaccceb) } } func applyAppearance(application: UIApplication) { // StatusBar style if (statusBarLightContent) { application.statusBarStyle = UIStatusBarStyle.LightContent } else { application.statusBarStyle = UIStatusBarStyle.Default } var navAppearance = UINavigationBar.appearance(); // NavigationBar Icon navAppearance.tintColor = titleColor; // NavigationBar Text navAppearance.titleTextAttributes = [NSForegroundColorAttributeName: titleColor]; // NavigationBar Background navAppearance.barTintColor = barColor; // navAppearance.setBackgroundImage(Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 1)), forBarMetrics: UIBarMetrics.Default) // navAppearance.shadowImage = Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 2)) // Small hack for correct background color UISearchBar.appearance().backgroundColor = barColor // NavigationBar Shadow // navAppearance.shadowImage = nil // if (shadowImage == nil) { // navAppearance.shadowImage = UIImage() // navAppearance.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) // } else { // navAppearance.shadowImage = UIImage(named: shadowImage!) // } } func applyAuthStatusBar() { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func applyStatusBarFast() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false) } } }
mit
92c338deda8dd44b9e3bc0bfafb1388d
41.610315
181
0.656355
4.395507
false
false
false
false
FRA7/FJWeibo
FJWeibo/Classes/Home/Popover/PopoverPresentationController.swift
1
1603
// // PopoverPresentationController.swift // FJWeibo // // Created by Francis on 3/1/16. // Copyright © 2016 FRAJ. All rights reserved. // import UIKit class PopoverPresentationController:UIPresentationController { var presentFrame = CGRectZero override init(presentedViewController: UIViewController, presentingViewController: UIViewController) { super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController) } override func containerViewWillLayoutSubviews() { if presentFrame == CGRectZero{ //1.设置弹出视图的大小 // let preX = UIScreen.mainScreen().bounds.size.width / 2 - 100 // print(preX) presentedView()?.frame = CGRect(x: 100, y: 56, width: 200, height: 200) }else{ presentedView()?.frame = presentFrame } //2.增加蒙版 containerView?.insertSubview(coverView, atIndex: 0) } //MARK: - 懒加载 private lazy var coverView:UIView = { //1.创建view let v = UIView() v.backgroundColor = UIColor(white: 0.0, alpha: 0.3) v.frame = UIScreen.mainScreen().bounds //2.添加监听 let tap = UITapGestureRecognizer(target: self, action: #selector(PopoverPresentationController.close)) v.addGestureRecognizer(tap) return v }() func close(){ presentedViewController.dismissViewControllerAnimated(true, completion: nil) } }
mit
8c4e04a80e685d25a438aa071e40f823
27.851852
120
0.619384
5.009646
false
false
false
false
IngmarStein/swift
test/IRGen/same_type_constraints.swift
3
1517
// RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // <rdar://problem/21665983> IRGen crash with protocol extension involving same-type constraint to X<T> public struct DefaultFoo<T> { var t: T? } public protocol P { associatedtype Foo } public extension P where Foo == DefaultFoo<Self> { public func foo() -> DefaultFoo<Self> { return DefaultFoo() } } // CHECK: define{{( protected)?}} void @_TFe21same_type_constraintsRxS_1Pwx3FoozGVS_10DefaultFoox_rS0_3foofT_GS2_x_ // <rdar://26873036> IRGen crash with derived class declaring same-type constraint on constrained associatedtype. public class C1<T: Equatable> { } public class C2<T: Equatable, U: P where T == U.Foo>: C1<T> {} // CHECK: define{{( protected)?}} void @_TFC21same_type_constraints2C1D public protocol MyHashable {} public protocol DataType : MyHashable {} public protocol E { associatedtype Data: DataType } struct Dict<V : MyHashable, K> {} struct Val {} public class GenericKlazz<T: DataType, R: E> : E where R.Data == T { public typealias Data = T var d: Dict<T, Val> init() { d = Dict() } } // This used to hit an infinite loop - <rdar://problem/27018457> public protocol CodingType { associatedtype ValueType } public protocol ValueCoding { associatedtype Coder: CodingType } func foo<Self>(s: Self) where Self : CodingType, Self.ValueType: ValueCoding, Self.ValueType.Coder == Self { print(Self.ValueType.self) }
apache-2.0
1df8cdec8e65e577ab1dded2c8d31640
24.283333
118
0.705339
3.378619
false
false
false
false
danstorre/CookIt
CookIt/CookIt/CoreDataStack.swift
1
5852
// // CoreDataStack.swift // VirtualTourist // // Created by Daniel Torres on 1/13/17. // Copyright © 2017 Daniel Torres. All rights reserved. // import CoreData // MARK: - CoreDataStack struct CoreDataStack { // MARK: Properties private let model: NSManagedObjectModel internal let coordinator: NSPersistentStoreCoordinator private let modelURL: URL internal let dbURL: URL internal let persistingContext: NSManagedObjectContext internal let backgroundContext: NSManagedObjectContext let context: NSManagedObjectContext static let shared = CoreDataStack(modelName: "CookIt")! // MARK: Initializers init?(modelName: String) { // Assumes the model is in the main bundle guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd") else { print("Unable to find \(modelName)in the main bundle") return nil } self.modelURL = modelURL // Try to create the model from the URL guard let model = NSManagedObjectModel(contentsOf: modelURL) else { print("unable to create a model from \(modelURL)") return nil } self.model = model // Create the store coordinator coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) // Create a persistingContext (private queue) and a child one (main queue) // create a context and add connect it to the coordinator persistingContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) persistingContext.persistentStoreCoordinator = coordinator context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.parent = persistingContext // Create a background context child of main context backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundContext.parent = context // Add a SQLite store located in the documents folder let fm = FileManager.default guard let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first else { print("Unable to reach the documents folder") return nil } self.dbURL = docUrl.appendingPathComponent("model.sqlite") // Options for migration let options = [NSInferMappingModelAutomaticallyOption: true,NSMigratePersistentStoresAutomaticallyOption: true] do { try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: options as [NSObject : AnyObject]?) } catch { print("unable to add store at \(dbURL)") } } // MARK: Utils func addStoreCoordinator(_ storeType: String, configuration: String?, storeURL: URL, options : [NSObject:AnyObject]?) throws { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: nil) } } // MARK: - CoreDataStack (Removing Data) internal extension CoreDataStack { func dropAllData() throws { // delete all the objects in the db. This won't delete the files, it will // just leave empty tables. try coordinator.destroyPersistentStore(at: dbURL, ofType: NSSQLiteStoreType , options: nil) try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: nil) } } // MARK: - CoreDataStack (Batch Processing in the Background) extension CoreDataStack { typealias Batch = (_ workerContext: NSManagedObjectContext) -> () func performBackgroundBatchOperation(_ batch: @escaping Batch) { backgroundContext.perform() { batch(self.backgroundContext) // Save it to the parent context, so normal saving // can work do { try self.backgroundContext.save() } catch { fatalError("Error while saving backgroundContext: \(error)") } } } } // MARK: - CoreDataStack (Save Data) extension CoreDataStack { func save() { // We call this synchronously, but it's a very fast // operation (it doesn't hit the disk). We need to know // when it ends so we can call the next save (on the persisting // context). This last one might take some time and is done // in a background queue context.performAndWait() { if self.context.hasChanges { do { try self.context.save() } catch { fatalError("Error while saving main context: \(error)") } // now we save in the background self.persistingContext.perform() { do { try self.persistingContext.save() } catch { fatalError("Error while saving persisting context: \(error)") } } } } } func autoSave(_ delayInSeconds : Int) { if delayInSeconds > 0 { do { try self.context.save() print("Autosaving") } catch { print("Error while autosaving") } let delayInNanoSeconds = UInt64(delayInSeconds) * NSEC_PER_SEC let time = DispatchTime.now() + Double(Int64(delayInNanoSeconds)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.autoSave(delayInSeconds) } } } }
mit
6a2d41a6b2b2be3d0795c0cb368a8db0
33.417647
136
0.599385
5.65314
false
false
false
false
naturaln0va/Doodler_iOS
DocumentsController.swift
1
6070
import Foundation class DocumentsController { static let sharedController = DocumentsController() private let fileManager = FileManager.default private let fileQueue = DispatchQueue(label: "io.ackermann.documents.io") private let doodleSavePath: URL? = { guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.io.ackermann.doodlesharing") else { print("Failed to create the doodle documents directory.") return nil } var wholeURL = url wholeURL.appendPathComponent("/doodles") if !FileManager.default.fileExists(atPath: url.absoluteString) { do { try FileManager.default.createDirectory(at: wholeURL, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { if error.code == 516 { return wholeURL } print("Error creating the doodle documents directory. Error: \(error)") return nil } } return wholeURL }() private let stickerSavePath: URL? = { guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.io.ackermann.doodlesharing") else { print("Failed to create the doodle documents directory.") return nil } var wholeURL = url wholeURL.appendPathComponent("/stickers") if !FileManager.default.fileExists(atPath: url.absoluteString) { do { try FileManager.default.createDirectory(at: wholeURL, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { if error.code == 516 { return wholeURL } print("Error creating the doodle documents directory. Error: \(error)") return nil } } return wholeURL }() var doodles: [Doodle] { guard let filePath = doodleSavePath else { return [] } var doodles = [Doodle]() if let doodleURLs = try? fileManager.contentsOfDirectory(at: filePath, includingPropertiesForKeys: nil, options: []) { for url in doodleURLs { if let data = try? Data(contentsOf: url, options: []) { if let dataDict = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Any] { if let doodle = Doodle(serializedDictionary: dataDict) { doodles.append(doodle) } } } } } return doodles } var stickerURLs: [URL] { guard let filePath = stickerSavePath else { return [] } var urls = [URL]() if let fileURLs = try? fileManager.contentsOfDirectory(at: filePath, includingPropertiesForKeys: nil, options: []) { urls.append(contentsOf: fileURLs) } return urls } func save(doodle: Doodle, completion: ((Bool) -> Void)?) { guard let savePath = doodleSavePath else { DispatchQueue.main.async { completion?(false) } return } var fullFilePath = savePath fullFilePath.appendPathComponent(doodle.fileName) var doodleToSave = doodle doodleToSave.updatedDate = Date() fileQueue.async { do { try NSKeyedArchiver.archivedData(withRootObject: doodleToSave.serializedDictionary).write(to: fullFilePath) } catch let error { print("Error saving file to path: \(fullFilePath)\nError: \(error)") DispatchQueue.main.async { completion?(false) } return } if let stickerSavePath = self.stickerSavePath { let fullStickerSavePath = stickerSavePath.appendingPathComponent(doodle.stickerFileName) do { try doodle.stickerImageData.write(to: fullStickerSavePath, options: .atomic) } catch let error { print("Error saving sticker to path: \(fullStickerSavePath)\nError: \(error)") } } DispatchQueue.main.async { completion?(true) } } } func delete(doodles: [Doodle], completion: ((Bool) -> Void)?) { guard let savePath = doodleSavePath else { DispatchQueue.main.async { completion?(false) } return } for doodle in doodles { let fullFilePath = savePath.appendingPathComponent(doodle.fileName) fileQueue.async { do { try self.fileManager.removeItem(at: fullFilePath) } catch { print("Error deleting file at path: \(fullFilePath)\nError: \(error)") DispatchQueue.main.async { completion?(false) } return } if let stickerSavePath = self.stickerSavePath { let fullStickerSavePath = stickerSavePath.appendingPathComponent(doodle.stickerFileName) do { try self.fileManager.removeItem(at: fullStickerSavePath) } catch let error { print("Error deleting sticker at path: \(fullStickerSavePath)\nError: \(error)") DispatchQueue.main.async { completion?(false) } return } } DispatchQueue.main.async { completion?(true) } } } } }
mit
8d5def1b1ff574c37db08d043aaf8ab6
35.130952
138
0.525206
5.558608
false
false
false
false
cornerstonecollege/402
Jorge_Juri/Mi_Ejemplo/DebuggingAndViews/DebuggingAndViews/ViewController.swift
3
1334
// // ViewController.swift // DebuggingAndViews // // Created by Luiz on 2016-10-12. // Copyright © 2016 Ideia do Luiz. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() createViews() } func createViews() { // let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // let label = UILabel(frame: rect) // label.backgroundColor = UIColor.red // label.text = "I'm a label" // label.center = self.view.center // self.view.addSubview(label) let label = UILabel() label.text = "I'm a label" label.sizeToFit() // the size will fit the text label.center = CGPoint(x: 50, y: 50) label.backgroundColor = UIColor.blue self.view.addSubview(label) let btnRect = CGRect(x: 100, y: 100, width: 100, height: 100) let button = UIButton(frame: btnRect) button.backgroundColor = UIColor.green // right way button.setTitle("I'm a button", for: UIControlState.normal) // wrong way //button.titleLabel?.text = "I'm a button" self.view.addSubview(button) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
a65c4147a099506ebc2d3b1a342a20b1
26.770833
69
0.592648
4.076453
false
false
false
false
natecook1000/swift
test/IRGen/mixed_mode_class_with_unimportable_fields.swift
1
5218
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/UsingObjCStuff.swiftmodule -module-name UsingObjCStuff -I %t -I %S/Inputs/mixed_mode -swift-version 5 %S/Inputs/mixed_mode/UsingObjCStuff.swift // RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 4 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V4 -DWORD=i%target-ptrsize // RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 5 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V5 -DWORD=i%target-ptrsize // REQUIRES: objc_interop import UsingObjCStuff public class SubButtHolder: ButtHolder { final var w: Float = 0 override public func virtual() {} public func subVirtual() {} } public class SubSubButtHolder: SubButtHolder { public override func virtual() {} public override func subVirtual() {} } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$S4main17accessFinalFields2ofyp_ypt14UsingObjCStuff10ButtHolderC_tF" public func accessFinalFields(of holder: ButtHolder) -> (Any, Any) { // ButtHolder.y cannot be imported in Swift 4 mode, so make sure we use field // offset globals here. // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1xSivpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1zSSvpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // ButtHolder.y is correctly imported in Swift 5 mode, so we can use fixed offsets. // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* %2, i32 0, i32 1 // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* %2, i32 0, i32 3 return (holder.x, holder.z) } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$S4main17accessFinalFields5ofSubyp_ypyptAA0F10ButtHolderC_tF" public func accessFinalFields(ofSub holder: SubButtHolder) -> (Any, Any, Any) { // We should use the runtime-adjusted ivar offsets since we may not have // a full picture of the layout in mixed Swift language version modes. // ButtHolder.y cannot be imported in Swift 4 mode, so make sure we use field // offset globals here. // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1xSivpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1zSSvpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S4main13SubButtHolderC1wSfvpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // ButtHolder.y is correctly imported in Swift 5 mode, so we can use fixed offsets. // CHECK-V5: [[SELF:%.*]] = bitcast %T4main13SubButtHolderC* %3 to %T14UsingObjCStuff10ButtHolderC* // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* [[SELF]], i32 0, i32 1 // CHECK-V5: [[SELF:%.*]] = bitcast %T4main13SubButtHolderC* %3 to %T14UsingObjCStuff10ButtHolderC* // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* [[SELF]], i32 0, i32 3 // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T4main13SubButtHolderC, %T4main13SubButtHolderC* %3, i32 0, i32 4 return (holder.x, holder.z, holder.w) } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$S4main12invokeMethod2onyAA13SubButtHolderC_tF" public func invokeMethod(on holder: SubButtHolder) { // CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 10 // CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 13 // CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]] // CHECK: call swiftcc void [[IMPL]] holder.virtual() // CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 15 // CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 18 // CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]] // CHECK: call swiftcc void [[IMPL]] holder.subVirtual() } // CHECK-V4-LABEL: define internal swiftcc %swift.metadata_response @"$S4main13SubButtHolderCMr"(%swift.type*, i8*, i8**) // CHECK-V4: call void @swift_initClassMetadata( // CHECK-V4-LABEL: define internal swiftcc %swift.metadata_response @"$S4main03SubB10ButtHolderCMr"(%swift.type*, i8*, i8**) // CHECK-V4: call void @swift_initClassMetadata(
apache-2.0
36b98d0596da0aeeb3cc8f922b1ceced
51.707071
229
0.678421
3.419397
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/CachedFaqInstantPage.swift
1
6474
// // CachedFaqInstantPage.swift // Telegram // // Created by Mikhail Filimonov on 02.12.2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import Postbox import TelegramCore private func extractAnchor(string: String) -> (String, String?) { var anchorValue: String? if let anchorRange = string.range(of: "#") { let anchor = string[anchorRange.upperBound...] if !anchor.isEmpty { anchorValue = String(anchor) } } var trimmedUrl = string if let anchor = anchorValue, let anchorRange = string.range(of: "#\(anchor)") { let url = string[..<anchorRange.lowerBound] if !url.isEmpty { trimmedUrl = String(url) } } return (trimmedUrl, anchorValue) } private let refreshTimeout: Int32 = 60 * 60 * 12 func cachedFaqInstantPage(context: AccountContext) -> Signal<inAppLink, NoError> { let faqUrl = "https://telegram.org/faq#general-questions" let (cachedUrl, anchor) = extractAnchor(string: faqUrl) return cachedInstantPage(postbox: context.account.postbox, url: cachedUrl) |> mapToSignal { cachedInstantPage -> Signal<inAppLink, NoError> in let updated = resolveInstantViewUrl(account: context.account, url: faqUrl) |> afterNext { result in if case let .instantView(_, webPage, _) = result, case let .Loaded(content) = webPage.content, let instantPage = content.instantPage { if instantPage.isComplete { let _ = updateCachedInstantPage(postbox: context.account.postbox, url: cachedUrl, webPage: webPage).start() } else { let _ = (actualizedWebpage(postbox: context.account.postbox, network: context.account.network, webpage: webPage) |> mapToSignal { webPage -> Signal<Void, NoError> in if case let .Loaded(content) = webPage.content, let instantPage = content.instantPage, instantPage.isComplete { return updateCachedInstantPage(postbox: context.account.postbox, url: cachedUrl, webPage: webPage) } else { return .complete() } }).start() } } } let now = Int32(CFAbsoluteTimeGetCurrent()) if let cachedInstantPage = cachedInstantPage, case let .Loaded(content) = cachedInstantPage.webPage.content, let instantPage = content.instantPage, instantPage.isComplete { let current: Signal<inAppLink, NoError> = .single(.instantView(link: faqUrl, webpage: cachedInstantPage.webPage, anchor: anchor)) if now > cachedInstantPage.timestamp + refreshTimeout { return current |> then(updated) } else { return current } } else { return updated } } } func faqSearchableItems(context: AccountContext) -> Signal<[SettingsSearchableItem], NoError> { return cachedFaqInstantPage(context: context) |> map { resolvedUrl -> [SettingsSearchableItem] in var results: [SettingsSearchableItem] = [] var nextIndex: Int32 = 2 if case let .instantView(_, webPage, _) = resolvedUrl { if case let .Loaded(content) = webPage.content, let instantPage = content.instantPage { var processingQuestions = false var currentSection: String? outer: for block in instantPage.blocks { if !processingQuestions { switch block { case .blockQuote: if results.isEmpty { processingQuestions = true } default: break } } else { switch block { case let .paragraph(text): if case .bold = text { currentSection = text.plainText } else if case .concat = text { processingQuestions = false } case let .list(items, false): if let currentSection = currentSection { for item in items { if case let .text(itemText, _) = item, case let .url(text, url, _) = itemText { let (_, anchor) = extractAnchor(string: url) var index = nextIndex if anchor?.contains("delete-my-account") ?? false { index = 1 } else { nextIndex += 1 } let item = SettingsSearchableItem(id: .faq(index), title: text.plainText, alternate: [], icon: .faq, breadcrumbs: [strings().accountSettingsFAQ, currentSection], present: { context, _, present in showInstantPage(InstantPageViewController(context, webPage: webPage, message: nil, anchor: anchor)) }) if index == 1 { results.insert(item, at: 0) } else { results.append(item) } } } } default: break } } } } } return results } }
gpl-2.0
24a669ffaae2d02f4d1d5a727a3659b1
46.948148
239
0.453885
6.049533
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/Advanced Settings/InsertMediaCustomImageSizeSettingTableViewCell.swift
3
1967
import UIKit class InsertMediaCustomImageSizeSettingTableViewCell: UITableViewCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var textFieldLabel: UILabel! @IBOutlet weak var textField: ThemeableTextField! private var theme = Theme.standard func configure(title: String, textFieldLabelText: String, textFieldText: String, theme: Theme) { titleLabel.text = title textFieldLabel.text = textFieldLabelText textField.text = textFieldText textField.isUnderlined = false textField.rightView = nil updateFonts() apply(theme: theme) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { titleLabel.font = UIFont.wmf_font(.body, compatibleWithTraitCollection: traitCollection) textFieldLabel.font = UIFont.wmf_font(.body, compatibleWithTraitCollection: traitCollection) textField.font = UIFont.wmf_font(.body, compatibleWithTraitCollection: traitCollection) } override var isUserInteractionEnabled: Bool { didSet { textField.isUserInteractionEnabled = isUserInteractionEnabled apply(theme: theme) } } } extension InsertMediaCustomImageSizeSettingTableViewCell: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground let textColor = isUserInteractionEnabled ? theme.colors.primaryText : theme.colors.secondaryText titleLabel.textColor = textColor textFieldLabel.textColor = textColor let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = theme.colors.midBackground self.selectedBackgroundView = selectedBackgroundView textField.apply(theme: theme) textField.textColor = textColor } }
mit
f5231702031707a4dfc5a866296a8665
37.568627
104
0.723437
5.960606
false
false
false
false
wdkk/CAIM
Metal/caimmetal04/CAIMMetal/CAIMMetalGeometrics.swift
15
17377
// // CAIMMetalGeometrics.swift // CAIM Project // https://kengolab.net/CreApp/wiki/ // // Copyright (c) Watanabe-DENKI Inc. // https://wdkk.co.jp/ // // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php // import Foundation import CoreGraphics import Metal import simd // Int2(8バイト) public struct Int2 : CAIMMetalBufferAllocatable { public private(set) var vectorInt2:vector_int2 public var x:Int32 { get { return vectorInt2.x } set { vectorInt2.x = newValue } } public var y:Int32 { get { return vectorInt2.y } set { vectorInt2.y = newValue } } public init( _ x:Int32 = 0, _ y:Int32 = 0 ) { vectorInt2 = [x, y] } public init( _ vec:vector_int2 ) { vectorInt2 = vec } public static var zero:Int2 { return Int2() } } // vector_int2拡張 public extension vector_int2 { var int2:Int2 { return Int2( self ) } } // 演算子オーバーロード public func + ( _ left:Int2, _ right:Int2 ) -> Int2 { return Int2( left.vectorInt2 &+ right.vectorInt2 ) } public func - ( _ left:Int2, _ right:Int2 ) -> Int2 { return Int2( left.vectorInt2 &- right.vectorInt2 ) } public func * ( _ left:Int2, _ right:Int2 ) -> Int2 { return Int2( left.vectorInt2 &* right.vectorInt2 ) } public func / ( _ left:Int2, _ right:Int2 ) -> Int2 { return Int2( left.vectorInt2 / right.vectorInt2 ) } // Int3(16バイト) public struct Int3 : CAIMMetalBufferAllocatable { public private(set) var vectorInt3:vector_int3 public var x:Int32 { get { return vectorInt3.x } set { vectorInt3.x = newValue } } public var y:Int32 { get { return vectorInt3.y } set { vectorInt3.y = newValue } } public var z:Int32 { get { return vectorInt3.z } set { vectorInt3.z = newValue } } public init( _ x:Int32 = 0, _ y:Int32 = 0, _ z:Int32 = 0 ) { vectorInt3 = [x, y, z] } public init( _ vec:vector_int3 ) { vectorInt3 = vec } public static var zero:Int3 { return Int3() } } // vector_int3拡張 public extension vector_int3 { var int3:Int3 { return Int3( self ) } } // 演算子オーバーロード public func + ( _ left:Int3, _ right:Int3 ) -> Int3 { return Int3( left.vectorInt3 &+ right.vectorInt3 ) } public func - ( _ left:Int3, _ right:Int3 ) -> Int3 { return Int3( left.vectorInt3 &- right.vectorInt3 ) } public func * ( _ left:Int3, _ right:Int3 ) -> Int3 { return Int3( left.vectorInt3 &* right.vectorInt3 ) } public func / ( _ left:Int3, _ right:Int3 ) -> Int3 { return Int3( left.vectorInt3 / right.vectorInt3 ) } // Int4(16バイト) public struct Int4 : CAIMMetalBufferAllocatable { public private(set) var vectorInt4:vector_int4 public var x:Int32 { get { return vectorInt4.x } set { vectorInt4.x = newValue } } public var y:Int32 { get { return vectorInt4.y } set { vectorInt4.y = newValue } } public var z:Int32 { get { return vectorInt4.z } set { vectorInt4.z = newValue } } public var w:Int32 { get { return vectorInt4.w } set { vectorInt4.w = newValue } } public init( _ x:Int32 = 0, _ y:Int32 = 0, _ z:Int32 = 0, _ w:Int32 = 0 ) { vectorInt4 = [x, y, z, w] } public init( _ vec:vector_int4 ) { vectorInt4 = vec } public static var zero:Int4 { return Int4() } } // vector_int3拡張 public extension vector_int4 { var int4:Int4 { return Int4( self ) } } // 演算子オーバーロード public func + ( _ left:Int4, _ right:Int4 ) -> Int4 { return Int4( left.vectorInt4 &+ right.vectorInt4 ) } public func - ( _ left:Int4, _ right:Int4 ) -> Int4 { return Int4( left.vectorInt4 &- right.vectorInt4 ) } public func * ( _ left:Int4, _ right:Int4 ) -> Int4 { return Int4( left.vectorInt4 &* right.vectorInt4 ) } public func / ( _ left:Int4, _ right:Int4 ) -> Int4 { return Int4( left.vectorInt4 / right.vectorInt4 ) } // Size2(8バイト) public typealias Size2 = Int2 extension Size2 { public var width:Int32 { get { return self.x } set { self.x = newValue } } public var height:Int32 { get { return self.y } set { self.y = newValue } } } // Size3(16バイト) public typealias Size3 = Int3 extension Size3 { public var width:Int32 { get { return self.x } set { self.x = newValue } } public var height:Int32 { get { return self.y } set { self.y = newValue } } public var depth:Int32 { get { return self.z } set { self.z = newValue } } } // Float2(8バイト) public struct Float2 : CAIMMetalBufferAllocatable { public private(set) var vectorFloat2:vector_float2 public var x:Float { get { return vectorFloat2.x } set { vectorFloat2.x = newValue } } public var y:Float { get { return vectorFloat2.y } set { vectorFloat2.y = newValue } } public init( _ x:Float=0.0, _ y:Float=0.0 ) { vectorFloat2 = [x, y] } public init( _ vec:vector_float2 ) { vectorFloat2 = vec } public static var zero:Float2 { return Float2() } public var normalize:Float2 { return simd_normalize( vectorFloat2 ).float2 } } // vector_float2拡張 public extension vector_float2 { var float2:Float2 { return Float2( self ) } } // 演算子オーバーロード public func + ( _ left:Float2, _ right:Float2 ) -> Float2 { return Float2( left.vectorFloat2 + right.vectorFloat2 ) } public func - ( _ left:Float2, _ right:Float2 ) -> Float2 { return Float2( left.vectorFloat2 - right.vectorFloat2 ) } public func * ( _ left:Float2, _ right:Float2 ) -> Float2 { return Float2( left.vectorFloat2 * right.vectorFloat2 ) } public func / ( _ left:Float2, _ right:Float2 ) -> Float2 { return Float2( left.vectorFloat2 / right.vectorFloat2 ) } public func * ( _ left:Float2, _ right:Float ) -> Float2 { return Float2( left.vectorFloat2 * right ) } public func / ( _ left:Float2, _ right:Float ) -> Float2 { return Float2( left.vectorFloat2 / right ) } // Float3(16バイト) public struct Float3 : CAIMMetalBufferAllocatable { public private(set) var vectorFloat3:vector_float3 public var x:Float { get { return vectorFloat3.x } set { vectorFloat3.x = newValue } } public var y:Float { get { return vectorFloat3.y } set { vectorFloat3.y = newValue } } public var z:Float { get { return vectorFloat3.z } set { vectorFloat3.z = newValue } } public init( _ x:Float=0.0, _ y:Float=0.0, _ z:Float=0.0 ) { vectorFloat3 = [x, y, z] } public init( _ vec:vector_float3 ) { vectorFloat3 = vec } public static var zero:Float3 { return Float3() } public var normalize:Float3 { return simd_normalize( vectorFloat3 ).float3 } } // vector_float3拡張 public extension vector_float3 { var float3:Float3 { return Float3( self ) } } // 演算子オーバーロード public func + ( _ left:Float3, _ right:Float3 ) -> Float3 { return Float3( left.vectorFloat3 + right.vectorFloat3 ) } public func - ( _ left:Float3, _ right:Float3 ) -> Float3 { return Float3( left.vectorFloat3 - right.vectorFloat3 ) } public func * ( _ left:Float3, _ right:Float3 ) -> Float3 { return Float3( left.vectorFloat3 * right.vectorFloat3 ) } public func / ( _ left:Float3, _ right:Float3 ) -> Float3 { return Float3( left.vectorFloat3 / right.vectorFloat3 ) } public func * ( _ left:Float3, _ right:Float ) -> Float3 { return Float3( left.vectorFloat3 * right ) } public func / ( _ left:Float3, _ right:Float ) -> Float3 { return Float3( left.vectorFloat3 / right ) } // Float4(16バイト) public struct Float4 : CAIMMetalBufferAllocatable { public private(set) var vectorFloat4:vector_float4 public var x:Float { get { return vectorFloat4.x } set { vectorFloat4.x = newValue } } public var y:Float { get { return vectorFloat4.y } set { vectorFloat4.y = newValue } } public var z:Float { get { return vectorFloat4.z } set { vectorFloat4.z = newValue } } public var w:Float { get { return vectorFloat4.w } set { vectorFloat4.w = newValue } } public init( _ x:Float=0.0, _ y:Float=0.0, _ z:Float=0.0, _ w:Float=0.0 ) { vectorFloat4 = [x, y, z, w] } public init( _ vec:vector_float4 ) { vectorFloat4 = vec } public static var zero:Float4 { return Float4() } public var normalize:Float4 { return simd_normalize( vectorFloat4 ).float4 } } // vector_float4拡張 public extension vector_float4 { var float4:Float4 { return Float4( self ) } } // 演算子オーバーロード public func + ( _ left:Float4, _ right:Float4 ) -> Float4 { return Float4( left.vectorFloat4 + right.vectorFloat4 ) } public func - ( _ left:Float4, _ right:Float4 ) -> Float4 { return Float4( left.vectorFloat4 - right.vectorFloat4 ) } public func * ( _ left:Float4, _ right:Float4 ) -> Float4 { return Float4( left.vectorFloat4 * right.vectorFloat4 ) } public func / ( _ left:Float4, _ right:Float4 ) -> Float4 { return Float4( left.vectorFloat4 / right.vectorFloat4 ) } public func * ( _ left:Float4, _ right:Float ) -> Float4 { return Float4( left.vectorFloat4 * right ) } public func / ( _ left:Float4, _ right:Float ) -> Float4 { return Float4( left.vectorFloat4 / right ) } // 3x3行列(48バイト) public struct Matrix3x3 : CAIMMetalBufferAllocatable { public private(set) var matrixFloat3x3:matrix_float3x3 public var X:Float3 { get { return matrixFloat3x3.columns.0.float3 } set { matrixFloat3x3.columns.0 = newValue.vectorFloat3 } } public var Y:Float3 { get { return matrixFloat3x3.columns.1.float3 } set { matrixFloat3x3.columns.1 = newValue.vectorFloat3 } } public var Z:Float3 { get { return matrixFloat3x3.columns.2.float3 } set { matrixFloat3x3.columns.2 = newValue.vectorFloat3 } } public init() { matrixFloat3x3 = matrix_float3x3( 0.0 ) } public init( _ columns:[float3] ) { matrixFloat3x3 = matrix_float3x3( columns ) } public init( _ vector:matrix_float3x3 ) { matrixFloat3x3 = vector } // 単位行列 public static var identity:Matrix3x3 { return Matrix3x3([ [ 1.0, 0.0, 0.0 ], [ 0.0, 1.0, 0.0 ], [ 0.0, 0.0, 1.0 ] ]) } } // matrix_float3x3拡張 public extension matrix_float3x3 { var matrix3x3:Matrix3x3 { return Matrix3x3( self ) } } // 演算子オーバーロード public func + ( _ left:Matrix3x3, _ right:Matrix3x3 ) -> Matrix3x3 { return Matrix3x3( left.matrixFloat3x3 + right.matrixFloat3x3 ) } public func - ( _ left:Matrix3x3, _ right:Matrix3x3 ) -> Matrix3x3 { return Matrix3x3( left.matrixFloat3x3 - right.matrixFloat3x3 ) } public func * ( _ left:Matrix3x3, _ right:Matrix3x3 ) -> Matrix3x3 { return Matrix3x3( left.matrixFloat3x3 * right.matrixFloat3x3 ) } public func * ( _ left:Matrix3x3, _ right:Float3 ) -> Float3 { return Float3( left.matrixFloat3x3 * right.vectorFloat3 ) } public func * ( _ left:Matrix3x3, _ right:matrix_float3x3 ) -> Matrix3x3 { return Matrix3x3( left.matrixFloat3x3 * right ) } public func * ( _ left:matrix_float3x3, _ right:Matrix3x3 ) -> Matrix3x3 { return Matrix3x3( left * right.matrixFloat3x3 ) } // 4x4行列(64バイト) public struct Matrix4x4 : CAIMMetalBufferAllocatable { public private(set) var matrixFloat4x4:matrix_float4x4 public var X:Float4 { get { return matrixFloat4x4.columns.0.float4 } set { matrixFloat4x4.columns.0 = newValue.vectorFloat4 } } public var Y:Float4 { get { return matrixFloat4x4.columns.1.float4 } set { matrixFloat4x4.columns.1 = newValue.vectorFloat4 } } public var Z:Float4 { get { return matrixFloat4x4.columns.2.float4 } set { matrixFloat4x4.columns.2 = newValue.vectorFloat4 } } public var W:Float4 { get { return matrixFloat4x4.columns.3.float4 } set { matrixFloat4x4.columns.3 = newValue.vectorFloat4 } } public init() { matrixFloat4x4 = matrix_float4x4( 0.0 ) } public init( _ columns:[float4] ) { matrixFloat4x4 = matrix_float4x4( columns ) } public init( _ vector:matrix_float4x4 ) { matrixFloat4x4 = vector } // 単位行列 public static var identity:Matrix4x4 { return Matrix4x4( [ [ 1.0, 0.0, 0.0, 0.0 ], [ 0.0, 1.0, 0.0, 0.0 ], [ 0.0, 0.0, 1.0, 0.0 ], [ 0.0, 0.0, 0.0, 1.0 ] ]) } // 平行移動 public static func translate(_ x:Float, _ y:Float, _ z:Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity mat.W.x = x mat.W.y = y mat.W.z = z return mat } // 拡大縮小 public static func scale(_ x:Float, _ y:Float, _ z:Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity mat.X.x = x mat.Y.y = y mat.Z.z = z return mat } // 回転(三軸同時) public static func rotate(axis: Float4, byAngle angle: Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity let c:Float = cos(angle) let s:Float = sin(angle) mat.X.x = axis.x * axis.x + (1 - axis.x * axis.x) * c mat.Y.x = axis.x * axis.y * (1 - c) - axis.z * s mat.Z.x = axis.x * axis.z * (1 - c) + axis.y * s mat.X.y = axis.x * axis.y * (1 - c) + axis.z * s mat.Y.y = axis.y * axis.y + (1 - axis.y * axis.y) * c mat.Z.y = axis.y * axis.z * (1 - c) - axis.x * s mat.X.z = axis.x * axis.z * (1 - c) - axis.y * s mat.Y.z = axis.y * axis.z * (1 - c) + axis.x * s mat.Z.z = axis.z * axis.z + (1 - axis.z * axis.z) * c return mat } public static func rotateX(byAngle angle: Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity let cosv:Float = cos(angle) let sinv:Float = sin(angle) mat.Y.y = cosv mat.Z.y = -sinv mat.Y.z = sinv mat.Z.z = cosv return mat } public static func rotateY(byAngle angle: Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity let cosv:Float = cos(angle) let sinv:Float = sin(angle) mat.X.x = cosv mat.Z.x = sinv mat.X.z = -sinv mat.Z.z = cosv return mat } public static func rotateZ(byAngle angle: Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity let cosv:Float = cos(angle) let sinv:Float = sin(angle) mat.X.x = cosv mat.Y.x = -sinv mat.X.y = sinv mat.Y.y = cosv return mat } // ピクセル座標系変換行列 public static func pixelProjection(wid:Int, hgt:Int) -> Matrix4x4 { var vp_mat:Matrix4x4 = .identity vp_mat.X.x = 2.0 / Float(wid) vp_mat.Y.y = -2.0 / Float(hgt) vp_mat.W.x = -1.0 vp_mat.W.y = 1.0 return vp_mat } public static func pixelProjection(wid:CGFloat, hgt:CGFloat) -> Matrix4x4 { return pixelProjection(wid: Int(wid), hgt: Int(hgt)) } public static func pixelProjection(wid:Float, hgt:Float) -> Matrix4x4 { return pixelProjection(wid: Int(wid), hgt: Int(hgt)) } public static func pixelProjection(_ size:CGSize) -> Matrix4x4 { return pixelProjection(wid: Int(size.width), hgt: Int(size.height)) } public static func ortho(left l: Float, right r: Float, bottom b: Float, top t: Float, near n: Float, far f: Float) -> Matrix4x4 { var mat:Matrix4x4 = .identity mat.X.x = 2.0 / (r-l) mat.W.x = (r+l) / (r-l) mat.Y.y = 2.0 / (t-b) mat.W.y = (t+b) / (t-b) mat.Z.z = -2.0 / (f-n) mat.W.z = (f+n) / (f-n) return mat } public static func ortho2d(wid:Float, hgt:Float) -> Matrix4x4 { return ortho(left: 0, right: wid, bottom: hgt, top: 0, near: -1, far: 1) } // 透視投影変換行列(手前:Z軸正方向) public static func perspective(aspect: Float, fieldOfViewY: Float, near: Float, far: Float) -> Matrix4x4 { var mat:Matrix4x4 = Matrix4x4() let fov_radians:Float = fieldOfViewY * Float(Double.pi / 180.0) let y_scale:Float = 1 / tan(fov_radians * 0.5) let x_scale:Float = y_scale / aspect let z_range:Float = far - near let z_scale:Float = -(far + near) / z_range let wz_scale:Float = -2 * far * near / z_range mat.X.x = x_scale mat.Y.y = y_scale mat.Z.z = z_scale mat.Z.w = -1.0 mat.W.z = wz_scale mat.W.w = 0.0 return mat } } // matrix_float4x4拡張 public extension matrix_float4x4 { var matrix4x4:Matrix4x4 { return Matrix4x4( self ) } } // 演算子オーバーロード public func + ( _ left:Matrix4x4, _ right:Matrix4x4 ) -> Matrix4x4 { return Matrix4x4( left.matrixFloat4x4 + right.matrixFloat4x4 ) } public func - ( _ left:Matrix4x4, _ right:Matrix4x4 ) -> Matrix4x4 { return Matrix4x4( left.matrixFloat4x4 - right.matrixFloat4x4 ) } public func * ( _ left:Matrix4x4, _ right:Matrix4x4 ) -> Matrix4x4 { return Matrix4x4( left.matrixFloat4x4 * right.matrixFloat4x4 ) } public func * ( _ left:Matrix4x4, _ right:Float4 ) -> Float4 { return Float4( left.matrixFloat4x4 * right.vectorFloat4 ) } public func * ( _ left:Matrix4x4, _ right:matrix_float4x4 ) -> Matrix4x4 { return Matrix4x4( left.matrixFloat4x4 * right ) } public func * ( _ left:matrix_float4x4, _ right:Matrix4x4 ) -> Matrix4x4 { return Matrix4x4( left * right.matrixFloat4x4 ) }
mit
abe70ff984321cdc05913b5d88fa4d34
35.530043
134
0.620572
2.930453
false
false
false
false
sr189/bitcoin_tracker
BitcoinTrackerWidget/TodayViewController.swift
1
1979
// // TodayViewController.swift // BitcoinTrackerWidget // // Created by Stefan Rohde on 21.02.15. // Copyright (c) 2015 Stefan Rohde. All rights reserved. // import UIKit import NotificationCenter import BitcoinTrackerDataKit class TodayViewController: UIViewController, BitcoinWalletDelegate, NCWidgetProviding { @IBOutlet weak var currentBitcoinRateLabel: UILabel! @IBOutlet weak var profitLabel: UILabel! var wallet: BitcoinWallet! override func viewDidLoad() { super.viewDidLoad() wallet = BitcoinWallet() wallet.refresh(self) var currentSize: CGSize = self.preferredContentSize currentSize.height = 60.0 self.preferredContentSize = currentSize // Do any additional setup after loading the view from its nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.NewData) } private func updateUI() { let profitValue = wallet.profit() currentBitcoinRateLabel.text = "\(formatNumber(wallet.currentBitcoinRate))€ / BTC" profitLabel.text = "\(formatNumber(profitValue))€ (\(formatNumber(wallet.profitInPercent()))%)" profitLabel.textColor = profitValue>=0.0 ? UIColor.greenColor() : UIColor.redColor() } func walletUpdated() { updateUI() } private func formatNumber(number: Double?) -> NSString { return(NSString(format:"%.2f", number!)) } }
mit
6890fb0198161bbaae0d4694566e4cd2
30.854839
103
0.666835
5.038265
false
false
false
false
russbishop/swift
test/SILGen/generic_closures.swift
1
13496
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s import Swift var zero: Int // CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}} func generic_nondependent_context<T>(_ x: T, y: Int) -> Int { func foo() -> Int { return y } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [[FOO]](%1) // CHECK: strong_release [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo() } // CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}} func generic_capture<T>(_ x: T) -> Any.Type { func foo() -> Any.Type { return T.self } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [[FOO]]<T>() // CHECK: strong_release [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>() return foo() } // CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}} func generic_capture_cast<T>(_ x: T, y: Any) -> Bool { func foo(_ a: Any) -> Bool { return a is T } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [[FOO]]<T>() // CHECK: strong_release [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>([[ARG:%.*]]) return foo(y) } protocol Concept { var sensical: Bool { get } } // CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}} func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool { func foo(_ a: Concept) -> Bool { return a.sensical } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = thin_to_thick_function [[FOO]] // CHECK: strong_release [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]([[ARG:%.*]]) return foo(y) } // CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}} func generic_dependent_context<T>(_ x: T, y: Int) -> T { func foo() -> T { return x } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [[FOO]]<T>([[BOX:%.*]]) // CHECK: strong_release [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T> return foo() } enum Optionable<Wrapped> { case none case some(Wrapped) } class NestedGeneric<U> { class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int { func foo() -> Int { return y } let _ = foo return foo() } class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T { func foo() -> T { return x } let _ = foo return foo() } class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U { func foo() -> U { return z } let _ = foo return foo() } class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) { func foo() -> (T, U) { return (x, z) } let _ = foo return foo() } // CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}} // CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo___XFo_iT__iT__ // CHECK: partial_apply [[REABSTRACT]]<U, T> func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> { return .some({}) } } // <rdar://problem/15417773> // Ensure that nested closures capture the generic parameters of their nested // context. // CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@in T) -> @out T // CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]] // CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T // CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]] // CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T { func nested_closure_in_generic<T>(_ x:T) -> T { return { { x }() }() } // CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties func local_properties<T>(_ t: inout T) { // CHECK: [[TBOX:%[0-9]+]] = alloc_box $T var prop: T { get { return t } set { t = newValue } } // CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER_REF]] t = prop // CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0) -> () // CHECK: apply [[SETTER_REF]] prop = t var prop2: T { get { return t } set { // doesn't capture anything } } // CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER2_REF]] t = prop2 // CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () // CHECK: apply [[SETTER2_REF]] prop2 = t } protocol Fooable { static func foo() -> Bool } // <rdar://problem/16399018> func shmassert(_ f: @autoclosure () -> Bool) {} // CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param func capture_generic_param<A: Fooable>(_ x: A) { shmassert(A.foo()) } // Make sure we use the correct convention when capturing class-constrained // member types: <rdar://problem/24470533> class Class {} protocol HasClassAssoc { associatedtype Assoc : Class } // CHECK-LABEL: sil hidden @_TF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_ // CHECK: bb0(%0 : $*T, %1 : $@callee_owned (@owned T.Assoc) -> @owned T.Assoc): // CHECK: [[GENERIC_FN:%.*]] = function_ref @_TFF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_U_FT_FQQ_5AssocS2_ // CHECK: [[CONCRETE_FN:%.*]] = partial_apply [[GENERIC_FN]]<T, T.Assoc>(%1) func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: (T.Assoc) -> T.Assoc) { let _: () -> (T.Assoc) -> T.Assoc = { f } } // Make sure local generic functions can have captures // CHECK-LABEL: sil hidden @_TF16generic_closures13outer_genericurFT1tx1iSi_T_ : $@convention(thin) <T> (@in T, Int) -> () func outer_generic<T>(t: T, i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic1<U>(u: U) -> Int { return i } func inner_generic2<U>(u: U) -> T { return t } let _: () -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_23inner_generic_nocaptureu__rFT1uqd___qd__ : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRGrXFo_iT__iT__XFo___ // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]<T>([[CLOSURE]]) // CHECK: strong_release [[THUNK_CLOSURE]] // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_23inner_generic_nocaptureu__rFT1uqd___qd__ : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0 _ = inner_generic_nocapture(u: t) // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_14inner_generic1u__rfT1uqd___Si : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @_TTRGrXFo_iT__dSi_XFo__dSi_ // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]<T>([[CLOSURE]]) // CHECK: strong_release [[THUNK_CLOSURE]] let _: () -> Int = inner_generic1 // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_14inner_generic1u__rfT1uqd___Si : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int _ = inner_generic1(u: t) // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_14inner_generic2u__rfT1uqd___x : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @owned @box τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @owned @box τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRGrXFo_iT__ix_XFo__ix_ // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]<T>([[CLOSURE]]) // CHECK: strong_release [[THUNK_CLOSURE]] let _: () -> T = inner_generic2 // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_14inner_generic2u__rfT1uqd___x : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @owned @box τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @owned @box τ_0_0) -> @out τ_0_0 _ = inner_generic2(u: t) } // CHECK-LABEL: sil hidden @_TF16generic_closures14outer_concreteFT1iSi_T_ : $@convention(thin) (Int) -> () func outer_concrete(i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic<U>(u: U) -> Int { return i } // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures14outer_concreteFT1iSi_T_L_23inner_generic_nocaptureurFT1ux_x : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_iT__iT__XFo___ // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]([[CLOSURE]]) // CHECK: strong_release [[THUNK_CLOSURE]] let _: () -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures14outer_concreteFT1iSi_T_L_23inner_generic_nocaptureurFT1ux_x : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0 _ = inner_generic_nocapture(u: i) // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures14outer_concreteFT1iSi_T_L_13inner_genericurfT1ux_Si : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_iT__dSi_XFo__dSi_ // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]([[CLOSURE]]) // CHECK: strong_release [[THUNK_CLOSURE]] let _: () -> Int = inner_generic // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures14outer_concreteFT1iSi_T_L_13inner_genericurfT1ux_Si : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int _ = inner_generic(u: i) } // CHECK-LABEL: sil hidden @_TF16generic_closures32mixed_generic_nongeneric_nestingurFT1tx_T_ : $@convention(thin) <T> (@in T) -> () func mixed_generic_nongeneric_nesting<T>(t: T) { func outer() { func middle<U>(u: U) { func inner() -> U { return u } inner() } middle(u: 11) } outer() } // CHECK-LABEL: sil shared @_TFF16generic_closures32mixed_generic_nongeneric_nestingurFT1tx_T_L_5outerurFT_T_ : $@convention(thin) <T> () -> () // CHECK-LABEL: sil shared @_TFFF16generic_closures32mixed_generic_nongeneric_nestingurFT1tx_T_L_5outerurFT_T_L_6middleu__rFT1uqd___T_ : $@convention(thin) <T><U> (@in U) -> () // CHECK-LABEL: sil shared @_TFFFF16generic_closures32mixed_generic_nongeneric_nestingurFT1tx_T_L_5outerurFT_T_L_6middleu__rFT1uqd___T_L_5inneru__rfT_qd__ : $@convention(thin) <T><U> (@owned @box U) -> @out U
apache-2.0
4bb824d8d74938a6c7b987aa26d592aa
44.293919
208
0.607966
2.926015
false
false
false
false
zaneswafford/ProjectEulerSwift
ProjectEuler/Problem12.swift
1
644
// // Problem12.swift // ProjectEuler // // Created by Zane Swafford on 6/28/15. // Copyright (c) 2015 Zane Swafford. All rights reserved. // import Foundation func problem12() -> Int { for var i = 2, triangleNumber = 1, divisors = 0; true; triangleNumber += i, i++ { var divisors = 2 let limit = Int(ceil(sqrt(Double(triangleNumber)))) for var naturalNumber = 2; naturalNumber <= limit; naturalNumber++ { if triangleNumber % naturalNumber == 0 { divisors += 2 } } if divisors > 500 { return triangleNumber } } }
bsd-2-clause
f53446ef846b25181b5379d50676e671
23.807692
85
0.551242
3.95092
false
false
false
false
DeveloperJx/ActivityIndicatorButton
UIButtonExtension.swift
1
1737
// // UIButtonExtension.swift // YunYou // // Created by Jx on 16/5/21. // Copyright © 2016年 gxcb. All rights reserved. // import UIKit extension UIButton { ///显示加载指示器 func showActivityIndicatorStartAnimating(_ style: UIActivityIndicatorViewStyle?) { DispatchQueue(label: "com.dispatch.serial").async { let activityIndicator = UIActivityIndicatorView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 20.0, height: 20.0))) if style != nil { activityIndicator.activityIndicatorViewStyle = style! } DispatchQueue.main.sync { self.titleLabel?.transform = CGAffineTransform(scaleX: 100000, y: 100000) self.imageView?.transform = CGAffineTransform(scaleX: 100000, y: 100000) self.addSubview(activityIndicator) activityIndicator.center = CGPoint(x: self.frame.width / 2.0, y: self.frame.height / 2.0) activityIndicator.startAnimating() self.isEnabled = false } } } ///关闭加载指示器 func showActivityIndicatorStopAnimating() { DispatchQueue(label: "com.dispatch.serial").async { for subView in self.subviews { if subView.isKind(of: UIActivityIndicatorView.classForCoder()) { DispatchQueue.main.sync { subView.removeFromSuperview() self.titleLabel?.transform = CGAffineTransform.identity self.imageView?.transform = CGAffineTransform.identity self.isEnabled = true } } } } } }
gpl-3.0
30da4d46f0e060e9c7b7892538db3712
35.297872
137
0.579132
5.265432
false
false
false
false
qinting513/WeiBo-Swift
WeiBo_V1/WeiBo/Classes/View[视图跟控制器]/Main/WBBaseViewController.swift
1
5317
// // WBBaseViewController.swift // WeiBo // // Created by Qinting on 16/9/6. // Copyright © 2016年 Qinting. All rights reserved. // import UIKit //面试题 OC中支持多继承吗 如果不支持,如何替代 答案: 使用协议替代 //class WBBaseViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{ //swift 中,利用‘extension’可以把函数按照功能分类管理,便于阅读跟维护 //注意: //1. extension中不能有属性 //2.extension中不能重写父类方法,重写父类方法,是子类的职责,扩展是对类的扩展,使类的功能更强大 //主控制机器基类 class WBBaseViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate { // 如果用户没有登录 则不创建 var tableView : UITableView? // 添加刷新控件 var refreshControl : UIRefreshControl? // 上拉刷新标记 var isPullup = false // 用户登录标记 var userLogon = false // 设置访客视图信息的字典 var visitorInfoDictionary : [String:String]? // MARK:- 隐藏系统的后,自定义导航栏 lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main().bounds.size.width, height: 64)) // MARK: - 自定义的导航项 lazy var naviItem = UINavigationItem() override func viewDidLoad() { super.viewDidLoad() setupUI() // 如果我想每次都加载,那就放在viewWillAppear方法里 loadData() } //MARK: - 重写title 的 setter方法 override var title: String? { didSet{ naviItem.title = title } } // 加载数据 具体的实现由子类负责 func loadData() { // 如果不实现任何方法,则默认关闭 refreshControl?.endRefreshing() } } //设置界面 extension WBBaseViewController { func setupUI() { view.backgroundColor = UIColor.randomColor() setupNavi() userLogon ? setupTableView() : setupVisitView() } // MARK: - 设置tableView private func setupTableView(){ tableView = UITableView(frame: view.bounds, style: .plain) view.insertSubview(tableView!, belowSubview: navigationBar) tableView?.dataSource = self tableView?.delegate = self // 取消自动缩进 如果隐藏了导航栏会缩进 20 个点 automaticallyAdjustsScrollViewInsets = false // 设置内容缩进 tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49 , right: 0) // 设置刷新控件 refreshControl = UIRefreshControl() tableView?.addSubview(refreshControl!) // 添加监听方法 refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) } // MARK: - 设置访客视图 private func setupVisitView(){ let visitorView = WBVisitorView(frame: view.bounds) visitorView.backgroundColor = UIColor.white() view.insertSubview(visitorView, belowSubview: navigationBar) visitorView.visitorInfo = visitorInfoDictionary } // MARK: - 设置导航条 private func setupNavi(){ // 添加一个导航栏 view.addSubview(navigationBar) // 设置导航项 navigationBar.items = [naviItem] // 设置naviBar的 背景 渲染颜色 navigationBar.barTintColor = UIColor(white: 0xF6F6F6, alpha: 1.0) // 设置naviBar的 barButton 文字渲染颜色 navigationBar.tintColor = UIColor.orange() // 设置naviBar的 标题字体颜色 navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray()] } } extension WBBaseViewController { @objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } // 基类只是准备方法,子类负责具体实现,子类的数据源方法不需要super @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 只是保证没有语法错误 return UITableViewCell() } /// 在显示最后一行的时候做上拉刷新 @objc(tableView:willDisplayCell:forRowAtIndexPath:) func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // 判断是最后分区 最后一行 let row = indexPath.row let section = tableView.numberOfSections - 1 if row < 0 || section < 0 { return } let count = tableView.numberOfRows(inSection: section) // 判断最后一行,同时没有上拉刷新 if row == (count - 1) && !isPullup { // print("上拉刷新") self.isPullup = true self.loadData() } } }
apache-2.0
99bdfa222ecdb9604024b5716254a442
29.281879
164
0.619681
4.330134
false
false
false
false
iovation/launchkey-ios-whitelabel-sdk
SampleAppSwift/SampleAppSwift/DevicesDefaultViewController.swift
2
1205
// // DevicesDefaultViewController.swift // WhiteLabelDemoAppSwift // // Created by ani on 8/7/16. // Copyright © 2016 LaunchKey. All rights reserved. // import Foundation class DevicesDefaultViewController:UIViewController { @IBOutlet weak var containerView: UIView! var devicesChildView:DevicesViewController! override func viewDidLoad() { super.viewDidLoad() self.title = "Devices (Default UI)" //Navigation Bar Buttons self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "NavBack"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(ContainerViewController.back)) self.navigationItem.leftBarButtonItem?.tintColor = UIColor.white devicesChildView = DevicesViewController.init(parentView: self) self.addChild(devicesChildView) containerView.addSubview(devicesChildView.view) devicesChildView.didMove(toParent: self) } @IBAction func back() { if let navController = self.navigationController { navController.popViewController(animated: true) } } }
mit
1363fee9d55535a6ad98bf2dcd21aa25
27.666667
196
0.670266
5.167382
false
false
false
false
benlangmuir/swift
test/ClangImporter/enum-objc.swift
22
1775
// RUN: %target-swift-frontend -emit-sil %s -enable-objc-interop -import-objc-header %S/Inputs/enum-objc.h -verify -enable-nonfrozen-enum-exhaustivity-diagnostics // REQUIRES: objc_interop func test(_ value: SwiftEnum, _ exhaustiveValue: ExhaustiveEnum) { switch value { // expected-warning {{switch covers known cases, but 'SwiftEnum' may have additional unknown values}} expected-note {{handle unknown values using "@unknown default"}} case .one: break case .two: break case .three: break } switch exhaustiveValue { // ok case .one: break case .two: break case .three: break } } let _: Int = forwardBarePointer // expected-error {{cannot convert value of type '(OpaquePointer) -> Void' to specified type 'Int'}} let _: Int = forwardWithUnderlyingPointer // expected-error {{cannot convert value of type '(OpaquePointer) -> Void' to specified type 'Int'}} let _: Int = forwardObjCPointer // expected-error {{cannot convert value of type '(OpaquePointer) -> Void' to specified type 'Int'}} // FIXME: It would be nice to import these as unavailable somehow instead. let _: Int = forwardWithUnderlyingValue // expected-error {{cannot find 'forwardWithUnderlyingValue' in scope}} let _: Int = forwardObjCValue // expected-error {{cannot find 'forwardObjCValue' in scope}} // Note that if /these/ start getting imported as unavailable, the error will // also mention that there's a missing argument, since the second argument isn't // actually defaultable. _ = SomeClass.tryInferDefaultArgumentUnderlyingValue(false) // expected-error {{type 'SomeClass' has no member 'tryInferDefaultArgumentUnderlyingValue'}} _ = SomeClass.tryInferDefaultArgumentObjCValue(false) // expected-error {{type 'SomeClass' has no member 'tryInferDefaultArgumentObjCValue'}}
apache-2.0
948e6d7ad259a1764d58d3009750fe4c
56.258065
183
0.750423
4.186321
false
false
false
false
keleyundou/dojo-table-performance
dojo-table-performance/XMCFeedTableViewCell.swift
3
3476
// // XMCFeedTableViewCell.swift // dojo-table-performance // // Created by David McGraw on 1/4/15. // Copyright (c) 2015 David McGraw. All rights reserved. // import UIKit class XMCFeedTableViewCell: UITableViewCell { @IBOutlet weak var dogPhoto: UIImageView! @IBOutlet weak var dogName: UILabel! @IBOutlet weak var title: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var likeAction: UIButton! func updateWithRandomData() { // ***** // Photo // Try out various methods for loading a photo, from worst to best loadPhoto() // loadPhotoAsync() // loadPhotoWithCache() // **** // Date // Constantly initializing formatters may not show a negative impact // right away visually, but it will add up eventually. Also, look at // the memory. loadDate() // loadDataStaticFormatter() // **************** // Dog name & Title // Make sure you really need attributed strings or not. loadAttributedText() // loadPlainText() } // MARK: Photo Handling func loadPhoto() { let r = (arc4random() % UInt32(20)) if let data = NSData(contentsOfURL: NSURL(string: "http://www.xmcgraw.com/pets/jpg/siberian\(r).jpg")!) { dogPhoto.image = UIImage(data: data) } } func loadPhotoAsync() { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { let r = (arc4random() % UInt32(20)) if let data = NSData(contentsOfURL: NSURL(string: "http://www.xmcgraw.com/pets/jpg/siberian\(r).jpg")!) { dispatch_async(dispatch_get_main_queue()) { self.dogPhoto.image = UIImage(data: data) } } } } func loadPhotoWithCache() { let r = (arc4random() % UInt32(20)) if let url = NSURL(string: "http://www.xmcgraw.com/pets/jpg/siberian\(r).jpg") { dogPhoto.hnk_setImageFromURL(url) } } // MARK: Date Handling func loadDate() { // Warning: these are not threadsafe so you need to create a static formatter // on each thread let formatter = NSDateFormatter() formatter.dateFormat = "MM-dd-yy" date.text = formatter.stringFromDate(NSDate()) } func loadDataStaticFormatter() { // Warning: these are not threadsafe so you will need to create a static formatter // on each thread date.text = XMCFeedTableViewController.XMCDateFormatter.stringFromDate(NSDate()) } // MARK: Text Handling func loadAttributedText() { var attributed = NSMutableAttributedString(string: "Calix") attributed.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(16.0), range: NSMakeRange(0, attributed.length)) dogName.attributedText = attributed attributed = NSMutableAttributedString(string: "Silly Dog") attributed.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(22.0), range: NSMakeRange(0, attributed.length)) title.attributedText = attributed } func loadPlainText() { dogName.text = "Calix" title.text = "Silly Dog" } }
mit
0d14d464670ea21b1412550f3272f4e8
29.491228
132
0.585731
4.543791
false
false
false
false
mshhmzh/firefox-ios
Sync/Synchronizers/Bookmarks/Merging.swift
4
10749
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger // Because generic protocols in Swift are a pain in the ass. public protocol BookmarkStorer: class { // TODO: this should probably return a timestamp. func applyUpstreamCompletionOp(op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>> } public class UpstreamCompletionOp: PerhapsNoOp { // Upload these records from the buffer, but with these child lists. public var amendChildrenFromBuffer: [GUID: [GUID]] = [:] // Upload these records from the mirror, but with these child lists. public var amendChildrenFromMirror: [GUID: [GUID]] = [:] // Upload these records from local, but with these child lists. public var amendChildrenFromLocal: [GUID: [GUID]] = [:] // Upload these records as-is. public var records: [Record<BookmarkBasePayload>] = [] public let ifUnmodifiedSince: Timestamp? public var isNoOp: Bool { return records.isEmpty } public init(ifUnmodifiedSince: Timestamp?=nil) { self.ifUnmodifiedSince = ifUnmodifiedSince } } public class BookmarksMergeResult: PerhapsNoOp { let uploadCompletion: UpstreamCompletionOp let overrideCompletion: LocalOverrideCompletionOp let bufferCompletion: BufferCompletionOp let itemSources: ItemSources public var isNoOp: Bool { return self.uploadCompletion.isNoOp && self.overrideCompletion.isNoOp && self.bufferCompletion.isNoOp } func applyToClient(client: BookmarkStorer, storage: SyncableBookmarks, buffer: BookmarkBufferStorage) -> Success { return client.applyUpstreamCompletionOp(self.uploadCompletion, itemSources: self.itemSources, trackingTimesInto: self.overrideCompletion) >>> { storage.applyLocalOverrideCompletionOp(self.overrideCompletion, itemSources: self.itemSources) } >>> { buffer.applyBufferCompletionOp(self.bufferCompletion, itemSources: self.itemSources) } } init(uploadCompletion: UpstreamCompletionOp, overrideCompletion: LocalOverrideCompletionOp, bufferCompletion: BufferCompletionOp, itemSources: ItemSources) { self.uploadCompletion = uploadCompletion self.overrideCompletion = overrideCompletion self.bufferCompletion = bufferCompletion self.itemSources = itemSources } static func NoOp(itemSources: ItemSources) -> BookmarksMergeResult { return BookmarksMergeResult(uploadCompletion: UpstreamCompletionOp(), overrideCompletion: LocalOverrideCompletionOp(), bufferCompletion: BufferCompletionOp(), itemSources: itemSources) } } // MARK: - Errors. public class BookmarksMergeError: MaybeErrorType { private let error: ErrorType? init(error: ErrorType?=nil) { self.error = error } public var description: String { return "Merge error: \(self.error)" } } public class BookmarksMergeConsistencyError: BookmarksMergeError { override public var description: String { return "Merge consistency error" } } public class BookmarksMergeErrorTreeIsUnrooted: BookmarksMergeConsistencyError { public let roots: Set<GUID> public init(roots: Set<GUID>) { self.roots = roots } override public var description: String { return "Tree is unrooted: roots are \(self.roots)" } } enum MergeState<T> { case Unknown // Default state. case Unchanged // Nothing changed: no work needed. case Remote // Take the associated remote value. case Local // Take the associated local value. case New(value: T) // Take this synthesized value. var isUnchanged: Bool { if case .Unchanged = self { return true } return false } var isUnknown: Bool { if case .Unknown = self { return true } return false } var label: String { switch self { case .Unknown: return "Unknown" case .Unchanged: return "Unchanged" case .Remote: return "Remote" case .Local: return "Local" case .New: return "New" } } } func ==<T: Equatable>(lhs: MergeState<T>, rhs: MergeState<T>) -> Bool { switch (lhs, rhs) { case (.Unknown, .Unknown): return true case (.Unchanged, .Unchanged): return true case (.Remote, .Remote): return true case (.Local, .Local): return true case let (.New(lh), .New(rh)): return lh == rh default: return false } } /** * Using this: * * You get one for the root. Then you give it children for the roots * from the mirror. * * Then you walk those, populating the remote and local nodes by looking * at the left/right trees. * * By comparing left and right, and doing value-based comparisons if necessary, * a merge state is decided and assigned for both value and structure. * * One then walks both left and right child structures (both to ensure that * all nodes on both left and right will be visited!) recursively. */ class MergedTreeNode { let guid: GUID let mirror: BookmarkTreeNode? var remote: BookmarkTreeNode? var local: BookmarkTreeNode? var hasLocal: Bool { return self.local != nil } var hasMirror: Bool { return self.mirror != nil } var hasRemote: Bool { return self.remote != nil } var valueState: MergeState<BookmarkMirrorItem> = MergeState.Unknown var structureState: MergeState<BookmarkTreeNode> = MergeState.Unknown var hasDecidedChildren: Bool { return !self.structureState.isUnknown } var mergedChildren: [MergedTreeNode]? = nil // One-sided constructors. static func forRemote(remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: remote.recordGUID, mirror: mirror, structureState: MergeState.Remote) n.remote = remote n.valueState = MergeState.Remote return n } static func forLocal(local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: local.recordGUID, mirror: mirror, structureState: MergeState.Local) n.local = local n.valueState = MergeState.Local return n } static func forUnchanged(mirror: BookmarkTreeNode) -> MergedTreeNode { let n = MergedTreeNode(guid: mirror.recordGUID, mirror: mirror, structureState: MergeState.Unchanged) n.valueState = MergeState.Unchanged return n } init(guid: GUID, mirror: BookmarkTreeNode?, structureState: MergeState<BookmarkTreeNode>) { self.guid = guid self.mirror = mirror self.structureState = structureState } init(guid: GUID, mirror: BookmarkTreeNode?) { self.guid = guid self.mirror = mirror } // N.B., you cannot recurse down `decidedStructure`: you'll depart from the // merged tree. You need to use `mergedChildren` instead. private var decidedStructure: BookmarkTreeNode? { switch self.structureState { case .Unknown: return nil case .Unchanged: return self.mirror case .Remote: return self.remote case .Local: return self.local case let .New(node): return node } } func asUnmergedTreeNode() -> BookmarkTreeNode { return self.decidedStructure ?? BookmarkTreeNode.Unknown(guid: self.guid) } // Recursive. Starts returning Unknown when nodes haven't been processed. func asMergedTreeNode() -> BookmarkTreeNode { guard let decided = self.decidedStructure, let merged = self.mergedChildren else { return BookmarkTreeNode.Unknown(guid: self.guid) } if case .Folder = decided { let children = merged.map { $0.asMergedTreeNode() } return BookmarkTreeNode.Folder(guid: self.guid, children: children) } return decided } var isFolder: Bool { return self.mergedChildren != nil } func dump(indent: Int) { precondition(indent < 200) let r: Character = "R" let l: Character = "L" let m: Character = "M" let ind = indenting(indent) print(ind, "[V: ", box(self.remote, r), box(self.mirror, m), box(self.local, l), self.guid, self.valueState.label, "]") guard self.isFolder else { return } print(ind, "[S: ", self.structureState.label, "]") if let children = self.mergedChildren { print(ind, " ..") for child in children { child.dump(indent + 2) } } } } private func box<T>(x: T?, _ c: Character) -> Character { if x == nil { return "□" } return c } private func indenting(by: Int) -> String { return String(count: by, repeatedValue: " " as Character) } class MergedTree { var root: MergedTreeNode var deleteLocally: Set<GUID> = Set() var deleteRemotely: Set<GUID> = Set() var deleteFromMirror: Set<GUID> = Set() var acceptLocalDeletion: Set<GUID> = Set() var acceptRemoteDeletion: Set<GUID> = Set() var allGUIDs: Set<GUID> { var out = Set<GUID>([self.root.guid]) func acc(node: MergedTreeNode) { guard let children = node.mergedChildren else { return } out.unionInPlace(children.map { $0.guid }) children.forEach(acc) } acc(self.root) return out } init(mirrorRoot: BookmarkTreeNode) { self.root = MergedTreeNode(guid: mirrorRoot.recordGUID, mirror: mirrorRoot, structureState: MergeState.Unchanged) self.root.valueState = MergeState.Unchanged } func dump() { print("Deleted locally: \(self.deleteLocally.joinWithSeparator(", "))") print("Deleted remotely: \(self.deleteRemotely.joinWithSeparator(", "))") print("Deleted from mirror: \(self.deleteFromMirror.joinWithSeparator(", "))") print("Accepted local deletions: \(self.acceptLocalDeletion.joinWithSeparator(", "))") print("Accepted remote deletions: \(self.acceptRemoteDeletion.joinWithSeparator(", "))") print("Root: ") self.root.dump(0) } }
mpl-2.0
b416ee7fa40d1ef67fa8a95b61ebc819
31.370482
192
0.649577
4.732277
false
false
false
false
rechsteiner/Parchment
Example/Examples/Calendar/DateFormatters.swift
1
603
import Foundation struct DateFormatters { static var shortDateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.timeStyle = .none dateFormatter.dateStyle = .short return dateFormatter }() static var dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "d" return dateFormatter }() static var weekdayFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE" return dateFormatter }() }
mit
ee5d4e4de589ab8c1f61d3617689ad94
26.409091
52
0.656716
6.03
false
false
false
false
malaonline/iOS
mala-ios/Controller/Main/MainViewController.swift
1
6282
// // MainViewController.swift // mala-ios // // Created by Elors on 12/18/15. // Copyright © 2015年 Mala Online. All rights reserved. // import UIKit class MainViewController: UITabBarController, UITabBarControllerDelegate { static let shared = MainViewController() // MARK: - Components /// 首页 private lazy var findTeacherViewController: MainNavigationController = { let naviVC = self.getNaviController( RootViewController.shared, title: L10n.teacher, imageName: "search_normal" ) return naviVC }() /// 课程表 private lazy var classScheduleViewController: MainNavigationController = { let naviVC = self.getNaviController( CourseTableViewController.shared, title: L10n.schedule, imageName: "schedule_normal" ) return naviVC }() /// 错题本 private lazy var memberPrivilegesViewController: MainNavigationController = { let naviVC = self.getNaviController( MemberPrivilegesViewController.shared, title: "错题本", imageName: "serivce_normal" ) return naviVC }() /// 个人 lazy var profileViewController: MainNavigationController = { let naviVC = self.getNaviController( ProfileViewController.shared, title: L10n.profile, imageName: "profile_normal" ) return naviVC }() // MARK: - Property private enum Tab: Int { case teacher case schedule case memberPrivileges case profile var title: String { switch self { case .teacher: return L10n.teacher case .schedule: return L10n.schedule case .profile: return L10n.profile case .memberPrivileges: return "错题本" } } } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() configure() setupTabBar() loadUnpaindOrder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Private Method private func configure() { delegate = self } private func setupTabBar() { let viewControllers: [UIViewController] = [ findTeacherViewController, classScheduleViewController, memberPrivilegesViewController, profileViewController ] self.setViewControllers(viewControllers, animated: false) } /// 查询用户是否有未处理订单/评价 func loadUnpaindOrder() { if !MalaUserDefaults.isLogined { return } MAProvider.userNewMessageCount { (messages) in guard let messages = messages else { return } println("未支付订单数量:\(messages.unpaid) - 待评价数量:\(messages.tocomments)") MalaUnpaidOrderCount = messages.unpaid MalaToCommentCount = messages.tocomments if messages.unpaid != 0, let viewController = getActivityViewController() { DispatchQueue.main.async { self.popAlert(viewController) } } self.profileViewController.showTabBadgePoint = (MalaUnpaidOrderCount > 0 || MalaToCommentCount > 0) } } /// 弹出未支付订单提示 private func popAlert(_ viewController: UIViewController) { let alert = JSSAlertView().show(viewController, title: L10n.youHaveSomeUnpaidOrder, buttonText: L10n.viewOrder, iconImage: UIImage(asset: .alertPaymentSuccess) ) alert.addAction(switchToProfile) } /// 切换到个人信息页面 private func switchToProfile() { let orderViewController = OrderFormViewController() orderViewController.hidesBottomBarWhenPushed = true if let viewController = getActivityViewController() { viewController.navigationController?.pushViewController(orderViewController, animated: true) } } /// Convenience Function to Create SubViewControllers /// And Add Into TabBarViewController /// /// - parameter viewController: ViewController /// - parameter title: String for ViewController's Title /// - parameter imageName: String for ImageName private func getNaviController(_ viewController: UIViewController, title: String, imageName: String) -> MainNavigationController { viewController.title = title viewController.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal) viewController.tabBarItem.selectedImage = UIImage(named: imageName)?.withRenderingMode(.alwaysTemplate) let navigationController = MainNavigationController(rootViewController: viewController) return navigationController } // MARK: - Delegate func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { /* guard let navi = viewController as? UINavigationController else { return false } // 点击[我的]页面前需要登录校验 if navi.topViewController is ProfileViewController /*|| navi.topViewController is ClassScheduleViewController*/ { // 未登陆则进行登陆动作 if !MalaUserDefaults.isLogined { self.present( UINavigationController(rootViewController: LoginViewController()), animated: true, completion: { () -> Void in }) return false } } */ return true } }
mit
81e5cb77b7c2e7180c6bf35cc6619747
30.158163
134
0.579663
5.734272
false
false
false
false
Kevin-De-Koninck/Sub-It
Sub It/Constants.swift
1
1330
// // Constants.swift // Sub It // // Created by Kevin De Koninck on 28/01/2017. // Copyright © 2017 Kevin De Koninck. All rights reserved. // import Foundation import Cocoa // Command let DEFAULT_COMMAND = "export PATH=$PATH:/usr/local/bin && subliminal download -s -l en" let DEFAULT_OUTPUTPATH = "~/Downloads/" let REGEX_PATTERN = ".+?(?=\\[)" //matches anything before the [ //Color var blueColor = NSColor.init(red: 45.0/255, green: 135.0/255, blue: 250.0/255, alpha: 1) // Settings let DEFAULT_SETTINGS = [ "selectedPath" : "~/Downloads/", "singleFile" : "1", //bool "forceDownload" : "1", //bool "preferHearingImpaired" : "0", //bool "useFilter" : "0", //bool "seperateDownloadsFolder": "0", //bool "languageSubs1" : "0", //index "languageSubs2" : "0" //index ] // User Defaults - keys let SAVED_COMMAND = "savedCommand" let SETTINGS_KEY = "settings" let SUBLIMINAL = "isYTDLInstalled" let BREW = "isBrewInstalled" let PYTHON = "isPythonInstalled" let XCODE = "isXcodeInstalled" let OUTPUT_PATH = "outputPath"
mit
9f28769fa0bf0d8212c11df5299b1671
33.076923
88
0.528217
3.743662
false
false
false
false
firebase/firebase-ios-sdk
FirebaseStorage/Sources/Internal/StorageUtils.swift
1
3327
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation #if os(iOS) || os(tvOS) import MobileCoreServices #elseif os(macOS) || os(watchOS) import CoreServices #endif class StorageUtils { internal class func defaultRequestForReference(reference: StorageReference, queryParams: [String: String]? = nil) -> URLRequest { var components = URLComponents() components.scheme = reference.storage.scheme components.host = reference.storage.host components.port = reference.storage.port if let queryParams = queryParams { var queryItems = [URLQueryItem]() for (key, value) in queryParams { queryItems.append(URLQueryItem(name: key, value: value)) } components.queryItems = queryItems // NSURLComponents does not encode "+" as "%2B". This is however required by our backend, as // it treats "+" as a shorthand encoding for spaces. See also // https://stackoverflow.com/questions/31577188/how-to-encode-into-2b-with-nsurlcomponents components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences( of: "+", with: "%2B" ) } let encodedPath = encodedURL(for: reference.path) components.percentEncodedPath = encodedPath guard let url = components.url else { fatalError("FirebaseStorage Internal Error: Failed to create url for \(reference.bucket)") } return URLRequest(url: url) } internal class func encodedURL(for path: StoragePath) -> String { let bucketString = "/b/\(GCSEscapedString(path.bucket))" var objectString: String if let objectName = path.object { objectString = "/o/\(GCSEscapedString(objectName))" } else { objectString = "/o" } return "/v0\(bucketString)\(objectString)" } internal class func GCSEscapedString(_ string: String) -> String { // This is the list at https://cloud.google.com/storage/docs/json_api/ without &, ; and +. let allowedSet = CharacterSet( charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*,=:@" ) return string.addingPercentEncoding(withAllowedCharacters: allowedSet)! } internal class func MIMETypeForExtension(_ fileExtension: String?) -> String { guard let fileExtension = fileExtension else { return "application/octet-stream" } if let type = UTTypeCreatePreferredIdentifierForTag( kUTTagClassFilenameExtension, fileExtension as NSString, nil )?.takeRetainedValue() { if let mimeType = UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType)? .takeRetainedValue() { return mimeType as String } } return "application/octet-stream" } }
apache-2.0
cd5c6534bd604da535856e77bb9ecb64
35.966667
100
0.689811
4.725852
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/IncomingRequestFooterTests.swift
1
2095
// // 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 XCTest @testable import Wire class IncomingRequestFooterTests: ZMSnapshotTestCase { override func setUp() { super.setUp() } func testIncomingRequestFooter_Light() { let footer = IncomingRequestFooterView() footer.overrideUserInterfaceStyle = .light let view = footer.prepareForSnapshots() verify(view: view) } func testIncomingRequestFooter_Dark() { let footer = IncomingRequestFooterView() footer.overrideUserInterfaceStyle = .dark let view = footer.prepareForSnapshots() verify(view: view) } } fileprivate extension IncomingRequestFooterView { func prepareForSnapshots() -> UIView { let container = UIView() container.addSubview(self) translatesAutoresizingMaskIntoConstraints = false container.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ container.widthAnchor.constraint(equalToConstant: 375), container.topAnchor.constraint(equalTo: topAnchor), container.bottomAnchor.constraint(equalTo: bottomAnchor), container.leadingAnchor.constraint(equalTo: leadingAnchor), container.trailingAnchor.constraint(equalTo: trailingAnchor) ]) container.setNeedsLayout() container.layoutIfNeeded() return container } }
gpl-3.0
8f92afbc284577b3c72dc5389c25cd1d
30.268657
72
0.70358
5.17284
false
true
false
false
zendobk/SwiftUtils
Sources/Classes/SwiftUtils.swift
1
1990
// // Type.swift // SwiftUtils // // Created by DaoNV on 12/30/15. // Copyright © 2016 Asian Tech Co., Ltd. All rights reserved. // import UIKit typealias JSObject = [String: AnyObject] typealias JSArray = [JSObject] public enum DeviceType { case iPhone4 case iPhone5 case iPhone6 case iPhone6p case iPhoneX case iPhoneXS case iPhoneXR case iPhoneXSMax case iPad case iPadPro105 case iPadPro129 public var size: CGSize { switch self { case .iPhone4: return CGSize(width: 320, height: 480) case .iPhone5: return CGSize(width: 320, height: 568) case .iPhone6: return CGSize(width: 375, height: 667) case .iPhone6p: return CGSize(width: 414, height: 736) case .iPhoneX: return CGSize(width: 375, height: 812) case .iPhoneXS: return CGSize(width: 375, height: 812) case .iPhoneXR: return CGSize(width: 414, height: 896) case .iPhoneXSMax: return CGSize(width: 414, height: 896) case .iPad: return CGSize(width: 768, height: 1024) case .iPadPro105: return CGSize(width: 834, height: 1112) case .iPadPro129: return CGSize(width: 1024, height: 1366) } } } public let kScreenSize = UIScreen.main.bounds.size public let iPhone = (UIDevice.current.userInterfaceIdiom == .phone) public let iPad = (UIDevice.current.userInterfaceIdiom == .pad) public let iPhone4 = (iPhone && DeviceType.iPhone4.size == kScreenSize) public let iPhone5 = (iPhone && DeviceType.iPhone5.size == kScreenSize) public let iPhone6 = (iPhone && DeviceType.iPhone6.size == kScreenSize) public let iPhone6p = (iPhone && DeviceType.iPhone6p.size == kScreenSize) public let iPhoneX = (iPhone && DeviceType.iPhoneX.size == kScreenSize) public let iPhoneXS = (iPhone && DeviceType.iPhoneXS.size == kScreenSize) public let iPhoneXR = (iPhone && DeviceType.iPhoneXR.size == kScreenSize) public let iPhoneXSMax = (iPhone && DeviceType.iPhoneXSMax.size == kScreenSize)
apache-2.0
570e4f771ef890791f5929d9d056c1f3
34.517857
79
0.691805
3.774194
false
false
false
false
twostraws/HackingWithSwift
Classic/project33/Project33/RecordWhistleViewController.swift
1
5654
// // RecordWhistleViewController.swift // Project33 // // Created by TwoStraws on 24/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import AVFoundation import UIKit class RecordWhistleViewController: UIViewController, AVAudioRecorderDelegate { var stackView: UIStackView! var recordButton: UIButton! var playButton: UIButton! var recordingSession: AVAudioSession! var whistleRecorder: AVAudioRecorder! var whistlePlayer: AVAudioPlayer! override func loadView() { view = UIView() view.backgroundColor = UIColor.gray stackView = UIStackView() stackView.spacing = 30 stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = UIStackView.Distribution.fillEqually stackView.alignment = .center stackView.axis = .vertical view.addSubview(stackView) stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } override func viewDidLoad() { super.viewDidLoad() title = "Record your whistle" navigationItem.backBarButtonItem = UIBarButtonItem(title: "Record", style: .plain, target: nil, action: nil) recordingSession = AVAudioSession.sharedInstance() do { try recordingSession.setCategory(.playAndRecord, mode: .default) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { if allowed { self.loadRecordingUI() } else { self.loadFailUI() } } } } catch { self.loadFailUI() } } func loadRecordingUI() { recordButton = UIButton() recordButton.translatesAutoresizingMaskIntoConstraints = false recordButton.setTitle("Tap to Record", for: .normal) recordButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title1) recordButton.addTarget(self, action: #selector(recordTapped), for: .touchUpInside) stackView.addArrangedSubview(recordButton) playButton = UIButton() playButton.translatesAutoresizingMaskIntoConstraints = false playButton.setTitle("Tap to Play", for: .normal) playButton.isHidden = true playButton.alpha = 0 playButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title1) playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside) stackView.addArrangedSubview(playButton) } func loadFailUI() { let failLabel = UILabel() failLabel.font = UIFont.preferredFont(forTextStyle: .headline) failLabel.text = "Recording failed: please ensure the app has access to your microphone." failLabel.numberOfLines = 0 stackView.addArrangedSubview(failLabel) } class func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } class func getWhistleURL() -> URL { return getDocumentsDirectory().appendingPathComponent("whistle.m4a") } func startRecording() { // 1 view.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1) // 2 recordButton.setTitle("Tap to Stop", for: .normal) // 3 let audioURL = RecordWhistleViewController.getWhistleURL() print(audioURL.absoluteString) // 4 let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { // 5 whistleRecorder = try AVAudioRecorder(url: audioURL, settings: settings) whistleRecorder.delegate = self whistleRecorder.record() } catch { finishRecording(success: false) } } func finishRecording(success: Bool) { view.backgroundColor = UIColor(red: 0, green: 0.6, blue: 0, alpha: 1) whistleRecorder.stop() whistleRecorder = nil if success { recordButton.setTitle("Tap to Re-record", for: .normal) if playButton.isHidden { UIView.animate(withDuration: 0.35) { [unowned self] in self.playButton.isHidden = false self.playButton.alpha = 1 } } navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTapped)) } else { recordButton.setTitle("Tap to Record", for: .normal) let ac = UIAlertController(title: "Record failed", message: "There was a problem recording your whistle; please try again.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } @objc func nextTapped() { let vc = SelectGenreViewController() navigationController?.pushViewController(vc, animated: true) } @objc func recordTapped() { if whistleRecorder == nil { startRecording() if !playButton.isHidden { UIView.animate(withDuration: 0.35) { [unowned self] in self.playButton.isHidden = true self.playButton.alpha = 0 } } } else { finishRecording(success: true) } } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if !flag { finishRecording(success: false) } } @objc func playTapped() { let audioURL = RecordWhistleViewController.getWhistleURL() do { whistlePlayer = try AVAudioPlayer(contentsOf: audioURL) whistlePlayer.play() } catch { let ac = UIAlertController(title: "Playback failed", message: "There was a problem playing your whistle; please try re-recording.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } }
unlicense
57a442cc45491129f461dfe3e3b8c186
27.989744
158
0.731116
3.980986
false
false
false
false
aamays/Yelp
Yelp/Views/BusinessDetailViewCell.swift
1
1588
// // BusinessDetailViewCell.swift // Yelp // // Created by Amay Singhal on 9/27/15. // Copyright © 2015 Timothy Lee. All rights reserved. // import UIKit import AFNetworking class BusinessDetailViewCell: UITableViewCell { @IBOutlet weak var businessImageView: UIImageView! @IBOutlet weak var businessNameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var ratingsImageView: UIImageView! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var openLabel: UILabel! @IBOutlet weak var reviewLabel: UILabel! var business: Business! { didSet { updateBusinessDetailsInCell() } } func updateBusinessDetailsInCell() { businessImageView.contentMode = .ScaleToFill businessImageView.setImageWithURL(business.imageURL) businessNameLabel.text = business.name ratingsImageView.setImageWithURL(business.ratingImageURL) categoryLabel.text = business.categories reviewLabel.text = "\(business.reviewCount!) Reviews" openLabel.text = business.open! ? "Open" : "Closed" openLabel.textColor = business.open! ? UIColor(red: 34/255, green: 139/255, blue: 34/255, alpha: 1) : UIColor.redColor() distanceLabel.text = business.distance } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
2b9cde83fb4480aa5aff2a631bbaaefe
29.519231
128
0.689351
4.6
false
false
false
false
hanhailong/practice-swift
Games/UberJump/UberJump/GameState.swift
3
1240
import UIKit class GameState: NSObject { var _score:Int = 0 var _highScore:Int = 0 var _stars:Int = 0 class var sharedInstance :GameState { struct Singleton { static let instance = GameState() } return Singleton.instance } override init(){ // Init _score = 0 _highScore = 0 _stars = 0 // Load game state var defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() var highScore = defaults.objectForKey("highScore") if let y = highScore as? Int { _highScore = y } var stars = defaults.objectForKey("stars") if let y = stars as? Int{ _stars = y } } func saveGame(){ // Update highScore if the current score is greater _highScore = max(_score, _highScore) // Store in user defaults var defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() defaults.setObject(_highScore, forKey: "highScore") defaults.setObject(_highScore, forKey: "stars") defaults.synchronize() } }
mit
61f1de6a12db3bd1cd7138e48dac6a71
21.545455
75
0.530645
5.344828
false
false
false
false
mzaks/EntitasKit
Entitas-Swift/Logging/EntitasLogger.swift
1
8974
// // EntitasLogger.swift // EntitasKitTests // // Created by Maxim Zaks on 04.03.18. // Copyright © 2018 Maxim Zaks. All rights reserved. // import Foundation public class EntitasLogger { var tick: Tick = 0 var eventTypes = [EventType]() var ticks = [Tick]() var timestamps = [Timestamp]() var contextIds = [ContextId]() var entityIds = [EntityId]() var compNameIds = [CompNameId]() var systemNameIds = [SystemNameId]() var infoIds = [InfoId]() var infos = [String]() let loggingStartTime: CFAbsoluteTime var contextMap = [ObjectIdentifier: ContextId]() var contextNamesMap = [String: ContextId]() var contextNames = [String]() var entityContextMap = [ObjectIdentifier: ContextId]() var systemNameMap = [String: SystemNameId]() var systemNames = [String]() var firstExecSystemNameId = SystemNameId.max private func systemId(_ name: String) -> SystemNameId { if let systemId = systemNameMap[name] { return systemId } let id = SystemNameId(systemNameMap.count) systemNameMap[name] = id systemNames.append(name) return id } var componentCidMap = [CID: CompNameId]() var componentNameMap = [String: CompNameId]() var compNames = [String]() private func compId(_ component: Component) -> CompNameId { if let compId = componentCidMap[component.cid] { return compId } let id = UInt16(componentCidMap.count) componentCidMap[component.cid] = id componentNameMap["\(type(of:component))"] = id compNames.append("\(type(of:component))") return id } var sysCallStack = [(Timestamp, SystemNameId, EventType)]() var sysCallStackMaterialised = 0 public init(contexts: [(Context, String)]) { loggingStartTime = CFAbsoluteTimeGetCurrent() for (ctx, name) in contexts { contextMap[ObjectIdentifier(ctx)] = ContextId(contextMap.count) contextNamesMap[name] = ContextId(contextNames.count) contextNames.append(name) ctx.observer(add: self) } } public func addInfo(_ text: String) { sysCallStackMaterialise() let infoId = InfoId(infos.count) infos.append(text) addEvent( type: .info, timestamp: currentTimestamp, systemNameId: sysCallStack.last?.1 ?? SystemNameId.max, infoId: infoId ) } public func addError(_ text: String) { sysCallStackMaterialise() let infoId = InfoId(infos.count) infos.append(text) addEvent( type: .error, timestamp: currentTimestamp, systemNameId: sysCallStack.last?.1 ?? SystemNameId.max, infoId: infoId ) } private func addEvent( type: EventType, timestamp: Timestamp, contextId: ContextId = .max, entityId: EntityId = .max, compNameId: CompNameId = .max, systemNameId: SystemNameId = .max, infoId: InfoId = .max ) { eventTypes.append(type) ticks.append(tick) timestamps.append(timestamp) contextIds.append(contextId) entityIds.append(entityId) compNameIds.append(compNameId) systemNameIds.append(systemNameId) infoIds.append(infoId) } private var currentTimestamp: Timestamp { // WE can record only 710 minutes return Timestamp((CFAbsoluteTimeGetCurrent() - loggingStartTime) * 100_000) } } extension EntitasLogger: SystemExecuteLogger { private func pushSysCall(event: EventType, sysName: String) { let sysId = systemId(sysName) if event == .willExec { if firstExecSystemNameId == .max { firstExecSystemNameId = sysId tick += 1 } else if firstExecSystemNameId == sysId { tick += 1 } } sysCallStack.append((currentTimestamp, sysId, event)) } private func popSysCal(event: EventType, name: String) { let timestamp = currentTimestamp if sysCallStackMaterialised != sysCallStack.count { if let sysCall = sysCallStack.last, timestamp - sysCall.0 > 500 { sysCallStackMaterialise() addEvent(type: event, timestamp: timestamp, systemNameId: systemId(name)) sysCallStack.removeLast() sysCallStackMaterialised = sysCallStack.count } else { sysCallStack.removeLast() } } else { addEvent(type: event, timestamp: timestamp, systemNameId: systemId(name)) sysCallStack.removeLast() sysCallStackMaterialised = sysCallStack.count } } private func sysCallStackMaterialise() { guard sysCallStack.isEmpty == false && sysCallStackMaterialised < sysCallStack.count else { return } for sysCal in sysCallStack[sysCallStackMaterialised...] { addEvent(type: sysCal.2, timestamp: sysCal.0, systemNameId: sysCal.1) } sysCallStackMaterialised = sysCallStack.count } public func willExecute(_ name: String) { pushSysCall(event: .willExec, sysName: name) } public func didExecute(_ name: String) { popSysCal(event: .didExec, name: name) } public func willInit(_ name: String) { pushSysCall(event: .willInit, sysName: name) } public func didInit(_ name: String) { popSysCal(event: .didInit, name: name) } public func willCleanup(_ name: String) { pushSysCall(event: .willCleanup, sysName: name) } public func didCleanup(_ name: String) { popSysCal(event: .didCleanup, name: name) } public func willTeardown(_ name: String) { pushSysCall(event: .willTeardown, sysName: name) } public func didTeardown(_ name: String) { popSysCal(event: .didTeardown, name: name) } } extension EntitasLogger: ContextObserver { public func created(entity: Entity, in context: Context) { entity.observer(add: self) sysCallStackMaterialise() let entityId = EntityId(entity.creationIndex) let contextId = contextMap[ObjectIdentifier(context)] ?? ContextId.max addEvent( type: .created, timestamp: currentTimestamp, contextId: contextId, entityId: entityId, systemNameId: sysCallStack.last?.1 ?? SystemNameId.max ) entityContextMap[ObjectIdentifier(entity)] = contextId } public func created(group: Group, withMatcher matcher: Matcher, in context: Context) {} public func created<T, C>(index: Index<T, C>, in context: Context) {} } extension EntitasLogger: EntityObserver { public func updated(component oldComponent: Component?, with newComponent: Component, in entity: Entity) { sysCallStackMaterialise() let entityId = EntityId(entity.creationIndex) let entityObjectId = ObjectIdentifier(entity) let contextId = entityContextMap[entityObjectId] ?? ContextId.max let compNameId = compId(newComponent) let infoId: InfoId if let compInfo = (newComponent as? ComponentInfo)?.info { infoId = InfoId(infos.count) infos.append(compInfo) } else { infoId = .max } addEvent( type: oldComponent == nil ? .added : .replaced, timestamp: currentTimestamp, contextId: contextId, entityId: entityId, compNameId: compNameId, systemNameId: sysCallStack.last?.1 ?? SystemNameId.max, infoId: infoId ) } public func removed(component: Component, from entity: Entity) { sysCallStackMaterialise() let entityId = EntityId(entity.creationIndex) let entityObjectId = ObjectIdentifier(entity) let contextId = entityContextMap[entityObjectId] ?? ContextId.max let compNameId = compId(component) addEvent( type: .removed, timestamp: currentTimestamp, contextId: contextId, entityId: entityId, compNameId: compNameId, systemNameId: sysCallStack.last?.1 ?? SystemNameId.max ) } public func destroyed(entity: Entity) { entity.observer(add: self) sysCallStackMaterialise() let entityId = EntityId(entity.creationIndex) let entityObjectId = ObjectIdentifier(entity) let contextId = entityContextMap[entityObjectId] ?? ContextId.max addEvent( type: .destroyed, timestamp: currentTimestamp, contextId: contextId, entityId: entityId, systemNameId: sysCallStack.last?.1 ?? SystemNameId.max ) entityContextMap[entityObjectId] = nil } }
mit
a425d06ea94434bedf010b79a2ea69e2
32.110701
110
0.617296
4.431111
false
false
false
false
gameontext/sample-room-swift
Sources/SwiftRoom/Constants.swift
1
2139
/** * Copyright IBM Corporation 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. */ public struct Constants { struct Room { static let lookUnknown = "It doesn't look interesting" static func unknownCommand(command: String) -> String { return "This room is a basic model. It doesn't understand \(command)" } static let unspecifiedDirection = "You didn't say which way you wanted to go." static func unknownDirection(direction: String) -> String { return "There isn't a door in this direction: \(direction)" } static func helloAll(name: String) -> String { return "\(name) is here" } static let helloUser = "Welcome!" static func goodbyeAll(name: String) -> String { return "\(name) has gone" } static let goodbyeUser = "Bye!" } struct Message { // Prefix for bookmark, this is appended with a unique string. Customize it! static let prefix = "room-" // The below constants are JSON elements specifying parts of a message static let type = "type" static let event = "event" static let chat = "chat" static let userId = "userId" static let username = "username" static var content = "content" static let bookmark = "bookmark" static let all = "*" } }
apache-2.0
45b017c74332243b03c9e3cf45bc8235
27.905405
86
0.571295
5.117225
false
false
false
false
the-grid/Disc
DiscTests/Models/GitHubTokenSpec.swift
1
924
import Argo import Disc import Nimble import Quick class GitHubTokenSpec: QuickSpec { override func spec() { let username = "gridbear" let value = "nijcoqf3h3287f7g" let json: JSON = .Object([ "username": .String(username), "token": .String(value) ]) let token = GitHubToken(username: username, value: value) describe("decoding") { it("should produce a GitHubToken") { guard let decoded = GitHubToken.decode(json).value else { return XCTFail("Unable to decode JSON: \(json)") } expect(decoded).to(equal(token)) } } describe("encoding") { it("should produce JSON") { let encoded = token.encode() expect(encoded).to(equal(json)) } } } }
mit
b99317b5235d6424b5b86e88d57781a8
26.176471
73
0.496753
4.690355
false
false
false
false
zeroc-ice/ice
swift/test/Ice/optional/TestI.swift
3
9151
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import TestCommon class InitialI: Initial { func shutdown(current: Ice.Current) throws { current.adapter!.getCommunicator().shutdown() } func pingPong(o: Ice.Value?, current _: Ice.Current) throws -> Ice.Value? { return o } func opOptionalException(a: Int32?, b: String?, o: OneOptional?, current _: Ice.Current) throws { throw OptionalException(req: false, a: a, b: b, o: o) } func opDerivedException(a: Int32?, b: String?, o: OneOptional?, current _: Ice.Current) throws { throw DerivedException(req: false, a: a, b: b, o: o, d1: "d1", ss: b, o2: o, d2: "d2") } func opRequiredException(a: Int32?, b: String?, o: OneOptional?, current _: Ice.Current) throws { let e = RequiredException() e.a = a e.b = b e.o = o if let b = b { e.ss = b } e.o2 = o throw e } func opByte(p1: UInt8?, current _: Ice.Current) throws -> (returnValue: UInt8?, p3: UInt8?) { return (p1, p1) } func opBool(p1: Bool?, current _: Ice.Current) throws -> (returnValue: Bool?, p3: Bool?) { return (p1, p1) } func opShort(p1: Int16?, current _: Ice.Current) throws -> (returnValue: Int16?, p3: Int16?) { return (p1, p1) } func opInt(p1: Int32?, current _: Ice.Current) throws -> (returnValue: Int32?, p3: Int32?) { return (p1, p1) } func opLong(p1: Int64?, current _: Ice.Current) throws -> (returnValue: Int64?, p3: Int64?) { return (p1, p1) } func opFloat(p1: Float?, current _: Ice.Current) throws -> (returnValue: Float?, p3: Float?) { return (p1, p1) } func opDouble(p1: Double?, current _: Ice.Current) throws -> (returnValue: Double?, p3: Double?) { return (p1, p1) } func opString(p1: String?, current _: Ice.Current) throws -> (returnValue: String?, p3: String?) { return (p1, p1) } func opCustomString(p1: String?, current _: Current) throws -> (returnValue: String?, p3: String?) { return (p1, p1) } func opMyEnum(p1: MyEnum?, current _: Ice.Current) throws -> (returnValue: MyEnum?, p3: MyEnum?) { return (p1, p1) } func opSmallStruct(p1: SmallStruct?, current _: Ice.Current) throws -> (returnValue: SmallStruct?, p3: SmallStruct?) { return (p1, p1) } func opFixedStruct(p1: FixedStruct?, current _: Ice.Current) throws -> (returnValue: FixedStruct?, p3: FixedStruct?) { return (p1, p1) } func opVarStruct(p1: VarStruct?, current _: Ice.Current) throws -> (returnValue: VarStruct?, p3: VarStruct?) { return (p1, p1) } func opOneOptional(p1: OneOptional?, current _: Ice.Current) throws -> (returnValue: OneOptional?, p3: OneOptional?) { return (p1, p1) } func opOneOptionalProxy(p1: Ice.ObjectPrx?, current _: Ice.Current) throws -> (returnValue: Ice.ObjectPrx?, p3: Ice.ObjectPrx?) { return (p1, p1) } func opByteSeq(p1: ByteSeq?, current _: Ice.Current) throws -> (returnValue: ByteSeq?, p3: ByteSeq?) { return (p1, p1) } func opBoolSeq(p1: BoolSeq?, current _: Ice.Current) throws -> (returnValue: BoolSeq?, p3: BoolSeq?) { return (p1, p1) } func opShortSeq(p1: ShortSeq?, current _: Ice.Current) throws -> (returnValue: ShortSeq?, p3: ShortSeq?) { return (p1, p1) } func opIntSeq(p1: IntSeq?, current _: Ice.Current) throws -> (returnValue: IntSeq?, p3: IntSeq?) { return (p1, p1) } func opLongSeq(p1: LongSeq?, current _: Ice.Current) throws -> (returnValue: LongSeq?, p3: LongSeq?) { return (p1, p1) } func opFloatSeq(p1: FloatSeq?, current _: Ice.Current) throws -> (returnValue: FloatSeq?, p3: FloatSeq?) { return (p1, p1) } func opDoubleSeq(p1: DoubleSeq?, current _: Ice.Current) throws -> (returnValue: DoubleSeq?, p3: DoubleSeq?) { return (p1, p1) } func opStringSeq(p1: StringSeq?, current _: Ice.Current) throws -> (returnValue: StringSeq?, p3: StringSeq?) { return (p1, p1) } func opSmallStructSeq(p1: SmallStructSeq?, current _: Ice.Current) throws -> (returnValue: SmallStructSeq?, p3: SmallStructSeq?) { return (p1, p1) } func opSmallStructList(p1: SmallStructList?, current _: Ice.Current) throws -> (returnValue: SmallStructList?, p3: SmallStructList?) { return (p1, p1) } func opFixedStructSeq(p1: FixedStructSeq?, current _: Ice.Current) throws -> (returnValue: FixedStructSeq?, p3: FixedStructSeq?) { return (p1, p1) } func opFixedStructList(p1: FixedStructList?, current _: Ice.Current) throws -> (returnValue: FixedStructList?, p3: FixedStructList?) { return (p1, p1) } func opVarStructSeq(p1: VarStructSeq?, current _: Ice.Current) throws -> (returnValue: VarStructSeq?, p3: VarStructSeq?) { return (p1, p1) } func opSerializable(p1: Serializable?, current _: Current) throws -> (returnValue: Serializable?, p3: Serializable?) { return (p1, p1) } func opIntIntDict(p1: [Int32: Int32]?, current _: Ice.Current) throws -> (returnValue: [Int32: Int32]?, p3: [Int32: Int32]?) { return (p1, p1) } func opStringIntDict(p1: [String: Int32]?, current _: Ice.Current) throws -> (returnValue: [String: Int32]?, p3: [String: Int32]?) { return (p1, p1) } func opCustomIntStringDict(p1: IntStringDict?, current _: Current) throws -> (returnValue: IntStringDict?, p3: IntStringDict?) { return (p1, p1) } func opIntOneOptionalDict(p1: [Int32: OneOptional?]?, current _: Ice.Current) throws -> (returnValue: [Int32: OneOptional?]?, p3: [Int32: OneOptional?]?) { return (p1, p1) } func opClassAndUnknownOptional(p _: A?, current _: Ice.Current) throws {} func sendOptionalClass(req _: Bool, o _: OneOptional?, current _: Ice.Current) throws {} func returnOptionalClass(req _: Bool, current _: Ice.Current) throws -> OneOptional? { return OneOptional(a: 53) } func opG(g: G?, current _: Ice.Current) throws -> G? { return g } func opVoid(current _: Ice.Current) throws {} func supportsRequiredParams(current _: Ice.Current) throws -> Bool { return false } func supportsJavaSerializable(current _: Ice.Current) throws -> Bool { return false } func supportsCsharpSerializable(current _: Ice.Current) throws -> Bool { return false } func supportsCppStringView(current _: Ice.Current) throws -> Bool { return false } func supportsNullOptional(current _: Ice.Current) throws -> Bool { return false } func opMStruct1(current _: Current) throws -> SmallStruct? { return SmallStruct() } func opMStruct2(p1: SmallStruct?, current _: Current) throws -> (returnValue: SmallStruct?, p2: SmallStruct?) { return (p1, p1) } func opMSeq1(current _: Current) throws -> StringSeq? { return [] } func opMSeq2(p1: StringSeq?, current _: Current) throws -> (returnValue: StringSeq?, p2: StringSeq?) { return (p1, p1) } func opMDict1(current _: Current) throws -> StringIntDict? { return [:] } func opMDict2(p1: StringIntDict?, current _: Current) throws -> (returnValue: StringIntDict?, p2: StringIntDict?) { return (p1, p1) } func opMG1(current _: Current) throws -> G? { return G() } func opMG2(p1: G?, current _: Current) throws -> (returnValue: G?, p2: G?) { return (p1, p1) } }
gpl-2.0
9208d477044b8824e95993991a5d1adb
34.061303
119
0.511966
4.135111
false
false
false
false
yulingtianxia/Spiral
Spiral/OrdinaryMap.swift
1
1859
// // Map.swift // Spiral // // Created by 杨萧玉 on 14-7-12. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import UIKit import SpriteKit open class OrdinaryMap: SKNode { var spacing:CGFloat = 0.0 var points:[CGPoint] = [] public convenience init(origin:CGPoint,layer:Int, size:CGSize){ var x:CGFloat = origin.x var y:CGFloat = origin.y self.init() //计算每层路径间隔距离 spacing = size.width / CGFloat(layer * 2-1) points.append(CGPoint(x: x, y: y)) for index in 1..<layer { y-=spacing*(2*CGFloat(index)-1) points.append(CGPoint(x: x, y: y)) x-=spacing*(2*CGFloat(index)-1) points.append(CGPoint(x: x, y: y)) y+=spacing*2*CGFloat(index) points.append(CGPoint(x: x, y: y)) x+=spacing*2*CGFloat(index) points.append(CGPoint(x: x, y: y)) } addRopes() } //将地图节点数组用绳子串起来 func addRopes(){ for index in 0..<points.count-1 { addRopesFromPointA(points[index], toPointB: points[index + 1]) } } //递归填充比图片长的直线 func addRopesFromPointA(_ a:CGPoint, toPointB b:CGPoint){ let xDistance = b.x-a.x let yDistance = b.y-a.y let distance = sqrt(xDistance * xDistance + yDistance * yDistance) let rope = Rope(length: distance) rope.zRotation = atan(xDistance / yDistance) let scale = rope.size.height / distance let realB = CGPoint(x: a.x + scale * xDistance, y: a.y + scale * yDistance) if scale < 1 { addRopesFromPointA(realB, toPointB: b) } let center = CGPoint(x: (a.x + realB.x)/2, y: (a.y + realB.y)/2) rope.position = center addChild(rope) } }
apache-2.0
d9803dad11c92e4f376bf911c49ba42e
30.732143
83
0.561621
3.278598
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Models/OneTap/PXPaymentMethodBehaviour.swift
1
1915
import Foundation public struct PXPaymentMethodBehaviour: Codable { let paymentTypeRules: [String]? let paymentMethodRules: [String]? let sliderTitle: String? let behaviours: [Behaviour]? public init(paymentTypeRules: [String]?, paymentMethodRules: [String]?, sliderTitle: String?, behaviours: [Behaviour]?) { self.paymentTypeRules = paymentTypeRules self.paymentMethodRules = paymentMethodRules self.sliderTitle = sliderTitle self.behaviours = behaviours } public enum CodingKeys: String, CodingKey { case paymentTypeRules = "payment_type_rules" case paymentMethodRules = "payment_method_rules" case sliderTitle = "slider_title" case behaviours = "behaviours" } } public struct Behaviour: Codable { let type: String let modalContent: ModalContent public init(type: String, modalContent: ModalContent) { self.type = type self.modalContent = modalContent } public enum CodingKeys: String, CodingKey { case type case modalContent = "modal_content" } } public struct ModalContent: Codable { let title: PXText let description: PXText let button: Button let imageURL: String? public init(title: PXText, description: PXText, button: Button, imageURL: String?) { self.title = title self.description = description self.button = button self.imageURL = imageURL } public enum CodingKeys: String, CodingKey { case title case description case button case imageURL = "image_url" } } public struct Button: Codable { let label: String let target: String? public init(label: String, target: String?) { self.label = label self.target = target } public enum CodingKeys: String, CodingKey { case label case target } }
mit
400fff3f9c488a57c09b2aa58b952765
25.232877
125
0.653786
4.537915
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Tracking/PXTrackingStore.swift
1
1355
import Foundation final class PXTrackingStore { enum TrackingChoType: String { case one_tap case one_tap_selector case traditional } static let sharedInstance = PXTrackingStore() static let cardIdsESC = "CARD_IDS_ESC" private var data = [String: Any]() private var initDate: Date = Date() private var trackingChoType: TrackingChoType? public func addData(forKey: String, value: Any) { self.data[forKey] = value } public func remove(key: String) { data.removeValue(forKey: key) } public func removeAll() { data.removeAll() } public func getData(forKey: String) -> Any? { return self.data[forKey] } } // MARK: Screen time support methods. extension PXTrackingStore { func initializeInitDate() { initDate = Date() } func getSecondsAfterInit() -> Int { guard let seconds = Calendar.current.dateComponents([Calendar.Component.second], from: initDate, to: Date()).second else { return 0 } return seconds } } // MARK: Tracking cho type. extension PXTrackingStore { func getChoType() -> String? { return trackingChoType?.rawValue } func setChoType(_ type: TrackingChoType) { trackingChoType = type } func cleanChoType() { trackingChoType = nil } }
mit
6a5a30fc7ac25ce1ed13859851d901e0
22.362069
141
0.633948
4.169231
false
false
false
false
buyiyang/iosstar
iOSStar/General/Base/PhotoBrowserVC.swift
4
1115
import UIKit import MWPhotoBrowser class PhotoBrowserVC: MWPhotoBrowser { convenience init(image:UIImage) { let photo = MWPhoto(image: image) self.init(photos:[photo!]) } override func viewDidLoad() { super.viewDidLoad() modalPresentationStyle = .custom modalTransitionStyle = .crossDissolve displayActionButton = true displayNavArrows = false displaySelectionButtons = false zoomPhotosToFill = true alwaysShowControls = false enableGrid = true startOnGrid = false autoPlayOnAppear = false enableSwipeToDismiss = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(selfDismiss)) view.subviews.first?.subviews.first?.subviews[1].addGestureRecognizer(tapGes) } func selfDismiss() { dismiss(animated: true, completion: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) dismiss(animated: true, completion: nil) } }
gpl-3.0
477e709799fb3652ecd5cd7a28694560
29.972222
89
0.650224
5.162037
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/PriceDetailObj.swift
1
1935
// // PriceDetailObj.swift // UberGoCore // // Created by Nghia Tran on 7/10/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Unbox public final class PriceDetailObj: Unboxable { // MARK: - Variable public var serviceFees: [ServiceFeeObj] public var costPerMinute: Float public var distanceUnit: String public var minimum: Float public var costPerDistance: Float public var base: Float public var cancellationFee: Float public var currencyCode: String // MARK: - Init public required init(unboxer: Unboxer) throws { serviceFees = try unboxer.unbox(key: Constants.Object.PriceDetail.ServiceFees) costPerMinute = try unboxer.unbox(key: Constants.Object.PriceDetail.CostPerMinute) distanceUnit = try unboxer.unbox(key: Constants.Object.PriceDetail.DistanceUnit) minimum = try unboxer.unbox(key: Constants.Object.PriceDetail.Minimum) costPerDistance = try unboxer.unbox(key: Constants.Object.PriceDetail.CostPerDistance) base = try unboxer.unbox(key: Constants.Object.PriceDetail.Base) cancellationFee = try unboxer.unbox(key: Constants.Object.PriceDetail.CancellationFee) currencyCode = try unboxer.unbox(key: Constants.Object.PriceDetail.CurrencyCode) } // Get all available services // The list isn't always fixed public lazy var allAvailableServiceFees: [ServiceFeeObj] = { var services: [ServiceFeeObj] = [] // Base services.append(ServiceFeeObj(name: "Base Fare", fee: self.base)) services.append(ServiceFeeObj(name: "Minimum Fare", fee: self.minimum)) services.append(ServiceFeeObj(name: "+ Per Minute", fee: self.costPerMinute)) services.append(ServiceFeeObj(name: "+ Per \(self.distanceUnit)", fee: self.costPerDistance)) // Append services.append(contentsOf: self.serviceFees) return services }() }
mit
0d444926aa478177e8138983b3eac5df
37.68
101
0.703723
4.186147
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/UberNotificationViewModel.swift
1
2176
// // UberNotificationViewModel.swift // UberGoCore // // Created by Nghia Tran on 8/30/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Foundation import RxCocoa import RxSwift public protocol UberNotificationViewModelProtocol { var input: UberNotificationViewModelInput { get } var output: UberNotificationViewModelOutput { get } } public protocol UberNotificationViewModelInput { } public protocol UberNotificationViewModelOutput { } public final class UberNotificationViewModel: UberNotificationViewModelProtocol, UberNotificationViewModelInput, UberNotificationViewModelOutput { // MARK: - Protocol public var input: UberNotificationViewModelInput { return self } public var output: UberNotificationViewModelOutput { return self } // MARK: - Service fileprivate var service: UberNotificationService // MARK: - Variable fileprivate let disposeBag = DisposeBag() // MARK: - Init init(service: UberNotificationService, appViewMode: AppViewModelProtocol, uberViewModel: UberServiceViewModelProtocol) { self.service = service // Handle show notification if need uberViewModel.output.currentTripStatusDriver .flatMapLatest({ (result) -> Driver<APIResult<TripObj>> in guard appViewMode.output.popoverStateVariable.value == .close else { return Driver.empty() } return Driver.just(result) }) .distinctUntilChanged { (old, new) -> Bool in // New state if old.isSucces && new.isSucces { return old.rawValue.status == new.rawValue.status } // Both are error if old.isError && new.isError { return true } // Different state return false } .drive(onNext: { (result) in service.notifyUberNotification(result) }) .addDisposableTo(disposeBag) } }
mit
b998d5a2929eb4176b4c0450f01893db
27.618421
84
0.605057
5.397022
false
false
false
false
VadimPavlov/SMVC
PerfectProject/Classes/Screens/Login/LoginController.swift
1
2003
// // LoginController.swift // PerfectProject // // Created by Vadim Pavlov on 10/7/16. // Copyright © 2016 Vadim Pavlov. All rights reserved. // import Foundation class LoginController: Controller<LoginView> { fileprivate var loginCancellationToken: ((Void) -> Void)? let actions: Actions struct Actions { let signIn: (@escaping User.Logining, String) -> Future<User, NSError> let signUp: (@escaping User.Logining, String) -> Future<User, NSError> } let flow: (Flow) -> Void enum Flow { case signup case user (User) } init(actions: Actions, flow: @escaping (Flow) -> Void) { self.actions = actions self.flow = flow let state = LoginState() super.init(state: state) } } // MARK: - Actions extension LoginController { func signIn(email: String, password: String) { let user = User.login(email: email) let operation = self.actions.signIn(user, password) self.login(operation: operation) } func signUp(email: String, password: String) { let user = User.login(email: email) let operation = self.actions.signUp(user, password) self.login(operation: operation) } func cancelLogin() { self.loginCancellationToken?() // cancellation called self.state = LoginState() // or reset to default } } // MARK: - Private private extension LoginController { func show(user:User) { self.flow(.user(user)) } func login(operation: Future<User, NSError>) { self.loginCancellationToken = operation.start { result in self.state.loading = false switch result { case .Success(let user): self.state.loggedIn = NSDate() self.show(user: user) case .Error(let error): self.state.error = error } } self.state.loading = true } }
mit
9f111c198538b4d1019998be749d1553
25.342105
78
0.586913
4.259574
false
false
false
false
wangshengjia/VWInstantRun
VWInstantRun/VWInstantRun.swift
1
2545
// // VWInstantRun.swift // // Created by Victor WANG on 20/12/15. // Copyright © 2015 Victor Wang. All rights reserved. // import Foundation import AppKit var sharedPlugin: VWInstantRun? class VWInstantRun: NSObject { // TODO: support more modules static let modules = ["Foundation"] var bundle: NSBundle lazy var center = NSNotificationCenter.defaultCenter() init(bundle: NSBundle) { self.bundle = bundle super.init() center.addObserver(self, selector: #selector(VWInstantRun.createMenuItems), name: NSApplicationDidFinishLaunchingNotification, object: nil) } deinit { removeObserver() } func removeObserver() { center.removeObserver(self) } func createMenuItems() { removeObserver() let item = NSApp.mainMenu?.itemWithTitle("Product") if item != nil { let actionMenuItem = NSMenuItem(title:"Instant Run", action:#selector(VWInstantRun.instantRun), keyEquivalent:"") actionMenuItem.keyEquivalentModifierMask = Int(NSEventModifierFlags.ShiftKeyMask.rawValue | NSEventModifierFlags.CommandKeyMask.rawValue | NSEventModifierFlags.AlternateKeyMask.rawValue) actionMenuItem.keyEquivalent = "R" actionMenuItem.target = self item!.submenu!.addItem(NSMenuItem.separatorItem()) item!.submenu!.addItem(actionMenuItem) } } } extension VWInstantRun { func instantRun() { guard let selectedLines = VWXcodeHelpers.selectedLines() else { return } guard let _ = try? VWFileIO.prepareTempDirectory() else { return } if VWXcodeHelpers.isObjCFile() { guard let _ = try? VWFileIO.writeToObjcMainFileWithText(selectedLines) else { return } VWPluginHelper.buildWithObjc(onCompletion: VWPluginHelper.run) } else if VWXcodeHelpers.isSwiftFile() { guard let _ = try? VWFileIO.writeToSwiftMainFileWithText(importModules() + selectedLines) else { return } VWPluginHelper.buildWithSwift(onCompletion: VWPluginHelper.run) } else { VWPluginHelper.logOutput("\n ERROR: Unexpected file type. Only support .swift, .m & .h") } } private func importModules() -> String { return VWInstantRun.modules.map({ (module) -> String in return "import " + module }).joinWithSeparator("\n") + "\n" } }
mit
aded47d765379fbb7ead63ad077a3db9
28.929412
198
0.632075
4.567325
false
false
false
false
shadanan/mado
Antlr4Runtime/Sources/Antlr4/misc/extension/StringExtension.swift
1
7300
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. //import Cocoa #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif //http://stackoverflow.com/questions/28182441/swift-how-to-get-substring-from-start-to-last-index-of-character //https://github.com/williamFalcon/Bolt_Swift/blob/master/Bolt/BoltLibrary/String/String.swift extension String { func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } func split(_ separator: String) -> [String] { return self.components(separatedBy: separator) } func replaceAll(_ from: String, replacement: String) -> String { return self.replacingOccurrences(of: from, with: replacement, options: NSString.CompareOptions.literal, range: nil) } func containsIgnoreCase(_ find: String) -> Bool { return self.lowercased().range(of: find.lowercased()) != nil } var length: Int { return self.characters.count } func indexOf(_ target: String) -> Int { let range = self.range(of: target) if let range = range { return self.characters.distance(from: self.startIndex, to: range.lowerBound) } else { return -1 } } func indexOf(_ target: String, startIndex: Int) -> Int { let startRange = self.characters.index(self.startIndex, offsetBy: startIndex) let range = self.range(of: target, options: NSString.CompareOptions.literal, range: startRange..<self.endIndex) if let range = range { return self.characters.distance(from: self.startIndex, to: range.lowerBound) } else { return -1 } } func lastIndexOf(_ target: String) -> Int { var index = -1 var stepIndex = self.indexOf(target) while stepIndex > -1 { index = stepIndex if stepIndex + target.length < self.length { stepIndex = indexOf(target, startIndex: stepIndex + target.length) } else { stepIndex = -1 } } return index } func substringAfter(_ string: String) -> String { if let range = self.range(of: string) { let intIndex: Int = self.characters.distance(from: self.startIndex, to: range.upperBound) return self.substring(from: self.characters.index(self.startIndex, offsetBy: intIndex)) } return self } var lowercaseFirstChar: String { var result = self if self.length > 0 { let startIndex = self.startIndex result.replaceSubrange(startIndex ... startIndex, with: String(self[startIndex]).lowercased()) } return result } func substringWithRange(_ range: Range<Int>) -> String { let start = self.characters.index(self.startIndex, offsetBy: range.lowerBound) let end = self.characters.index(self.startIndex, offsetBy: range.upperBound) return self.substring(with: start ..< end) } subscript(integerIndex: Int) -> Character { let index = characters.index(startIndex, offsetBy: integerIndex) return self[index] } subscript(integerRange: Range<Int>) -> String { let start = characters.index(startIndex, offsetBy: integerRange.lowerBound) let end = characters.index(startIndex, offsetBy: integerRange.upperBound) let range = start ..< end return self[range] } func charAt(_ index: Int) -> Character { return self[self.characters.index(self.startIndex, offsetBy: index)] } } // Mapping from XML/HTML character entity reference to character // From http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references private let characterEntities: [String:Character] = [ // XML predefined entities: "&quot;": "\"", "&amp;": "&", "&apos;": "'", "&lt;": "<", "&gt;": ">", // HTML character entity references: "&nbsp;": "\u{00a0}", // ... "&diams;": "♦", ] extension String { /// Returns a new string made by replacing in the `String` /// all HTML character entity references with the corresponding /// character. var stringByDecodingHTMLEntities: String { // Convert the number in the string to the corresponding // Unicode character, e.g. // decodeNumeric("64", 10) --> "@" // decodeNumeric("20ac", 16) --> "€" func decodeNumeric(_ string: String, base: Int32) -> Character? { let code = UInt32(strtoul(string, nil, base)) return Character(UnicodeScalar(code)!) } // Decode the HTML character entity to the corresponding // Unicode character, return `nil` for invalid input. // decode("&#64;") --> "@" // decode("&#x20ac;") --> "€" // decode("&lt;") --> "<" // decode("&foo;") --> nil func decode(_ entity: String) -> Character? { if entity.hasPrefix("&#x") || entity.hasPrefix("&#X") { return decodeNumeric(entity.substring(from: entity.characters.index(entity.startIndex, offsetBy: 3)), base: 16) } else if entity.hasPrefix("&#") { return decodeNumeric(entity.substring(from: entity.characters.index(entity.startIndex, offsetBy: 2)), base: 10) } else { return characterEntities[entity] } } var result = "" var position = startIndex // Find the next '&' and copy the characters preceding it to `result`: while let ampRange = self.range(of: "&", range: position ..< endIndex) { result.append(self[position ..< ampRange.lowerBound]) position = ampRange.lowerBound // Find the next ';' and copy everything from '&' to ';' into `entity` if let semiRange = self.range(of: ";", range: position ..< endIndex) { let entity = self[position ..< semiRange.upperBound] position = semiRange.upperBound if let decoded = decode(entity) { // Replace by decoded character: result.append(decoded) } else { // Invalid entity, copy verbatim: result.append(entity) } } else { // No matching ';'. break } } // Copy remaining characters to `result`: result.append(self[position ..< endIndex]) return result } } extension String { static let htmlEscapedDictionary = [ "&amp;": "&", "&quot;": "\"", "&#x27;": "'", "&#x39;": "'", "&#x92;": "'", "&#x96;": "'", "&gt;": ">", "&lt;": "<"] public var escapedHtmlString: String { var newString = "\(self)" for (key, value) in String.htmlEscapedDictionary { newString = newString.replaceAll(value, replacement: key) } return newString } }
mit
7faa9f055dcd604adea6daa10d57ec69
31.132159
127
0.572251
4.519207
false
false
false
false
yanagiba/swift-ast
Sources/Lexer/UnicodeScalar+Lexer.swift
2
2765
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ extension UnicodeScalar { var string: String { return String(self) } var int: Int? { return Int(string) } var hex: Int? { let capitalA: Int = 65 let capitalF: Int = 70 let smallA: Int = 97 let smallF: Int = 102 if let v = Int(string) { return v } let xs = string.unicodeScalars let x = Int(xs[xs.startIndex].value) if (capitalA <= x) && (x <= capitalF) { return x - capitalA + 10 } if (smallA <= x) && (x <= smallF) { return x - smallA + 10 } return nil } } /*- * Thie file contains code derived from * https://github.com/demmys/treeswift/blob/master/src/Parser/TokenComposer.swift * with the following license: * * BSD 2-clause "Simplified" License * * Copyright (c) 2014, Atsuki Demizu * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
apache-2.0
8b93687c8b382f0495ea3dbb592f2742
34.909091
85
0.718626
4.280186
false
false
false
false
rnystrom/GitHawk
Classes/Issues/Comments/Unsupported/IssueCommentUnsupportedCell.swift
1
1047
// // IssueCommentUnsupportedCell.swift // Freetime // // Created by Ryan Nystrom on 6/19/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit import IGListKit final class IssueCommentUnsupportedCell: IssueCommentBaseCell, ListBindable { let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = .red label.font = UIFont.boldSystemFont(ofSize: 14) label.textAlignment = .center label.textColor = .white label.backgroundColor = .clear contentView.addSubview(label) label.snp.makeConstraints { make in make.center.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: ListBindable func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? IssueCommentUnsupportedModel else { return } label.text = viewModel.name } }
mit
eb56008a727009cb86a8fc91fdfde30b
23.325581
88
0.662524
4.587719
false
false
false
false
mcxiaoke/learning-ios
swift-language-guide/25_Advanced_Operators.playground/Contents.swift
1
4409
//: Playground - noun: a place where people can play // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html#//apple_ref/doc/uid/TP40014097-CH41-ID3 import UIKit let initialBits: UInt8 = 0b00001111 let invertedBits = ~initialBits // equals 11110000 let firstSixBits: UInt8 = 0b11111100 let lastSixBits: UInt8 = 0b00111111 let middleFourBits = firstSixBits & lastSixBits // equals 00111100 let someBits: UInt8 = 0b10110010 let moreBits: UInt8 = 0b01011110 let combinedbits = someBits | moreBits // equals 11111110 let firstBits: UInt8 = 0b00010100 let otherBits: UInt8 = 0b00000101 let outputBits = firstBits ^ otherBits // equals 00010001 let shiftBits: UInt8 = 4 // 00000100 in binary shiftBits << 1 // 00001000 shiftBits << 2 // 00010000 shiftBits << 5 // 10000000 shiftBits << 6 // 00000000 shiftBits >> 2 // 00000001 let pink: UInt32 = 0xCC6699 let redComponent = (pink & 0xFF0000) >> 16 // redComponent is 0xCC, or 204 let greenComponent = (pink & 0x00FF00) >> 8 // greenComponent is 0x66, or 102 let blueComponent = pink & 0x0000FF // blueComponent is 0x99, or 153 var unsignedOverflow = UInt8.max // unsignedOverflow equals 255, which is the maximum value a UInt8 can hold unsignedOverflow = unsignedOverflow &+ 1 // unsignedOverflow is now equal to 0 var unsignedOverflow2 = UInt8.min // unsignedOverflow equals 0, which is the minimum value a UInt8 can hold unsignedOverflow2 = unsignedOverflow2 &- 1 // unsignedOverflow is now equal to 255 var signedOverflow3 = Int8.min // signedOverflow equals -128, which is the minimum value an Int8 can hold signedOverflow3 = signedOverflow3 &- 1 // signedOverflow is now equal to 127 // operator function struct Vector2D { var x = 0.0, y = 0.0 } func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } let vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector // combinedVector is a Vector2D instance with values of (5.0, 5.0) print("result: \(combinedVector)") prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) } let positive = Vector2D(x: 3.0, y: 4.0) let negative = -positive // negative is a Vector2D instance with values of (-3.0, -4.0) let alsoPositive = -negative // alsoPositive is a Vector2D instance with values of (3.0, 4.0) print(negative) print(alsoPositive) func += (inout left: Vector2D, right: Vector2D) { left = left + right } var original = Vector2D(x: 1.0, y: 2.0) let vectorToAdd = Vector2D(x: 3.0, y: 4.0) original += vectorToAdd // original now has values of (4.0, 6.0) print(original) prefix func ++ (inout vector: Vector2D) -> Vector2D { vector += Vector2D(x: 1.0, y: 1.0) return vector } var toIncrement = Vector2D(x: 3.0, y: 4.0) let afterIncrement = ++toIncrement // toIncrement now has values of (4.0, 5.0) // afterIncrement also has values of (4.0, 5.0) print(toIncrement) print(afterIncrement) func == (left: Vector2D, right: Vector2D) -> Bool { return (left.x == right.x) && (left.y == right.y) } func != (left: Vector2D, right: Vector2D) -> Bool { return !(left == right) } let twoThree = Vector2D(x: 2.0, y: 3.0) let anotherTwoThree = Vector2D(x: 2.0, y: 3.0) if twoThree == anotherTwoThree { print("These two vectors are equivalent.") } // prints "These two vectors are equivalent." // custom operators // declare operator prefix operator +++ {} // impl operator for Vector2D prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } var toBeDoubled = Vector2D(x: 1.0, y: 4.0) let afterDoubling = +++toBeDoubled // toBeDoubled now has values of (2.0, 8.0) // afterDoubling also has values of (2.0, 8.0) print(toBeDoubled) print(afterDoubling) // custom infix operators infix operator +- { associativity left precedence 140 } func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } let firstVector = Vector2D(x: 1.0, y: 2.0) let secondVector = Vector2D(x: 3.0, y: 4.0) let plusMinusVector = firstVector +- secondVector // plusMinusVector is a Vector2D instance with values of (4.0, -2.0) print(firstVector) print(secondVector) print(plusMinusVector)
apache-2.0
84aa8a36523e2c5a9c056b3debcc14f6
26.216049
159
0.700386
3.102745
false
false
false
false
haveahennessy/Patrician
Patrician/Radix.swift
1
7196
// // radix.swift // Patrician // // Created by Matt Isaacs. // Copyright (c) 2015 Matt Isaacs. All rights reserved. // struct Terminal<T> { let key: String let value: T init(key: String, value: T) { self.key = key self.value = value } } struct Edge<T> { let label: Character let node: Node<T> init(label: Character, node: Node<T>) { self.label = label self.node = node } } public struct RadixTree<T> { let root: Node<T> var size: Int public var count: Int { return self.size } init(root: Node<T>) { self.root = root self.size = 0 } public init() { self.init(root: Node(edges: [], prefix: "", terminal: nil)) } public static func emptyTree() -> RadixTree { return self.init(root: Node(edges: [], prefix: "", terminal: nil)) } // Item insertion public mutating func insert(key: String, value: T) { //var search: [Character] = Array(key) var search = key var currentNode = self.root var parent = self.root while true { if search.endIndex == search.startIndex { if let term = currentNode.terminal { currentNode.terminal = Terminal(key: key, value: value) return } currentNode.terminal = Terminal(key: key, value: value) self.size++ return } //let searchLabel = search[0] let searchLabel = search.first! parent = currentNode if let nextNode = currentNode.edgeForLabel(searchLabel)?.node { // Edge exists currentNode = nextNode let commonPrefix = currentNode.prefix.commonPrefixWithString(search, options: NSStringCompareOptions.LiteralSearch) let commonPrefixLength = commonPrefix.endIndex search = search.substringFromIndex(commonPrefixLength) if commonPrefixLength == currentNode.prefix.endIndex { continue } let intermediate = Node<T>(edges: [], prefix: commonPrefix, terminal: nil) let terminal = Terminal(key: key, value: value) let currentSuffix = currentNode.prefix.substringFromIndex(commonPrefixLength) self.size++ parent.replaceEdge(Edge(label: searchLabel, node: intermediate)) intermediate.addEdge(Edge(label: currentSuffix[currentSuffix.startIndex], node: currentNode)) currentNode.prefix = currentSuffix if search.isEmpty { intermediate.terminal = terminal } else { intermediate.addEdge(Edge(label: search.first!, node: Node(edges: [], prefix: search, terminal: terminal))) } return } else { // Create the edge. let terminal = Terminal(key: key, value: value) let node = Node(edges: [], prefix: search, terminal: terminal) let edge = Edge(label: searchLabel, node: node) currentNode.addEdge(edge) self.size++ return } } } // Item lookup by key. public func lookup(key: String) -> T? { var search = key var currentNode = self.root while true { if search.endIndex == search.startIndex { if let term = currentNode.terminal { return term.value } return nil } // search.first can be unwrapped, because we know know that it is non-nil from the check above. if let nextNode = currentNode.edgeForLabel(search.first!)?.node { currentNode = nextNode let currentPrefixLength = currentNode.prefix.endIndex if search.hasPrefix(currentNode.prefix) { search = search.substringFromIndex(currentPrefixLength) continue } } return nil } } // Remove items from tree. public mutating func delete(key: String) { var search = key var currentNode = self.root var parent = self.root if search.endIndex == search.startIndex { return } while true { // Locate value to be deleted if search.endIndex == search.startIndex { if let term = currentNode.terminal { // Remove leaf currentNode.terminal = nil size-- if currentNode.edges.count == 0 { //let prefixArray = Array(currentNode.prefix) if let label = currentNode.prefix.first { parent.removeEdge(label) // The parent only has one edge remaining. // The parent has no leaf value. // The parent isn't the tree root. if (parent.edges.count == 1) && (parent.prefix.endIndex != parent.prefix.startIndex) && (parent.terminal == nil) { let child = parent.edges.first!.node parent.prefix += child.prefix parent.edges = child.edges parent.terminal = child.terminal } } return } if currentNode.edges.count == 1 { let child = currentNode.edges.first!.node currentNode.prefix += child.prefix currentNode.edges = child.edges currentNode.terminal = child.terminal } } return } parent = currentNode // search.first can be unwrapped, because we know know that it is non-nil from the check above. if let nextNode = currentNode.edgeForLabel(search.first!)?.node { currentNode = nextNode let currentPrefixLength = currentNode.prefix.endIndex if search.hasPrefix(currentNode.prefix) { search = search.substringFromIndex(currentPrefixLength) continue } } return } } public subscript(key: String) -> T? { get { return self.lookup(key) } set(newValue) { if let val = newValue { self.insert(key, value: val) } } } } extension RadixTree : DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, T)...) { self.init() for (key, val) in elements { self.insert(key, value: val) } } }
mit
6ee910929e533b9e70b681cab5ec7ef9
30.840708
142
0.498888
5.326425
false
false
false
false
rasmusth/BluetoothKit
Example/Source/Global/Logger.swift
1
1898
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // 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 internal protocol LoggerDelegate: class { func loggerDidLogString(_ string: String) } internal struct Logger { // MARK: Properties internal static weak var delegate: LoggerDelegate? internal static let loggingDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "HH:mm:ss.SSS" return formatter }() // MARK: Functions internal static func log(_ string: String) { let date = Date() let stringWithDate = "[\(loggingDateFormatter.string(from: date))] \(string)" print(stringWithDate, terminator: "") Logger.delegate?.loggerDidLogString(stringWithDate) } }
mit
b705cfe4237a2b046228913aa651d0e5
35.5
85
0.720232
4.519048
false
false
false
false
ThumbWorks/i-meditated
IMeditated/MinutesListViewModel.swift
1
1367
// // MinutesListViewModel.swift // IMeditated // // Created by Bob Spryn on 8/17/16. // Copyright © 2016 Thumbworks. All rights reserved. // import Foundation import RxSwift import RxCocoa class MinutesListViewModel: MinutesListViewModelType { // TODO: Add tests around this sorting and grouping? let minutesSamplesGroups: Driver<([String], [String: [MinutesEntryViewModel]])> init(minutesListContext: MainContextStateType) { self.minutesSamplesGroups = minutesListContext.allMeditationSamples .observeOn(SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .userInitiated)) .map { $0.map(MinutesEntryViewModel.init) } .map { entries in return entries.categorize { $0.day } }.asDriver(onErrorDriveWith: Driver.just(([], [:]))) } } // Move somewhere shared, add tests public extension Sequence { func categorize<U : Hashable>( keyFunc: (Iterator.Element) -> U) -> ([U], [U:[Iterator.Element]]) { var dict: [U:[Iterator.Element]] = [:] var keys: [U] = [] for el in self { let key = keyFunc(el) if(!keys.contains(key)) { keys.append(key) dict[key] = [el] } else { dict[key]?.append(el) } } return (keys, dict) } }
mit
613ffc4e17f3bf6322b17e2c44b6ab33
28.06383
103
0.598097
4.190184
false
false
false
false
swift-gtk/SwiftGTK
Sources/UIKit/RevealerTransitionType.swift
1
1130
public enum RevealerTransitionType: RawRepresentable { case None, Crossfade, SlideRight, SlideLeft, SlideUp, SlideDown public typealias RawValue = GtkRevealerTransitionType public var rawValue: RawValue { switch self { case .None: return GTK_REVEALER_TRANSITION_TYPE_NONE case .Crossfade: return GTK_REVEALER_TRANSITION_TYPE_CROSSFADE case .SlideRight: return GTK_REVEALER_TRANSITION_TYPE_SLIDE_RIGHT case .SlideLeft: return GTK_REVEALER_TRANSITION_TYPE_SLIDE_LEFT case .SlideUp: return GTK_REVEALER_TRANSITION_TYPE_SLIDE_UP case .SlideDown: return GTK_REVEALER_TRANSITION_TYPE_SLIDE_DOWN } } public init?(rawValue: RawValue) { switch rawValue { case GTK_REVEALER_TRANSITION_TYPE_NONE: self = .None case GTK_REVEALER_TRANSITION_TYPE_CROSSFADE: self = .Crossfade case GTK_REVEALER_TRANSITION_TYPE_SLIDE_RIGHT: self = .SlideRight case GTK_REVEALER_TRANSITION_TYPE_SLIDE_LEFT: self = .SlideLeft case GTK_REVEALER_TRANSITION_TYPE_SLIDE_UP: self = .SlideUp case GTK_REVEALER_TRANSITION_TYPE_SLIDE_DOWN: self = .SlideDown default: return nil } } }
gpl-2.0
cde46bb31c8141678354ecaae34787a0
24.681818
64
0.742478
2.860759
false
false
false
false
VladasZ/iOSTools
Sources/iOS/Views/TopPushPanel.swift
1
1343
// // TopPushPanel.swift // iOSTools // // Created by Vladas Zakrevskis on 8/14/17. // Copyright © 2017 VladasZ. All rights reserved. // #if os(iOS) import UIKit open class TopPushPanel { //MARK: - Properties private static var isVisible: Bool = false public static var view: UIView! open class var height: CGFloat { LogError(); return CGFloat() } open class var visibilityDuration: Int { return 2 } open class var animationDuration: TimeInterval { return 0.211 } open class var autoDismiss: Bool { return true } open class func setup() { view.frame = CGRect(x: 0, y: -height, width: keyWindow.width, height: height) keyWindow.addSubview(view) } public static func show() { if view == nil { setup() } if isVisible { return }; isVisible = true keyWindow.bringSubviewToFront(view) view.isHidden = false UIView.animate(withDuration: animationDuration) { view.y = 0 } if autoDismiss { after(visibilityDuration.toDouble) { dismiss() } } } public static func dismiss() { UIView.animate(withDuration: animationDuration, animations: { view.y = -height }){ _ in view.isHidden = true isVisible = false } } } #endif
mit
d5b70fd6ec4092b7fd249775d34ba5a2
24.320755
96
0.604322
4.357143
false
false
false
false
khizkhiz/swift
stdlib/public/SDK/Foundation/Foundation.swift
1
46074
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import CoreGraphics //===----------------------------------------------------------------------===// // Enums //===----------------------------------------------------------------------===// // FIXME: one day this will be bridged from CoreFoundation and we // should drop it here. <rdar://problem/14497260> (need support // for CF bridging) public var kCFStringEncodingASCII: CFStringEncoding { return 0x0600 } // FIXME: <rdar://problem/16074941> NSStringEncoding doesn't work on 32-bit public typealias NSStringEncoding = UInt public var NSASCIIStringEncoding: UInt { return 1 } public var NSNEXTSTEPStringEncoding: UInt { return 2 } public var NSJapaneseEUCStringEncoding: UInt { return 3 } public var NSUTF8StringEncoding: UInt { return 4 } public var NSISOLatin1StringEncoding: UInt { return 5 } public var NSSymbolStringEncoding: UInt { return 6 } public var NSNonLossyASCIIStringEncoding: UInt { return 7 } public var NSShiftJISStringEncoding: UInt { return 8 } public var NSISOLatin2StringEncoding: UInt { return 9 } public var NSUnicodeStringEncoding: UInt { return 10 } public var NSWindowsCP1251StringEncoding: UInt { return 11 } public var NSWindowsCP1252StringEncoding: UInt { return 12 } public var NSWindowsCP1253StringEncoding: UInt { return 13 } public var NSWindowsCP1254StringEncoding: UInt { return 14 } public var NSWindowsCP1250StringEncoding: UInt { return 15 } public var NSISO2022JPStringEncoding: UInt { return 21 } public var NSMacOSRomanStringEncoding: UInt { return 30 } public var NSUTF16StringEncoding: UInt { return NSUnicodeStringEncoding } public var NSUTF16BigEndianStringEncoding: UInt { return 0x90000100 } public var NSUTF16LittleEndianStringEncoding: UInt { return 0x94000100 } public var NSUTF32StringEncoding: UInt { return 0x8c000100 } public var NSUTF32BigEndianStringEncoding: UInt { return 0x98000100 } public var NSUTF32LittleEndianStringEncoding: UInt { return 0x9c000100 } //===----------------------------------------------------------------------===// // NSObject //===----------------------------------------------------------------------===// // These conformances should be located in the `ObjectiveC` module, but they can't // be placed there because string bridging is not available there. extension NSObject : CustomStringConvertible {} extension NSObject : CustomDebugStringConvertible {} //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message="Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message="Please use String or NSString") public class NSConstantString {} @warn_unused_result @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(string: String) -> NSString { return string._bridgeToObjectiveC() } @warn_unused_result @_semantics("convertFromObjectiveC") public // COMPILER_INTRINSIC func _convertNSStringToString(nsstring: NSString?) -> String { if nsstring == nil { return "" } var result: String? String._forceBridgeFromObjectiveC(nsstring!, result: &result) return result! } extension NSString : StringLiteralConvertible { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutablePointer<Void>(value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? NSASCIIStringEncoding : NSUTF8StringEncoding, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: NSUTF32StringEncoding)! } self.init(string: immutableResult as String) } } //===----------------------------------------------------------------------===// // New Strings //===----------------------------------------------------------------------===// // // Conversion from NSString to Swift's native representation // extension String { public init(_ cocoaString: NSString) { self = String(_cocoaString: cocoaString) } } extension String : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSString.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSString { // This method should not do anything extra except calling into the // implementation inside core. (These two entry points should be // equivalent.) return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSString.self) } public static func _forceBridgeFromObjectiveC( x: NSString, result: inout String? ) { result = String(x) } public static func _conditionallyBridgeFromObjectiveC( x: NSString, result: inout String? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } } //===----------------------------------------------------------------------===// // Numbers //===----------------------------------------------------------------------===// // Conversions between NSNumber and various numeric types. The // conversion to NSNumber is automatic (auto-boxing), while conversion // back to a specific numeric type requires a cast. // FIXME: Incomplete list of types. extension Int : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.integerValue } public static func _getObjectiveCType() -> Any.Type { return NSNumber.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(integer: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Int? ) { result = x.integerValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Int? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } extension UInt : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.unsignedIntegerValue } public static func _getObjectiveCType() -> Any.Type { return NSNumber.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(unsignedInteger: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout UInt? ) { result = x.unsignedIntegerValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout UInt? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } extension Float : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.floatValue } public static func _getObjectiveCType() -> Any.Type { return NSNumber.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(float: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Float? ) { result = x.floatValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Float? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } extension Double : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.doubleValue } public static func _getObjectiveCType() -> Any.Type { return NSNumber.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(double: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Double? ) { result = x.doubleValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Double? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } extension Bool: _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.boolValue } public static func _getObjectiveCType() -> Any.Type { return NSNumber.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(bool: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Bool? ) { result = x.boolValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Bool? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } // CGFloat bridging. extension CGFloat : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self.native = CGFloat.NativeType(number) } public static func _getObjectiveCType() -> Any.Type { return NSNumber.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return self.native._bridgeToObjectiveC() } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout CGFloat? ) { var nativeResult: CGFloat.NativeType? = 0.0 CGFloat.NativeType._forceBridgeFromObjectiveC(x, result: &nativeResult) result = CGFloat(nativeResult!) } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout CGFloat? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } // Literal support for NSNumber extension NSNumber : FloatLiteralConvertible, IntegerLiteralConvertible, BooleanLiteralConvertible { /// Create an instance initialized to `value`. public required convenience init(integerLiteral value: Int) { self.init(integer: value) } /// Create an instance initialized to `value`. public required convenience init(floatLiteral value: Double) { self.init(double: value) } /// Create an instance initialized to `value`. public required convenience init(booleanLiteral value: Bool) { self.init(bool: value) } } public let NSNotFound: Int = .max //===----------------------------------------------------------------------===// // Arrays //===----------------------------------------------------------------------===// extension NSArray : ArrayLiteralConvertible { /// Create an instance initialized with `elements`. public required convenience init(arrayLiteral elements: AnyObject...) { // + (instancetype)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt; let x = _extractOrCopyToNativeArrayBuffer(elements._buffer) self.init( objects: UnsafeMutablePointer(x.firstElementAddress), count: x.count) _fixLifetime(x) } } /// The entry point for converting `NSArray` to `Array` in bridge /// thunks. Used, for example, to expose : /// /// func f([NSView]) {} /// /// to Objective-C code as a method that accepts an `NSArray`. This operation /// is referred to as a "forced conversion" in ../../../docs/Arrays.rst @warn_unused_result @_semantics("convertFromObjectiveC") public func _convertNSArrayToArray<T>(source: NSArray?) -> [T] { if _slowPath(source == nil) { return [] } var result: [T]? Array._forceBridgeFromObjectiveC(source!, result: &result) return result! } /// The entry point for converting `Array` to `NSArray` in bridge /// thunks. Used, for example, to expose : /// /// func f() -> [NSView] { return [] } /// /// to Objective-C code as a method that returns an `NSArray`. @warn_unused_result public func _convertArrayToNSArray<T>(array: [T]) -> NSArray { return array._bridgeToObjectiveC() } extension Array : _ObjectiveCBridgeable { /// Private initializer used for bridging. /// /// The provided `NSArray` will be copied to ensure that the copy can /// not be mutated by other code. internal init(_cocoaArray: NSArray) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFArrayCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFArrayCreateCopy() copies array contents unconditionally, // resulting in O(n) copies even for immutable arrays. // // <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than // -[NSArray copyWithZone:] // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Array( _immutableCocoaArray: unsafeBitCast(_cocoaArray.copy(), to: _NSArrayCore.self)) } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Element.self) } public static func _getObjectiveCType() -> Any.Type { return NSArray.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSArray { return unsafeBitCast(self._buffer._asCocoaArray(), to: NSArray.self) } public static func _forceBridgeFromObjectiveC( source: NSArray, result: inout Array? ) { _precondition( Swift._isBridgedToObjectiveC(Element.self), "array element type is not bridged to Objective-C") // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) { result = native return } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) result = Array(_cocoaArray: source) return } result = _arrayForceCast([AnyObject](_cocoaArray: source)) } public static func _conditionallyBridgeFromObjectiveC( source: NSArray, result: inout Array? ) -> Bool { // Construct the result array by conditionally bridging each element. let anyObjectArr = [AnyObject](_cocoaArray: source) result = _arrayConditionalCast(anyObjectArr) return result != nil } } //===----------------------------------------------------------------------===// // Dictionaries //===----------------------------------------------------------------------===// extension NSDictionary : DictionaryLiteralConvertible { public required convenience init( dictionaryLiteral elements: (NSCopying, AnyObject)... ) { self.init( objects: elements.map { (AnyObject?)($0.1) }, forKeys: elements.map { (NSCopying?)($0.0) }, count: elements.count) } } extension Dictionary { /// Private initializer used for bridging. /// /// The provided `NSDictionary` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaDictionary: _NSDictionary) { _sanityCheck( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), "Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C") // FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFDictionaryCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Dictionary( _immutableCocoaDictionary: unsafeBitCast(_cocoaDictionary.copy(with: nil), to: _NSDictionary.self)) } } /// The entry point for bridging `NSDictionary` to `Dictionary` in bridge /// thunks. Used, for example, to expose: /// /// func f([String : String]) {} /// /// to Objective-C code as a method that accepts an `NSDictionary`. /// /// This is a forced downcast. This operation should have O(1) complexity /// when `Key` and `Value` are bridged verbatim. /// /// The cast can fail if bridging fails. The actual checks and bridging can be /// deferred. @warn_unused_result @_semantics("convertFromObjectiveC") public func _convertNSDictionaryToDictionary< Key : Hashable, Value >(d: NSDictionary?) -> [Key : Value] { // Note: there should be *a good justification* for doing something else // than just dispatching to `_forceBridgeFromObjectiveC`. if _slowPath(d == nil) { return [:] } var result: [Key : Value]? Dictionary._forceBridgeFromObjectiveC(d!, result: &result) return result! } // FIXME: right now the following is O(n), not O(1). /// The entry point for bridging `Dictionary` to `NSDictionary` in bridge /// thunks. Used, for example, to expose: /// /// func f() -> [String : String] {} /// /// to Objective-C code as a method that returns an `NSDictionary`. /// /// This is a forced downcast. This operation should have O(1) complexity. /// /// The cast can fail if bridging fails. The actual checks and bridging can be /// deferred. @warn_unused_result public func _convertDictionaryToNSDictionary<Key, Value>( d: [Key : Value] ) -> NSDictionary { // Note: there should be *a good justification* for doing something else // than just dispatching to `_bridgeToObjectiveC`. return d._bridgeToObjectiveC() } // Dictionary<Key, Value> is conditionally bridged to NSDictionary extension Dictionary : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSDictionary.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDictionary { return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSDictionary.self) } public static func _forceBridgeFromObjectiveC( d: NSDictionary, result: inout Dictionary? ) { if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = [Key : Value]( _cocoaDictionary: unsafeBitCast(d, to: _NSDictionary.self)) return } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d.count) d.enumerateKeysAndObjects({ (anyObjectKey: AnyObject, anyObjectValue: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( x: NSDictionary, result: inout Dictionary? ) -> Bool { let anyDict = x as [NSObject : AnyObject] if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = Swift._dictionaryDownCastConditional(anyDict) return result != nil } result = Swift._dictionaryBridgeFromObjectiveCConditional(anyDict) return result != nil } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Key.self) && Swift._isBridgedToObjectiveC(Value.self) } } //===----------------------------------------------------------------------===// // Fast enumeration //===----------------------------------------------------------------------===// // NB: This is a class because fast enumeration passes around interior pointers // to the enumeration state, so the state cannot be moved in memory. We will // probably need to implement fast enumeration in the compiler as a primitive // to implement it both correctly and efficiently. final public class NSFastEnumerationIterator : IteratorProtocol { var enumerable: NSFastEnumeration var state: [NSFastEnumerationState] var n: Int var count: Int /// Size of ObjectsBuffer, in ids. var STACK_BUF_SIZE: Int { return 4 } // FIXME: Replace with _CocoaFastEnumerationStackBuf. /// Must have enough space for STACK_BUF_SIZE object references. struct ObjectsBuffer { var buf: (OpaquePointer, OpaquePointer, OpaquePointer, OpaquePointer) = (nil, nil, nil, nil) } var objects: [ObjectsBuffer] public func next() -> AnyObject? { if n == count { // FIXME: Is this check necessary before refresh()? if count == 0 { return nil } refresh() if count == 0 { return nil } } let next: AnyObject = state[0].itemsPtr[n]! n += 1 return next } func refresh() { n = 0 count = enumerable.countByEnumerating( with: state._baseAddressIfContiguous, objects: AutoreleasingUnsafeMutablePointer( objects._baseAddressIfContiguous), count: STACK_BUF_SIZE) } public init(_ enumerable: NSFastEnumeration) { self.enumerable = enumerable self.state = [ NSFastEnumerationState( state: 0, itemsPtr: nil, mutationsPtr: _fastEnumerationStorageMutationsPtr, extra: (0, 0, 0, 0, 0)) ] self.objects = [ ObjectsBuffer() ] self.n = -1 self.count = -1 } } extension NSArray : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). final public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } /* TODO: API review extension NSArray : Swift.Collection { final public var startIndex: Int { return 0 } final public var endIndex: Int { return count } } */ extension Set { /// Private initializer used for bridging. /// /// The provided `NSSet` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaSet: _NSSet) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Set can be backed by NSSet _variantStorage only when the member type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFSetCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFSetCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20697680> CFSetCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Set( _immutableCocoaSet: unsafeBitCast(_cocoaSet.copy(with: nil), to: _NSSet.self)) } } extension NSSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } extension NSOrderedSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } // FIXME: move inside NSIndexSet when the compiler supports this. public struct NSIndexSetIterator : IteratorProtocol { public typealias Element = Int internal let _set: NSIndexSet internal var _first: Bool = true internal var _current: Int? internal init(set: NSIndexSet) { self._set = set self._current = nil } public mutating func next() -> Int? { if _first { _current = _set.firstIndex _first = false } else if let c = _current { _current = _set.indexGreaterThanIndex(c) } else { // current is already nil } if _current == NSNotFound { _current = nil } return _current } } extension NSIndexSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSIndexSetIterator { return NSIndexSetIterator(set: self) } } // FIXME: right now the following is O(n), not O(1). /// The entry point for bridging `Set` to `NSSet` in bridge /// thunks. Used, for example, to expose: /// /// func f() -> Set<String> {} /// /// to Objective-C code as a method that returns an `NSSet`. /// /// This is a forced downcast. This operation should have O(1) complexity. /// /// The cast can fail if bridging fails. The actual checks and bridging can be /// deferred. @warn_unused_result public func _convertSetToNSSet<T>(s: Set<T>) -> NSSet { return s._bridgeToObjectiveC() } /// The entry point for bridging `NSSet` to `Set` in bridge /// thunks. Used, for example, to expose: /// /// func f(Set<String>) {} /// /// to Objective-C code as a method that accepts an `NSSet`. /// /// This is a forced downcast. This operation should have O(1) complexity /// when `T` is bridged verbatim. /// /// The cast can fail if bridging fails. The actual checks and bridging can be /// deferred. @warn_unused_result @_semantics("convertFromObjectiveC") public func _convertNSSetToSet<T : Hashable>(s: NSSet?) -> Set<T> { if _slowPath(s == nil) { return [] } var result: Set<T>? Set._forceBridgeFromObjectiveC(s!, result: &result) return result! } // Set<Element> is conditionally bridged to NSSet extension Set : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSSet.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSSet { return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSSet.self) } public static func _forceBridgeFromObjectiveC(s: NSSet, result: inout Set?) { if let native = Set<Element>._bridgeFromObjectiveCAdoptingNativeStorageOf(s as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Element.self) { result = Set<Element>(_cocoaSet: unsafeBitCast(s, to: _NSSet.self)) return } // `Set<Element>` where `Element` is a value type may not be backed by // an NSSet. var builder = _SetBuilder<Element>(count: s.count) s.enumerateObjects({ (anyObjectMember: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in builder.add(member: Swift._forceBridgeFromObjectiveC( anyObjectMember, Element.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( x: NSSet, result: inout Set? ) -> Bool { let anySet = x as Set<NSObject> if _isBridgedVerbatimToObjectiveC(Element.self) { result = Swift._setDownCastConditional(anySet) return result != nil } result = Swift._setBridgeFromObjectiveCConditional(anySet) return result != nil } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Element.self) } } extension NSDictionary : Sequence { // FIXME: A class because we can't pass a struct with class fields through an // [objc] interface without prematurely destroying the references. final public class Iterator : IteratorProtocol { var _fastIterator: NSFastEnumerationIterator var _dictionary: NSDictionary { return _fastIterator.enumerable as! NSDictionary } public func next() -> (key: AnyObject, value: AnyObject)? { if let key = _fastIterator.next() { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return (key: key, value: _dictionary.object(forKey: key)!) } return nil } internal init(_ _dict: NSDictionary) { _fastIterator = NSFastEnumerationIterator(_dict) } } /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator(self) } } extension NSEnumerator : Sequence { /// Return an *iterator* over the *enumerator*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } //===----------------------------------------------------------------------===// // Ranges //===----------------------------------------------------------------------===// extension NSRange { public init(_ x: Range<Int>) { location = x.startIndex length = x.count } @warn_unused_result public func toRange() -> Range<Int>? { if location == NSNotFound { return nil } return location..<(location+length) } } //===----------------------------------------------------------------------===// // NSLocalizedString //===----------------------------------------------------------------------===// /// Returns a localized string, using the main bundle if one is not specified. @warn_unused_result public func NSLocalizedString(key: String, tableName: String? = nil, bundle: NSBundle = NSBundle.main(), value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value:value, table:tableName) } //===----------------------------------------------------------------------===// // NSLog //===----------------------------------------------------------------------===// public func NSLog(format: String, _ args: CVarArg...) { withVaList(args) { NSLogv(format, $0) } } #if os(OSX) //===----------------------------------------------------------------------===// // NSRectEdge //===----------------------------------------------------------------------===// // In the SDK, the following NS*Edge constants are defined as macros for the // corresponding CGRectEdge enumerators. Thus, in the SDK, NS*Edge constants // have CGRectEdge type. This is not correct for Swift (as there is no // implicit conversion to NSRectEdge). @available(*, unavailable, renamed="NSRectEdge.MinX") public var NSMinXEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } @available(*, unavailable, renamed="NSRectEdge.MinY") public var NSMinYEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } @available(*, unavailable, renamed="NSRectEdge.MaxX") public var NSMaxXEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } @available(*, unavailable, renamed="NSRectEdge.MaxY") public var NSMaxYEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } extension NSRectEdge { public init(rectEdge: CGRectEdge) { self = NSRectEdge(rawValue: UInt(rectEdge.rawValue))! } } extension CGRectEdge { public init(rectEdge: NSRectEdge) { self = CGRectEdge(rawValue: UInt32(rectEdge.rawValue))! } } #endif //===----------------------------------------------------------------------===// // NSError (as an out parameter). //===----------------------------------------------------------------------===// public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?> // Note: NSErrorPointer becomes ErrorPointer in Swift 3. public typealias ErrorPointer = NSErrorPointer public // COMPILER_INTRINSIC let _nilObjCError: ErrorProtocol = _GenericObjCError.nilError @warn_unused_result @_silgen_name("swift_convertNSErrorToErrorProtocol") public // COMPILER_INTRINSIC func _convertNSErrorToErrorProtocol(error: NSError?) -> ErrorProtocol { if let error = error { return error } return _nilObjCError } @warn_unused_result @_silgen_name("swift_convertErrorProtocolToNSError") public // COMPILER_INTRINSIC func _convertErrorProtocolToNSError(error: ErrorProtocol) -> NSError { return unsafeDowncast(_bridgeErrorProtocolToNSError(error), to: NSError.self) } //===----------------------------------------------------------------------===// // Variadic initializers and methods //===----------------------------------------------------------------------===// 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) } } extension NSExpression { // + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...; public convenience init(format expressionFormat: String, _ args: CVarArg...) { let va_args = getVaList(args) self.init(format: expressionFormat, arguments: va_args) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: NSLocale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } @warn_unused_result public class func localizedStringWithFormat( format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: NSLocale.current(), arguments: $0) } } @warn_unused_result public func appendingFormat(format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSArray { // Overlay: - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: AnyObject...) { // - (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt; let x = _extractOrCopyToNativeArrayBuffer(elements._buffer) // Use Imported: // @objc(initWithObjects:count:) // init(withObjects objects: UnsafePointer<AnyObject?>, // count cnt: Int) self.init(objects: UnsafeMutablePointer(x.firstElementAddress), count: x.count) _fixLifetime(x) } } extension NSOrderedSet { // - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: AnyObject...) { self.init(array: elements) } } extension NSSet { // - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: AnyObject...) { self.init(array: elements) } } extension NSSet : ArrayLiteralConvertible { public required convenience init(arrayLiteral elements: AnyObject...) { self.init(array: elements) } } extension NSOrderedSet : ArrayLiteralConvertible { public required convenience init(arrayLiteral elements: AnyObject...) { self.init(array: elements) } } //===--- "Copy constructors" ----------------------------------------------===// // These are needed to make Cocoa feel natural since we eliminated // implicit bridging conversions from Objective-C to Swift //===----------------------------------------------------------------------===// extension NSArray { /// Initializes a newly allocated array by placing in it the objects /// contained in a given array. /// /// - Returns: An array initialized to contain the objects in /// `anArray``. The returned object might be different than the /// original receiver. /// /// Discussion: After an immutable array has been initialized in /// this way, it cannot be modified. @objc(_swiftInitWithArray_NSArray:) public convenience init(array anArray: NSArray) { self.init(array: anArray as Array) } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @objc(_swiftInitWithString_NSString:) public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSSet { /// Initializes a newly allocated set and adds to it objects from /// another given set. /// /// - Returns: An initialized objects set containing the objects from /// `set`. The returned set might be different than the original /// receiver. @objc(_swiftInitWithSet_NSSet:) public convenience init(set anSet: NSSet) { self.init(set: anSet as Set) } } extension NSDictionary { /// Initializes a newly allocated dictionary and adds to it objects from /// another given dictionary. /// /// - Returns: An initialized dictionary—which might be different /// than the original receiver—containing the keys and values /// found in `otherDictionary`. @objc(_swiftInitWithDictionary_NSDictionary:) public convenience init(dictionary otherDictionary: NSDictionary) { self.init(dictionary: otherDictionary as Dictionary) } } //===----------------------------------------------------------------------===// // NSUndoManager //===----------------------------------------------------------------------===// @_silgen_name("NS_Swift_NSUndoManager_registerUndoWithTargetHandler") internal func NS_Swift_NSUndoManager_registerUndoWithTargetHandler( self_: AnyObject, _ target: AnyObject, _ handler: @convention(block) (AnyObject) -> Void) extension NSUndoManager { @available(OSX 10.11, iOS 9.0, *) public func registerUndoWithTarget<TargetType : AnyObject>( target: TargetType, handler: (TargetType) -> Void ) { // The generic blocks use a different ABI, so we need to wrap the provided // handler in something ObjC compatible. let objcCompatibleHandler: (AnyObject) -> Void = { internalTarget in handler(internalTarget as! TargetType) } NS_Swift_NSUndoManager_registerUndoWithTargetHandler( self as AnyObject, target as AnyObject, objcCompatibleHandler) } } //===----------------------------------------------------------------------===// // NSCoder //===----------------------------------------------------------------------===// @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObject") internal func NS_Swift_NSCoder_decodeObject( self_: AnyObject, _ error: NSErrorPointer) -> AnyObject? @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObjectForKey") internal func NS_Swift_NSCoder_decodeObjectForKey( self_: AnyObject, _ key: AnyObject, _ error: NSErrorPointer) -> AnyObject? @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObjectOfClassForKey") internal func NS_Swift_NSCoder_decodeObjectOfClassForKey( self_: AnyObject, _ cls: AnyObject, _ key: AnyObject, _ error: NSErrorPointer) -> AnyObject? @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObjectOfClassesForKey") internal func NS_Swift_NSCoder_decodeObjectOfClassesForKey( self_: AnyObject, _ classes: NSSet?, _ key: AnyObject, _ error: NSErrorPointer) -> AnyObject? @available(OSX 10.11, iOS 9.0, *) internal func resolveError(error: NSError?) throws { if let error = error where error.code != NSCoderValueNotFoundError { throw error } } extension NSCoder { @warn_unused_result public func decodeObjectOfClass<DecodedObjectType: NSCoding where DecodedObjectType: NSObject>(cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType? { let result = NS_Swift_NSCoder_decodeObjectOfClassForKey(self as AnyObject, cls as AnyObject, key as AnyObject, nil) return result as! DecodedObjectType? } @warn_unused_result @nonobjc public func decodeObjectOfClasses(classes: NSSet?, forKey key: String) -> AnyObject? { var classesAsNSObjects: Set<NSObject>? = nil if let theClasses = classes { classesAsNSObjects = Set(IteratorSequence(NSFastEnumerationIterator(theClasses)).map { unsafeBitCast($0, to: NSObject.self) }) } return self.__decodeObject(ofClasses: classesAsNSObjects, forKey: key) } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObject() throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSCoder_decodeObject(self as AnyObject, &error) try resolveError(error) return result } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObjectForKey(key: String) throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSCoder_decodeObjectForKey(self as AnyObject, key as AnyObject, &error) try resolveError(error) return result } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObjectOfClass<DecodedObjectType: NSCoding where DecodedObjectType: NSObject>(cls: DecodedObjectType.Type, forKey key: String) throws -> DecodedObjectType? { var error: NSError? let result = NS_Swift_NSCoder_decodeObjectOfClassForKey(self as AnyObject, cls as AnyObject, key as AnyObject, &error) try resolveError(error) return result as! DecodedObjectType? } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObjectOfClasses(classes: NSSet?, forKey key: String) throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSCoder_decodeObjectOfClassesForKey(self as AnyObject, classes, key as AnyObject, &error) try resolveError(error) return result } } //===----------------------------------------------------------------------===// // NSKeyedUnarchiver //===----------------------------------------------------------------------===// @warn_unused_result @_silgen_name("NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData") internal func NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData( self_: AnyObject, _ data: AnyObject, _ error: NSErrorPointer) -> AnyObject? extension NSKeyedUnarchiver { @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public class func unarchiveTopLevelObjectWithData(data: NSData) throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData(self, data as AnyObject, &error) try resolveError(error) return result } } //===----------------------------------------------------------------------===// // NSURL //===----------------------------------------------------------------------===// extension NSURL : _FileReferenceLiteralConvertible { private convenience init(failableFileReferenceLiteral path: String) { let fullPath = NSBundle.main().path(forResource: path, ofType: nil)! self.init(fileURLWithPath: fullPath) } public required convenience init(fileReferenceLiteral path: String) { self.init(failableFileReferenceLiteral: path) } } public typealias _FileReferenceLiteralType = NSURL //===----------------------------------------------------------------------===// // Mirror/Quick Look Conformance //===----------------------------------------------------------------------===// extension NSURL : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .url(absoluteString) } } extension NSRange : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["location": location, "length": length]) } } extension NSRange : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .range(Int64(location), Int64(length)) } } extension NSDate : CustomPlaygroundQuickLookable { var summary: String { let df = NSDateFormatter() df.dateStyle = .mediumStyle df.timeStyle = .shortStyle return df.string(from: self) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(summary) } } extension NSSet : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as Set<NSObject>) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } } extension NSArray : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [AnyObject]) } } extension NSDictionary : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [NSObject : AnyObject]) } }
apache-2.0
c26404d2784b39b1c7c409b1eb5dbf99
30.706813
184
0.654526
4.742151
false
false
false
false
barbrobmich/linkbase
LinkBase/LinkBase/AddAffiliationsViewController.swift
1
2566
// // AddAffiliationsViewController.swift // LinkBase // // Created by Barbara Ristau on 4/1/17. // Copyright © 2017 barbrobmich. All rights reserved. // import UIKit import Parse class AddAffiliationsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var currentUser: User! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = false currentUser = User.current() tableView.dataSource = self tableView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) tableView.reloadData() navigationItem.title = "Affiliations" navigationItem.rightBarButtonItem?.title = "Next" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() //self.automaticallyAdjustsScrollViewInsets = false } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddNew" { let destinationVC = segue.destination as! AddNewTableViewController destinationVC.navigationItem.title = "Add New Affiliation" } // this one is not yet functional else if segue.identifier == "Edit" { let destinationVC = segue.destination as! AddNewTableViewController destinationVC.navigationItem.title = "Edit Affiliation" } } } extension AddAffiliationsViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AffiliationsCell", for: indexPath) as! AffiliationsCell if indexPath.section == 0 { cell.cellSection = 1 } else { cell.cellSection = 2 } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return (section%2 == 0) ? "My Affiliations":"Categories" } }
mit
df427c2ecb009bf6fa61f4686102bf54
27.5
121
0.639766
5.411392
false
false
false
false
garygriswold/Bible.js
SafeBible2/SafeBible_ios/SafeBible/Adapters/BiblePageModel.swift
1
12993
// // BiblePageModel.swift // Settings // // Created by Gary Griswold on 10/25/18. // Copyright © 2018 ShortSands. All rights reserved. // // Bible.objectKey contains codes that define String replacements // %I := Id in last part of s3KeyPrefix // %O := ordinal 1 is GEN, 70 is MAT, not zero filled // %o := 3 char ordinal A01 is GEN, zero filled // %B := USFM 3 char book code // %b := 2 char book code // %C := chapter number, not zero filled // %c := chapter number, zero filled, 2 char, 3 Psalms // import AWS import WebKit struct BiblePageModel { func loadPage(reference: Reference, webView: WKWebView, controller: UIViewController) { self.getChapter(reference: reference, view: webView, complete: { html in if html != nil { let page = DynamicCSS.shared.wrapHTML(html: html!, reference: reference) webView.loadHTMLString(page, baseURL: nil) } else { // Usually an error occurs because the book does not exist in this Bible TOCBooksViewController.push(controller: controller) } }) } func loadCompareVerseCell(reference: Reference, startVerse: Int, endVerse: Int, cell: CompareVerseCell, table: UITableView, indexPath: IndexPath) { self.getChapter(reference: reference, view: cell.contentView, complete: { html in if html != nil { cell.verse.text = self.parse(html: html!, reference: reference, startVerse: startVerse, endVerse: endVerse) table.reloadRows(at: [indexPath], with: .automatic) } }) } /** * I guess the correct way to pass back a string is to pass in a Writable Key Path, but I don't understand it. */ func loadLabel(reference: Reference, verse: Int, label: UILabel) { self.getChapter(reference: reference, view: nil, complete: { html in if html != nil { var result = self.parse(html: html!, reference: reference, startVerse: verse, endVerse: verse) result = result.replacingOccurrences(of: String(verse), with: "") label.text = result.trimmingCharacters(in: .whitespacesAndNewlines) } }) } /** Used by HTMLVerseParserTest */ func testParse(reference: Reference, lastVerse: Int, complete: @escaping () -> Void) { self.getChapter(reference: reference, view: nil, complete: { html in for verse in 1..<(lastVerse + 1) { let result = self.parse(html: html!, reference: reference, startVerse: verse, endVerse: verse) if result.count < 5 { print("PARSE ERROR \(reference):\(verse) |\(result)|") } } complete() }) } private func parse(html: String, reference: Reference, startVerse: Int, endVerse: Int) -> String { if reference.isDownloaded { return BibleDB.shared.getBibleVerses(reference: reference, startVerse: startVerse, endVerse: endVerse) } else if reference.isShortsands { let parser = HTMLVerseParserSS(html: html, startVerse: startVerse, endVerse: endVerse) return parser.parseVerses() } else { let parser = HTMLVerseParserDBP(html: html, startVerse: startVerse, endVerse: endVerse) return parser.parseVerses() } } private func getChapter(reference: Reference, view: UIView?, complete: @escaping (_ data:String?) -> Void) { let start = CFAbsoluteTimeGetCurrent() let html = BibleDB.shared.getBiblePage(reference: reference) if html == nil { let progress = self.addProgressIndicator(view: view) let s3Key = self.generateKey(reference: reference) let s3 = (reference.isShortsands) ? AwsS3Manager.findSS() : AwsS3Manager.findDbp() s3.downloadText(s3Bucket: reference.bible.textBucket, s3Key: s3Key, complete: { error, data in self.removeProgressIndicator(indicator: progress) if let err = error { print("ERROR: \(err)") complete(nil) } else if let data1 = data { complete(data1) print("AWS Load \(reference.toString())") _ = BibleDB.shared.storeBiblePage(reference: reference, html: data1) print("*** BiblePageModel.getChapter duration \((CFAbsoluteTimeGetCurrent() - start) * 1000) ms") } }) } else { complete(html) print("DB Load \(reference.toString())") } } private func addProgressIndicator(view: UIView?) -> UIActivityIndicatorView? { if view != nil { let style: UIActivityIndicatorView.Style = AppFont.nightMode ? .white : .gray let progress = UIActivityIndicatorView(style: style) progress.frame = CGRect(x: 40, y: 40, width: 0, height: 0) view!.addSubview(progress) progress.startAnimating() return progress } else { return nil } } private func removeProgressIndicator(indicator: UIActivityIndicatorView?) { if indicator != nil { indicator!.stopAnimating() indicator!.removeFromSuperview() } } private func generateKey(reference: Reference) -> String { var result = [String]() var inItem = false for char: Character in reference.s3TextTemplate { if char == "%" { inItem = true } else if !inItem { result.append(String(char)) } else { inItem = false switch char { case "I": // Id is last part of s3KeyPrefix let parts = reference.s3TextPrefix.split(separator: "/") result.append(String(parts[parts.count - 1])) case "O": // ordinal 1 is GEN, 70 is MAT, not zero filled if let seq = bookMap[reference.bookId]?.seq { result.append(seq) } case "o": // 3 char ordinal A01 is GEN, zero filled if let seq3 = bookMap[reference.bookId]?.seq3 { result.append(seq3) } case "B": // USFM 3 char book code result.append(reference.bookId) case "b": // 2 char book code if let id2 = bookMap[reference.bookId]?.id2 { result.append(id2) } case "C": // chapter number, not zero filled if reference.chapter > 0 { result.append(String(reference.chapter)) } else { result.removeLast() // remove the underscore that would preceed chapter } case "d": // chapter number, 2 char zero filled, Psalms 3 char var chapStr = String(reference.chapter) if chapStr.count == 1 { chapStr = "0" + chapStr } if chapStr.count == 2 && reference.bookId == "PSA" { chapStr = "0" + chapStr } result.append(chapStr) default: print("ERROR: Unknown format char %\(char)") } } } return reference.s3TextPrefix + "/" + result.joined() } struct BookData { let seq: String let seq3: String let id2: String } let bookMap: [String: BookData] = [ "FRT": BookData(seq: "0", seq3: "?", id2: "?"), "GEN": BookData(seq: "2", seq3: "A01", id2: "GN"), "EXO": BookData(seq: "3", seq3: "A02", id2: "EX"), "LEV": BookData(seq: "4", seq3: "A03", id2: "LV"), "NUM": BookData(seq: "5", seq3: "A04", id2: "NU"), "DEU": BookData(seq: "6", seq3: "A05", id2: "DT"), "JOS": BookData(seq: "7", seq3: "A06", id2: "JS"), "JDG": BookData(seq: "8", seq3: "A07", id2: "JG"), "RUT": BookData(seq: "9", seq3: "A08", id2: "RT"), "1SA": BookData(seq: "10", seq3: "A09", id2: "S1"), "2SA": BookData(seq: "11", seq3: "A10", id2: "S2"), "1KI": BookData(seq: "12", seq3: "A11", id2: "K1"), "2KI": BookData(seq: "13", seq3: "A12", id2: "K2"), "1CH": BookData(seq: "14", seq3: "A13", id2: "R1"), "2CH": BookData(seq: "15", seq3: "A14", id2: "R2"), "EZR": BookData(seq: "16", seq3: "A15", id2: "ER"), "NEH": BookData(seq: "17", seq3: "A16", id2: "NH"), "EST": BookData(seq: "18", seq3: "A17", id2: "ET"), "JOB": BookData(seq: "19", seq3: "A18", id2: "JB"), "PSA": BookData(seq: "20", seq3: "A19", id2: "PS"), "PRO": BookData(seq: "21", seq3: "A20", id2: "PR"), "ECC": BookData(seq: "22", seq3: "A21", id2: "EC"), "SNG": BookData(seq: "23", seq3: "A22", id2: "SS"), "ISA": BookData(seq: "24", seq3: "A23", id2: "IS"), "JER": BookData(seq: "25", seq3: "A24", id2: "JR"), "LAM": BookData(seq: "26", seq3: "A25", id2: "LM"), "EZK": BookData(seq: "27", seq3: "A26", id2: "EK"), "DAN": BookData(seq: "28", seq3: "A27", id2: "DN"), "HOS": BookData(seq: "29", seq3: "A28", id2: "HS"), "JOL": BookData(seq: "30", seq3: "A29", id2: "JL"), "AMO": BookData(seq: "31", seq3: "A30", id2: "AM"), "OBA": BookData(seq: "32", seq3: "A31", id2: "OB"), "JON": BookData(seq: "33", seq3: "A32", id2: "JH"), "MIC": BookData(seq: "34", seq3: "A33", id2: "MC"), "NAM": BookData(seq: "35", seq3: "A34", id2: "NM"), "HAB": BookData(seq: "36", seq3: "A35", id2: "HK"), "ZEP": BookData(seq: "37", seq3: "A36", id2: "ZP"), "HAG": BookData(seq: "38", seq3: "A37", id2: "HG"), "ZEC": BookData(seq: "39", seq3: "A38", id2: "ZC"), "MAL": BookData(seq: "40", seq3: "A39", id2: "ML"), "TOB": BookData(seq: "41", seq3: "?", id2: "?"), "JDT": BookData(seq: "42", seq3: "?", id2: "?"), "ESG": BookData(seq: "43", seq3: "?", id2: "?"), "WIS": BookData(seq: "45", seq3: "?", id2: "?"), "SIR": BookData(seq: "46", seq3: "?", id2: "?"), "BAR": BookData(seq: "47", seq3: "?", id2: "?"), "LJE": BookData(seq: "48", seq3: "?", id2: "?"), "S3Y": BookData(seq: "49", seq3: "?", id2: "?"), "SUS": BookData(seq: "50", seq3: "?", id2: "?"), "BEL": BookData(seq: "51", seq3: "?", id2: "?"), "1MA": BookData(seq: "52", seq3: "?", id2: "?"), "2MA": BookData(seq: "53", seq3: "?", id2: "?"), "1ES": BookData(seq: "54", seq3: "?", id2: "?"), "MAN": BookData(seq: "55", seq3: "?", id2: "?"), "3MA": BookData(seq: "57", seq3: "?", id2: "?"), "4MA": BookData(seq: "59", seq3: "?", id2: "?"), "MAT": BookData(seq: "70", seq3: "B01", id2: "MT"), "MRK": BookData(seq: "71", seq3: "B02", id2: "MK"), "LUK": BookData(seq: "72", seq3: "B03", id2: "LK"), "JHN": BookData(seq: "73", seq3: "B04", id2: "JN"), "ACT": BookData(seq: "74", seq3: "B05", id2: "AC"), "ROM": BookData(seq: "75", seq3: "B06", id2: "RM"), "1CO": BookData(seq: "76", seq3: "B07", id2: "C1"), "2CO": BookData(seq: "77", seq3: "B08", id2: "C2"), "GAL": BookData(seq: "78", seq3: "B09", id2: "GL"), "EPH": BookData(seq: "79", seq3: "B10", id2: "EP"), "PHP": BookData(seq: "80", seq3: "B11", id2: "PP"), "COL": BookData(seq: "81", seq3: "B12", id2: "CL"), "1TH": BookData(seq: "82", seq3: "B13", id2: "H1"), "2TH": BookData(seq: "83", seq3: "B14", id2: "H2"), "1TI": BookData(seq: "84", seq3: "B15", id2: "T1"), "2TI": BookData(seq: "85", seq3: "B16", id2: "T2"), "TIT": BookData(seq: "86", seq3: "B17", id2: "TT"), "PHM": BookData(seq: "87", seq3: "B18", id2: "PM"), "HEB": BookData(seq: "88", seq3: "B19", id2: "HB"), "JAS": BookData(seq: "89", seq3: "B20", id2: "JM"), "1PE": BookData(seq: "90", seq3: "B21", id2: "P1"), "2PE": BookData(seq: "91", seq3: "B22", id2: "P2"), "1JN": BookData(seq: "92", seq3: "B23", id2: "J1"), "2JN": BookData(seq: "93", seq3: "B24", id2: "J2"), "3JN": BookData(seq: "94", seq3: "B25", id2: "J3"), "JUD": BookData(seq: "95", seq3: "B26", id2: "JD"), "REV": BookData(seq: "96", seq3: "B27", id2: "RV"), "BAK": BookData(seq: "97", seq3: "?", id2: "?"), "GLO": BookData(seq: "106", seq3: "?", id2: "?") ] }
mit
8b67847252f463900986c4adbc6641b7
45.902527
117
0.504233
3.382452
false
false
false
false
XLabKC/Badger
Badger/Badger/ProfileCircle.swift
1
3657
import UIKit import Haneke class ProfileCircle: UIView { var status = UserStatus.Unknown var user: User? var team: Team? var userObserver: FirebaseObserver<User>? var teamObserver: FirebaseObserver<Team>? var circle: UIImageView var teamCircle: TeamCircle? required init(coder aDecoder: NSCoder) { self.circle = UIImageView() super.init(coder: aDecoder) self.backgroundColor = UIColor.clearColor() let height = self.frame.height self.circle.frame = CGRect(x: 0, y: 0, width: height, height: height) self.circle.clipsToBounds = true self.circle.layer.borderColor = Colors.UnknownStatus.CGColor self.circle.autoresizingMask = UIViewAutoresizing.allZeros self.addSubview(circle) self.layoutView() } deinit { self.dispose() } override func layoutSubviews() { super.layoutSubviews() self.layoutView() } func setUid(uid: String) { if let old = self.user { if old.uid == uid { // Already setup. return } else { self.dispose() } } let ref = User.createRef(uid) self.userObserver = FirebaseObserver<User>(query: ref, withBlock: self.userUpdated) } func setTeamId(id: String) { if let old = self.team { if old.id == id { // Already setup. return } else { self.dispose() } } let ref = Team.createRef(id) self.teamObserver = FirebaseObserver<Team>(query: ref, withBlock: self.teamUpdated) } func userUpdated(newUser: User) { self.user = newUser let placeholder = UIImage(named: "DefaultUserProfile") let imagePath = newUser.profileImages[newUser.status] if imagePath != nil && imagePath != "" { let url = Helpers.getProfileImageUrl(imagePath!) self.circle.hnk_setImageFromURL(url, placeholder: placeholder, format: nil, failure: nil, success: nil) } else { self.circle.image = placeholder } self.circle.layer.borderColor = Helpers.statusToColor(newUser.status).CGColor } func teamUpdated(newTeam: Team) { self.team = newTeam self.getTeamCircle().setTeam(newTeam) } private func layoutView() { self.circle.layer.cornerRadius = self.frame.height / 2.0 if self.circle.frame.height > 80 { self.circle.layer.borderWidth = 4.0 } else if self.circle.frame.height > 60 { self.circle.layer.borderWidth = 3.0 } else { self.circle.layer.borderWidth = 2.0 } if let teamCircle = self.teamCircle { teamCircle.frame = self.createTeamCircleFrame() } } private func dispose() { if let observer = self.userObserver { observer.dispose() } if let observer = self.teamObserver { observer.dispose() } } private func getTeamCircle() -> TeamCircle { if let teamCircle = self.teamCircle { return teamCircle } let circle = TeamCircle(frame: self.createTeamCircleFrame()) self.addSubview(circle) return circle } private func createTeamCircleFrame() -> CGRect { let diameter = self.circle.frame.width / 2.0 let offset = diameter * 0.20 let x = -offset let y = self.circle.frame.height - diameter + offset return CGRect(x: x, y: y, width: diameter, height: diameter) } }
gpl-2.0
cdcbe765827f6bf23e76cbad6ffcaa43
29.22314
115
0.584359
4.400722
false
false
false
false
squaremeals/squaremeals-ios-app
SquareMeals/View/MealViewController.swift
1
2391
// // MealViewController.swift // SquareMeals // // Created by Zachary Shakked on 11/16/17. // Copyright © 2017 Shakd, LLC. All rights reserved. // import UIKit public protocol MealViewControllerDelegate:class { func mealViewControllerDidLoad(controller: MealViewController) func profileButtonPressed(controller: MealViewController) } public final class MealViewController: UIViewController { public let meal: Meal public weak var delegate: MealViewControllerDelegate? public init(meal: Meal) { self.meal = meal super.init(nibName: "MealViewController", bundle: Bundle.main) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var coverImageView: UIImageView! @IBOutlet fileprivate weak var caloriesLabel: UILabel! @IBOutlet fileprivate weak var proteinLabel: UILabel! @IBOutlet fileprivate weak var carbsLabel: UILabel! @IBOutlet fileprivate weak var fatsLabel: UILabel! @IBOutlet fileprivate weak var dateLabel: UILabel! @IBOutlet fileprivate weak var mealTitle: UILabel! @IBOutlet fileprivate weak var profileButton: UIButton! @IBOutlet fileprivate weak var descriptionLabel: UILabel! @IBOutlet fileprivate weak var ingredientsLabel: UILabel! @IBAction func profileButtonPressed(_ sender: Any) { delegate?.profileButtonPressed(controller: self) } override public func viewDidLoad() { super.viewDidLoad() titleLabel.text = meal.name.capitalized coverImageView.image = meal.coverImage caloriesLabel.text = String(format: "%.0f", meal.calories) carbsLabel.text = String(format: "%.0f", meal.carbohydrates) fatsLabel.text = String(format: "%.0f", meal.fats) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateLabel.text = "Today, \(dateFormatter.string(from: Date()))" descriptionLabel.text = meal.description ingredientsLabel.text = meal.ingredients } @IBAction func cancelButtonPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
15b22a98307168c9d3928c3cbdbc6b8b
33.637681
71
0.699582
4.94824
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/SBAExternalIDOptions.swift
1
3503
// // SBAExternalIDOptions.swift // ResearchUXFactory // // Copyright © 2017 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation /** Object with the options for the external ID form item `ORKAnswerFormat` */ public struct SBAExternalIDOptions { /** By default, the autocapitalization type is all characters */ public static let defaultAutocapitalizationType: UITextAutocapitalizationType = .allCharacters /** By default, the keyboard type is ASCII */ public static let defaultKeyboardType: UIKeyboardType = .asciiCapable /** Auto-capitalization type for the text field */ public let autocapitalizationType: UITextAutocapitalizationType /** Keyboard type for the text field */ public let keyboardType: UIKeyboardType public init() { self.autocapitalizationType = SBAExternalIDOptions.defaultAutocapitalizationType self.keyboardType = SBAExternalIDOptions.defaultKeyboardType } public init(autocapitalizationType: UITextAutocapitalizationType, keyboardType: UIKeyboardType) { self.autocapitalizationType = autocapitalizationType self.keyboardType = keyboardType } public init(options: [String : AnyObject]?) { self.autocapitalizationType = { if let autocap = options?["autocapitalizationType"] as? String { return UITextAutocapitalizationType(key: autocap) } else { return SBAExternalIDOptions.defaultAutocapitalizationType } }() self.keyboardType = { if let keyboard = options?["keyboardType"] as? String { return UIKeyboardType(key: keyboard) } else { return SBAExternalIDOptions.defaultKeyboardType } }() } }
bsd-3-clause
17c238fab586e0f6e9af39b50e42bd87
38.348315
101
0.710737
5.514961
false
false
false
false
DarthMike/YapDatabaseExtensions
framework/YapDatabaseExtensions/Common/Write.swift
1
39326
// // Created by Daniel Thorpe on 22/04/2015. // // import YapDatabase // MARK: - YapDatabaseTransaction extension YapDatabaseReadWriteTransaction { func writeAtIndex(index: YapDB.Index, object: AnyObject, metadata: AnyObject? = .None) { if let metadata: AnyObject = metadata { setObject(object, forKey: index.key, inCollection: index.collection, withMetadata: metadata) } else { setObject(object, forKey: index.key, inCollection: index.collection) } } } extension YapDatabaseReadWriteTransaction { /** Writes a Persistable object conforming to NSCoding to the database inside the read write transaction. :param: object An Object. :returns: The Object. */ public func write<Object where Object: NSCoding, Object: Persistable>(object: Object) -> Object { writeAtIndex(indexForPersistable(object), object: object) return object } /** Writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: object An ObjectWithObjectMetadata. :returns: The ObjectWithObjectMetadata. */ public func write<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> ObjectWithObjectMetadata { writeAtIndex(indexForPersistable(object), object: object, metadata: object.metadata) return object } /** Writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: object An ObjectWithValueMetadata. :returns: The ObjectWithValueMetadata. */ public func write<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable, ObjectWithValueMetadata.MetadataType.ArchiverType.ValueType == ObjectWithValueMetadata.MetadataType>(object: ObjectWithValueMetadata) -> ObjectWithValueMetadata { writeAtIndex(indexForPersistable(object), object: object, metadata: ObjectWithValueMetadata.MetadataType.ArchiverType(object.metadata)) return object } /** Writes a Persistable value, conforming to Saveable to the database inside the read write transaction. :param: value A Value. :returns: The Value. */ public func write<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value) -> Value { writeAtIndex(indexForPersistable(value), object: Value.ArchiverType(value)) return value } /** Writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: value A ValueWithValueMetadata. :returns: The ValueWithValueMetadata. */ public func write<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> ValueWithValueMetadata { writeAtIndex(indexForPersistable(value), object: ValueWithValueMetadata.ArchiverType(value), metadata: ValueWithValueMetadata.MetadataType.ArchiverType(value.metadata)) return value } /** Writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: value A ValueWithObjectMetadata. :returns: The ValueWithObjectMetadata. */ public func write<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> ValueWithObjectMetadata { writeAtIndex(indexForPersistable(value), object: ValueWithObjectMetadata.ArchiverType(value), metadata: value.metadata) return value } } extension YapDatabaseReadWriteTransaction { /** Writes a sequence of Persistable Object instances conforming to NSCoding to the database inside the read write transaction. :param: objects A SequenceType of Object instances. :returns: An array of Object instances. */ public func write<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects) -> [Object] { return map(objects, write) } /** Writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithObjectMetadata instances. :returns: An array of ObjectWithObjectMetadata instances. */ public func write<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> [ObjectWithObjectMetadata] { return map(objects, write) } /** Writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithValueMetadata instances. :returns: An array of ObjectWithValueMetadata instances. */ public func write<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> [ObjectWithValueMetadata] { return map(objects, write) } /** Writes a sequence of Persistable Value instances conforming to Saveable to the database inside the read write transaction. :param: objects A SequenceType of Value instances. :returns: An array of Value instances. */ public func write<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values) -> [Value] { return map(values, write) } /** Writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithValueMetadata instances. :returns: An array of ValueWithValueMetadata instances. */ public func write<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(values: Values) -> [ValueWithValueMetadata] { return map(values, write) } /** Writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithObjectMetadata instances. :returns: An array of ValueWithObjectMetadata instances. */ public func write<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> [ValueWithObjectMetadata] { return map(values, write) } } // MARK: - YapDatabaseConnection extension YapDatabaseConnection { /** Synchonously writes a Persistable object conforming to NSCoding to the database using the connection. :param: object An Object. :returns: The Object. */ public func write<Object where Object: NSCoding, Object: Persistable>(object: Object) -> Object { return write { $0.write(object) } } /** Synchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: object An ObjectWithObjectMetadata. :returns: The ObjectWithObjectMetadata. */ public func write<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> ObjectWithObjectMetadata { return write { $0.write(object) } } /** Synchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: object An ObjectWithValueMetadata. :returns: The ObjectWithValueMetadata. */ public func write<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata) -> ObjectWithValueMetadata { return write { $0.write(object) } } /** Synchonously writes a Persistable value conforming to Saveable to the database using the connection. :param: value A Value. :returns: The Value. */ public func write<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value) -> Value { return write { $0.write(value) } } /** Synchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: value A ValueWithValueMetadata. :returns: The ValueWithValueMetadata. */ public func write<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> ValueWithValueMetadata { return write { $0.write(value) } } /** Synchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: value A ValueWithObjectMetadata. :returns: The ValueWithObjectMetadata. */ public func write<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> ValueWithObjectMetadata { return write { $0.write(value) } } } extension YapDatabaseConnection { /** Asynchonously writes a Persistable object conforming to NSCoding to the database using the connection. :param: object An Object. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the Object. */ public func asyncWrite<Object where Object: NSCoding, Object: Persistable>(object: Object, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object) -> Void) { asyncWrite({ $0.write(object) }, queue: queue, completion: completion) } /** Asynchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: object An ObjectWithObjectMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ObjectWithObjectMetadata. */ public func asyncWrite<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithObjectMetadata) -> Void) { asyncWrite({ $0.write(object) }, queue: queue, completion: completion) } /** Asynchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: object An ObjectWithValueMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ObjectWithValueMetadata. */ public func asyncWrite<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithValueMetadata) -> Void) { asyncWrite({ $0.write(object) }, queue: queue, completion: completion) } /** Asynchonously writes a Persistable value conforming to Saveable to the database using the connection. :param: value A Value. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the Value. */ public func asyncWrite<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value) -> Void) { asyncWrite({ $0.write(value) }, queue: queue, completion: completion) } /** Asynchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: value An ValueWithValueMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ValueWithValueMetadata. */ public func asyncWrite<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithValueMetadata) -> Void) { asyncWrite({ $0.write(value) }, queue: queue, completion: completion) } /** Asynchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: value An ValueWithObjectMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ValueWithObjectMetadata. */ public func asyncWrite<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithObjectMetadata) -> Void) { asyncWrite({ $0.write(value) }, queue: queue, completion: completion) } } extension YapDatabaseConnection { /** Synchonously writes Persistable objects conforming to NSCoding to the database using the connection. :param: objects A SequenceType of Object instances. :returns: An array of Object instances. */ public func write<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects) -> [Object] { return write { $0.write(objects) } } /** Synchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithObjectMetadata instances. :returns: An array of ObjectWithObjectMetadata instances. */ public func write<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> [ObjectWithObjectMetadata] { return write { $0.write(objects) } } /** Synchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithValueMetadata instances. :returns: An array of ObjectWithValueMetadata instances. */ public func write<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> [ObjectWithValueMetadata] { return write { $0.write(objects) } } /** Synchonously writes Persistable values conforming to Saveable to the database using the connection. :param: values A SequenceType of Value instances. :returns: An array of Object instances. */ public func write<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values) -> [Value] { return write { $0.write(values) } } /** Synchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithValueMetadata instances. :returns: An array of ValueWithValueMetadata instances. */ public func write<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(values: Values) -> [ValueWithValueMetadata] { return write { $0.write(values) } } /** Synchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithObjectMetadata instances. :returns: An array of ValueWithObjectMetadata instances. */ public func write<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> [ValueWithObjectMetadata] { return write { $0.write(values) } } } extension YapDatabaseConnection { /** Asynchonously writes Persistable objects conforming to NSCoding to the database using the connection. :param: objects A SequenceType of Object instances. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Object instances. */ public func asyncWrite<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { asyncWrite({ $0.write(objects) }, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithObjectMetadata instances. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of ObjectWithObjectMetadata instances. */ public func asyncWrite<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithObjectMetadata]) -> Void) { asyncWrite({ $0.write(objects) }, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithValueMetadata instances. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of ObjectWithValueMetadata instances. */ public func asyncWrite<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithValueMetadata]) -> Void) { asyncWrite({ $0.write(objects) }, queue: queue, completion: completion) } /** Asynchonously writes Persistable values conforming to Saveable to the database using the connection. :param: values A SequenceType of Value instances. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Value instances. */ public func asyncWrite<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { asyncWrite({ $0.write(values) }, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithObjectMetadata instances. :returns: An array of ValueWithObjectMetadata instances. */ public func asyncWrite<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithObjectMetadata]) -> Void) { asyncWrite({ $0.write(values) }, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithValueMetadata instances. :returns: An array of ValueWithValueMetadata instances. */ public func asyncWrite<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithValueMetadata]) -> Void) { asyncWrite({ $0.write(values) }, queue: queue, completion: completion) } } // MARK: - YapDatabase extension YapDatabase { /** Synchonously writes a Persistable object conforming to NSCoding to the database using a new connection. :param: object An Object. :returns: The Object. */ public func write<Object where Object: NSCoding, Object: Persistable>(object: Object) -> Object { return newConnection().write(object) } /** Synchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: object An ObjectWithObjectMetadata. :returns: The ObjectWithObjectMetadata. */ public func write<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> ObjectWithObjectMetadata { return newConnection().write(object) } /** Synchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: object An ObjectWithValueMetadata. :returns: The ObjectWithValueMetadata. */ public func write<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata) -> ObjectWithValueMetadata { return newConnection().write(object) } /** Synchonously writes a Persistable value conforming to Saveable to the database using a new connection. :param: value A Value. :returns: The Value. */ public func write<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value) -> Value { return newConnection().write(value) } /** Synchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: value A ValueWithValueMetadata. :returns: The ValueWithValueMetadata. */ public func write<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> ValueWithValueMetadata { return newConnection().write(value) } /** Synchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: value A ValueWithObjectMetadata. :returns: The ValueWithObjectMetadata. */ public func write<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> ValueWithObjectMetadata { return newConnection().write(value) } } extension YapDatabase { /** Asynchonously writes a Persistable object conforming to NSCoding to the database using a new connection. :param: object An Object. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the Object. */ public func asyncWrite<Object where Object: NSCoding, Object: Persistable>(object: Object, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object) -> Void) { newConnection().asyncWrite(object, queue: queue, completion: completion) } /** Asynchonously writes a Persistable object with metadata, both conforming to NSCoding to the database using a new connection. :param: object An ObjectWithObjectMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ObjectWithObjectMetadata. */ public func asyncWrite<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithObjectMetadata) -> Void) { newConnection().asyncWrite(object, queue: queue, completion: completion) } /** Asynchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database using a new connection. :param: object An ObjectWithValueMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ObjectWithValueMetadata. */ public func asyncWrite<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithValueMetadata) -> Void) { newConnection().asyncWrite(object, queue: queue, completion: completion) } /** Asynchonously writes a Persistable value conforming to Saveable to the database using a new connection. :param: value A Value. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the Value. */ public func asyncWrite<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value) -> Void) { newConnection().asyncWrite(value, queue: queue, completion: completion) } /** Asynchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database using a new connection. :param: object An ValueWithValueMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ValueWithValueMetadata. */ public func asyncWrite<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithValueMetadata) -> Void) { newConnection().asyncWrite(value, queue: queue, completion: completion) } /** Asynchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database using a new connection. :param: object An ValueWithObjectMetadata. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives the ValueWithObjectMetadata. */ public func asyncWrite<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithObjectMetadata) -> Void) { newConnection().asyncWrite(value, queue: queue, completion: completion) } } extension YapDatabase { /** Synchonously writes Persistable objects conforming to NSCoding to the database using a new connection. :param: objects A SequenceType of Object instances. :returns: An array of Object instances. */ public func write<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects) -> [Object] { return newConnection().write(objects) } /** Synchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithObjectMetadata instances. :returns: An array of ObjectWithObjectMetadata instances. */ public func write<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> [ObjectWithObjectMetadata] { return newConnection().write(objects) } /** Synchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithValueMetadata instances. :returns: An array of ObjectWithValueMetadata instances. */ public func write<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> [ObjectWithValueMetadata] { return newConnection().write(objects) } /** Synchonously writes Persistable values conforming to Saveable to the database using a new connection. :param: values A SequenceType of Value instances. :returns: An array of Object instances. */ public func write<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values) -> [Value] { return newConnection().write(values) } /** Synchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithValueMetadata instances. :returns: An array of ValueWithValueMetadata instances. */ public func write<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(values: Values) -> [ValueWithValueMetadata] { return newConnection().write(values) } /** Synchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithObjectMetadata instances. :returns: An array of ValueWithObjectMetadata instances. */ public func write<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> [ValueWithObjectMetadata] { return newConnection().write(values) } } extension YapDatabase { /** Asynchonously writes Persistable objects conforming to NSCoding to the database using a new connection. :param: values A SequenceType of Object instances. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Object instances. */ public func asyncWrite<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { newConnection().asyncWrite(objects, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithObjectMetadata instances. :returns: An array of ObjectWithObjectMetadata instances. */ public func asyncWrite<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithObjectMetadata]) -> Void) { newConnection().asyncWrite(objects, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction. :param: objects A SequenceType of ObjectWithValueMetadata instances. :returns: An array of ObjectWithValueMetadata instances. */ public func asyncWrite<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithValueMetadata]) -> Void) { newConnection().asyncWrite(objects, queue: queue, completion: completion) } /** Asynchonously writes Persistable values conforming to Saveable to the database using a new connection. :param: values A SequenceType of Value instances. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Value instances. */ public func asyncWrite<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { newConnection().asyncWrite(values, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithValueMetadata instances. :returns: An array of ValueWithValueMetadata instances. */ public func asyncWrite<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithValueMetadata]) -> Void) { newConnection().asyncWrite(values, queue: queue, completion: completion) } /** Asynchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction. :param: objects A SequenceType of ValueWithObjectMetadata instances. :returns: An array of ValueWithObjectMetadata instances. */ public func asyncWrite<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithObjectMetadata]) -> Void) { newConnection().asyncWrite(values, queue: queue, completion: completion) } }
mit
35fb0288273c67ad6ddc2957892ea816
56.076923
512
0.764227
4.893728
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Elements/Match/Breakdown/MatchBreakdownConfigurator2020.swift
1
11326
import Foundation import UIKit private class BreakdownStyle2020 { public static let bottomImage = UIImage(systemName: "rectangle") public static let outerImage = UIImage(systemName: "hexagon") public static let innerImage = UIImage(systemName: "circle") } struct MatchBreakdownConfigurator2020: MatchBreakdownConfigurator { static func configureDataSource(_ snapshot: inout NSDiffableDataSourceSnapshot<String?, BreakdownRow>, _ breakdown: [String: Any]?, _ red: [String: Any]?, _ blue: [String: Any]?) { var rows: [BreakdownRow?] = [] // Auto rows.append(initLine(red: red, blue: blue)) rows.append(powerCellRow(title: "Auto Power Cells", period: "auto", red: red, blue: blue)) rows.append(row(title: "Auto Power Cell Points", key: "autoCellPoints", red: red, blue: blue, type: .subtotal)) rows.append(row(title: "Total Auto", key: "autoPoints", red: red, blue: blue, type: .total)) // Teleop rows.append(powerCellRow(title: "Teleop Power Cells", period: "teleop", red: red, blue: blue)) rows.append(row(title: "Teleop Power Cell Points", key: "teleopCellPoints", red: red, blue: blue, type: .subtotal)) rows.append(row(title: "Control Panel Points", key: "controlPanelPoints", red: red, blue: blue, type: .subtotal)) for i in [1, 2, 3] { rows.append(endgameRow(i: i, red: red, blue: blue)) } rows.append(shieldSwitchLevelRow(title: "Shield Generator Switch Level", red: red, blue: blue)) rows.append(row(title: "Endgame Points", key: "endgamePoints", red: red, blue: blue, type: .subtotal)) rows.append(row(title: "Total Teleop", key: "teleopPoints", red: red, blue: blue, type: .total)) rows.append(stageActivationRow(title: "Stage Activations", red: red, blue: blue)) rows.append(shieldOperationalRow(title: "Shield Generator Operational", red: red, blue: blue)) // Match totals rows.append(foulRow(title: "Fouls / Tech Fouls", red: red, blue: blue)) rows.append(row(title: "Adjustments", key: "adjustPoints", red: red, blue: blue)) rows.append(row(title: "Total Score", key: "totalPoints", red: red, blue: blue, type: .total)) // RP rows.append(row(title: "Ranking Points", key: "rp", formatString: "+%@ RP", red: red, blue: blue)) // Clean up any empty rows let validRows = rows.compactMap({ $0 }) if !validRows.isEmpty { snapshot.appendSections([nil]) snapshot.appendItems(validRows) } } private static func initLine(red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { var redLineStrings: [String] = [] var blueLineStrings: [String] = [] for i in [1, 2, 3] { guard let initValues = values(key: "initLineRobot\(i)", red: red, blue: blue) else { return nil } let (rv, bv) = initValues guard let redInit = rv as? String, let blueInit = bv as? String else { return nil } redLineStrings.append(redInit) blueLineStrings.append(blueInit) } let mode = UIView.ContentMode.scaleAspectFit let elements = [redLineStrings, blueLineStrings].map { (lineStrings) -> [AnyHashable] in return lineStrings.map { (line) -> AnyHashable in switch line { case "None": return BreakdownStyle.imageView(image: BreakdownStyle.xImage, contentMode: mode, forceSquare: false) case "Exited": return BreakdownStyle.imageView(image: BreakdownStyle.checkImage, contentMode: mode, forceSquare: false) default: return "?" } } } let (redElements, blueElements) = (elements[0], elements[1]) guard let redBreakdownElements = redElements as? [BreakdownElement], let blueBreakdownElements = blueElements as? [BreakdownElement] else { return nil } let redStackView = UIStackView(arrangedSubviews: redBreakdownElements.map { $0.toView() }) redStackView.distribution = .fillEqually let blueStackView = UIStackView(arrangedSubviews: blueBreakdownElements.map { $0.toView() }) blueStackView.distribution = .fillEqually // Add the point totals for the init line guard let initLinePoints = values(key: "autoInitLinePoints", red: red, blue: blue) else { return nil } let (redLinePoints, blueLinePoints) = initLinePoints let redLinePointsString = "(+\(redLinePoints ?? 0))" let blueLinePointsString = "(+\(blueLinePoints ?? 0))" return BreakdownRow(title: "Initiation Line exited", red: [redStackView, redLinePointsString], blue: [blueStackView, blueLinePointsString]) } private static func powerCellRow(title: String, period: String, red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { let keys = ["CellsBottom", "CellsOuter", "CellsInner"] let images = [BreakdownStyle2020.bottomImage, BreakdownStyle2020.outerImage, BreakdownStyle2020.innerImage] let locations = keys.map { "\(period)\($0)" } var redCells: [Int] = [] var blueCells: [Int] = [] for location in locations { guard let cellValues = values(key: location, red: red, blue: blue) else { return nil } let (rv, bv) = cellValues guard let redCellValue = rv as? Int, let blueCellValue = bv as? Int else { return nil } redCells.append(redCellValue) blueCells.append(blueCellValue) } let mode = UIView.ContentMode.scaleAspectFit let redValues = zip((images).map { return BreakdownStyle.imageView(image: $0, contentMode: mode) }, redCells).flatMap { (imgV: UIImageView, v: Int) -> [AnyHashable?] in [imgV, String(v) ] } let blueValues = zip((images).map { return BreakdownStyle.imageView(image: $0, contentMode: mode) }, blueCells).flatMap { (imgV: UIImageView, v: Int) -> [AnyHashable?] in [imgV, String(v) ] } return BreakdownRow(title: title, red: redValues, blue: blueValues) } private static func endgameRow(i: Int, red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { guard let endgameValues = values(key: "endgameRobot\(i)", red: red, blue: blue) else { return nil } let (rw, bw) = endgameValues guard let redEndgame = rw as? String, let blueEndgame = bw as? String else { return nil } let elements = [redEndgame, blueEndgame].map { (endgame) -> AnyHashable in if endgame == "Park" { return "Park (+5)" } else if endgame == "Hang" { return "Hang (+25)" } return BreakdownStyle.xImage } return BreakdownRow(title: "Robot \(i) Endgame", red: [elements.first], blue: [elements.last]) } private static func foulRow(title: String, red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { guard let foulValues = values(key: "foulCount", red: red, blue: blue) else { return nil } let (rf, bf) = foulValues guard let redFouls = rf as? Int, let blueFouls = bf as? Int else { return nil } guard let techFoulValues = values(key: "techFoulCount", red: red, blue: blue) else { return nil } let (rtf, btf) = techFoulValues guard let redTechFouls = rtf as? Int, let blueTechFouls = btf as? Int else { return nil } // NOTE: red and blue are passed in backwards here intentionally, because // the fouls returned are what the opposite alliance received let elements = [(blueFouls, blueTechFouls), (redFouls, redTechFouls)].map { (fouls, techFouls) -> AnyHashable in return "+\(fouls * 3) / +\(techFouls * 15)" } return BreakdownRow(title: title, red: [elements.first], blue: [elements.last]) } private static func shieldSwitchLevelRow(title: String, red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { guard let endgameIsLevelValues = values(key: "endgameRungIsLevel", red: red, blue: blue) else { return nil } let (rw, bw) = endgameIsLevelValues guard let redEndgame = rw as? String, let blueEndgame = bw as? String else { return nil } let elements = [redEndgame, blueEndgame].map { (endgame) -> [AnyHashable] in let mode = UIView.ContentMode.center if endgame == "IsLevel" { let result: [AnyHashable] = [BreakdownStyle.imageView(image: BreakdownStyle.checkImage, contentMode: mode), "(+15)"] return result } let result: [AnyHashable] = [BreakdownStyle.imageView(image: BreakdownStyle.xImage, contentMode: mode)] return result } return BreakdownRow(title: title, red: elements.first ?? [], blue: elements.last ?? []) } private static func shieldOperationalRow(title: String, red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { guard let shieldOperationalValues = values(key: "shieldOperationalRankingPoint", red: red, blue: blue) else { return nil } let (rw, bw) = shieldOperationalValues guard let redShieldOperational = rw as? Int, let blueShieldOperational = bw as? Int else { return nil } let elements = [redShieldOperational, blueShieldOperational].map { (shieldOperational) -> [AnyHashable] in if shieldOperational == 1 { let result: [AnyHashable] = [BreakdownStyle.imageView(image: BreakdownStyle.checkImage), "(+1 RP)"] return result } let result: [AnyHashable] = [BreakdownStyle.imageView(image: BreakdownStyle.xImage)] return result } return BreakdownRow(title: title, red: elements.first ?? [], blue: elements.last ?? []) } private static func stageActivationRow(title: String, red: [String: Any]?, blue: [String: Any]?) -> BreakdownRow? { var redActivation: [Int] = []; var blueActivation: [Int] = []; for i in [3, 2, 1] { guard let stageActivatedValues = values(key: "stage\(i)Activated", red: red, blue: blue) else { return nil } let (rw, bw) = stageActivatedValues guard let redStage = rw as? Int, let blueStage = bw as? Int else { return nil } redActivation.append(redStage); blueActivation.append(blueStage); } let elements = [redActivation, blueActivation].map { (stage) -> String in if stage[0] == 1 { return "3 (+1 RP)" } else if stage[1] == 1 { return "2" } else if stage[2] == 1 { return "1" } return "" } return BreakdownRow(title: title, red: [elements.first], blue: [elements.last]) } }
mit
99ffc74727c892f4236ea12a335907ec
43.766798
184
0.595974
4.033476
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/UI/Views/Progress Indicators/CircleProgressView.swift
1
3353
// // CircleProgressView.swift // YourGoals // // Created by André Claaßen on 01.08.19. // Copyright © 2019 André Claaßen. All rights reserved. // import Foundation import UIKit /// a view with a circle which displays a little of progress @IBDesignable class CircleProgressView:UIView { /// the progress between 0.0 and 1.0 @IBInspectable var progress:CGFloat = 0.3 { willSet(newProgress) { assert(newProgress >= 0.0 && newProgress <= 1.0) } didSet { self.circle.strokeEnd = progress } } /// the line width of the circlefeiw @IBInspectable var lineWidth:CGFloat = 2.0 { didSet { self.circle.lineWidth = self.lineWidth self.circleBackground.lineWidth = self.lineWidth } } @IBInspectable var strokeColor = UIColor.green { didSet { self.circle.strokeColor = self.strokeColor.cgColor } } @IBInspectable var backgroundStrokeShadowColor = UIColor.lightGray { didSet { self.circleBackground.strokeColor = self.strokeColor.cgColor } } @IBInspectable var backgroundCircleColor = UIColor.clear { didSet { self.circleBackground.fillColor = self.backgroundCircleColor.cgColor } } var circle:CAShapeLayer! var circleBackground:CAShapeLayer! override init(frame: CGRect) { super.init(frame: frame) setupDefaults() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupDefaults() } func createCirclePath() -> CGPath { let startAngle:CGFloat = degreesToRadians(angle: -90.0) let endAngle:CGFloat = degreesToRadians(angle: -90.01) let radius = self.frame.height / 2.0 - lineWidth / 2.0 let centerPoint = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.height / 2.0) let circlePath = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) return circlePath.cgPath } /// create two circles with inner and outer progress func setupCircleProgressLayers() { let circlePath = createCirclePath() circle = CAShapeLayer() circle.path = circlePath circle.lineCap = .round circle.fillColor = UIColor.clear.cgColor circle.lineWidth = lineWidth circle.strokeColor = self.strokeColor.cgColor circle.zPosition = 1 circle.strokeEnd = self.progress self.layer.addSublayer(circle) circleBackground = CAShapeLayer() circleBackground.path = circlePath circleBackground.lineCap = .round circleBackground.fillColor = self.backgroundCircleColor.cgColor circleBackground.lineWidth = lineWidth circleBackground.strokeColor = self.backgroundStrokeShadowColor.cgColor circleBackground.strokeEnd = 1.0 circleBackground.zPosition = -1 self.layer.addSublayer(circleBackground) } override func layoutSubviews() { let circlePath = self.createCirclePath() self.circle.path = circlePath self.circleBackground.path = circlePath } func setupDefaults() { setupCircleProgressLayers() } }
lgpl-3.0
c8a2ad61a471b3482a67be448ef7a548
29.715596
138
0.640382
4.880466
false
false
false
false
kronik/swift4fun
LeaveList/Playground.playground/Contents.swift
2
8835
import UIKit import Foundation import CoreLocation import MapKit import XCPlayground /* * K-Mean clustering algorithm * Wikipedia: https://en.wikipedia.org/wiki/K-means_clustering * and some visualisation http://util.io/k-means */ // Centroid data structure struct Centroid { var center: CLLocation // Center of this centroid var points: [CLLocation] // Points near this centroid } // K-Mean clustering initial K centroids definition and distribution func initializeCentroids(locations: [CLLocation], maxDistance: CLLocationDistance) -> [Centroid] { var centroids = [Centroid]() // Find a location far enough from all previous centroids and add it into a list of centroids for location in locations { var foundCentroid = false for centroid in centroids { let distance = centroid.center.distanceFromLocation(location) if distance <= maxDistance { foundCentroid = true break } } if !foundCentroid { centroids.append(Centroid(center: location, points: [CLLocation]())) } } return centroids } // K-Mean clustering implementation func clusterLocations(locations: [CLLocation], maxDistance: CLLocationDistance) -> [Centroid] { var centroids = initializeCentroids(locations, maxDistance: maxDistance) var centerMoveDist: CLLocationDistance = 0.0 repeat { var newCentroids = [Centroid]() // Clone old centroid list into new centroid list for centroid in centroids { newCentroids.append(Centroid(center: centroid.center, points: [CLLocation]())) } // For each location find nearest centroid and associate location with this centroid for location in locations { for i in 0..<newCentroids.count { let distance = newCentroids[i].center.distanceFromLocation(location) if distance < maxDistance { newCentroids[i].points.append(location) break } } } // Adjust centroid centers based on nearest locations associated with this centroid for i in 0..<newCentroids.count { newCentroids[i].center = CLLocation.centroidForLocations(newCentroids[i].points) } centerMoveDist = 0 // Calculate distance from old centroid locations and new centroid locations for i in 0..<newCentroids.count { centerMoveDist = newCentroids[i].center.distanceFromLocation(centroids[i].center) if centerMoveDist > maxDistance { break } } // Update current centroid list centroids = newCentroids } while centerMoveDist > maxDistance // Check if distance difference small enough to stop return centroids } extension CLLocation { class func centroidForLocations(locations: [CLLocation]) -> CLLocation { var latitude: CLLocationDegrees = 0 var longitude: CLLocationDegrees = 0 for location in locations { let coordinate = location.coordinate latitude += coordinate.latitude; longitude += coordinate.longitude } return CLLocation(latitude: latitude / CLLocationDistance(locations.count), longitude: longitude / CLLocationDistance(locations.count)) } func locationWithBearing(bearing:Double, distance:CLLocationDistance) -> CLLocation { let earthRadius = 6372797.6 // earth radius in meters let distRadians = distance / earthRadius let origin = self.coordinate let lat1 = origin.latitude * M_PI / 180 let lon1 = origin.longitude * M_PI / 180 let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearing)) let lon2 = lon1 + atan2(sin(bearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2)) return CLLocation(latitude: lat2 * 180 / M_PI, longitude: lon2 * 180 / M_PI) } } class ColoredAnnotation: MKPointAnnotation { private var pinColor: UIColor init(pinColor: UIColor) { self.pinColor = pinColor super.init() } } // Create a map view let mapView = MKMapView(frame: CGRect( x:0, y:0, width:800, height:800)) // Create an initial point (Marina Bay Sands) let initialPoint = CLLocation(latitude: 1.2832185, longitude: 103.8581184) // Create and populate a visible region on the map var region = MKCoordinateRegion() region.center.latitude = initialPoint.coordinate.latitude region.center.longitude = initialPoint.coordinate.longitude // Span defines the zoom let delta = 0.01 region.span.latitudeDelta = delta region.span.longitudeDelta = delta // inform the mapView of these edits mapView.setRegion( region, animated: false ) protocol MapRenderable { func renderInView(mapView: MKMapView) } class Renderer: NSObject, MKMapViewDelegate { func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) let colorPointAnnotation = annotation as! ColoredAnnotation pinView?.pinTintColor = colorPointAnnotation.pinColor } else { pinView?.annotation = annotation } return pinView } } class LocationsRenderer: Renderer, MapRenderable { var locations: [CLLocation] = [] var color: UIColor? func renderInView(mapView: MKMapView) { let colors: [UIColor] = [.blueColor(), .magentaColor(), .brownColor(), .greenColor()] var pinColor = UIColor.blueColor() if let color = color { pinColor = color } else { pinColor = colors[Int(arc4random()) % colors.count] } for location in locations { let annotation = ColoredAnnotation(pinColor: pinColor) annotation.coordinate = location.coordinate mapView.addAnnotation(annotation) } } } class CentroidsRenderer: Renderer, MapRenderable { var centroids: [Centroid] = [] func renderInView(mapView: MKMapView) { let colors: [UIColor] = [.blackColor(), .whiteColor(), .orangeColor(), .purpleColor()] mapView.delegate = self for i in 0..<centroids.count { let centroid = centroids[i] let color = colors[i % colors.count] let annotation = ColoredAnnotation(pinColor: color) annotation.coordinate = centroid.center.coordinate annotation.title = "centroid\(i)" mapView.addAnnotation(annotation) let locationsRenderer = LocationsRenderer() locationsRenderer.locations = centroid.points locationsRenderer.color = colors[(i + 1) % colors.count] locationsRenderer.renderInView(mapView) } } } // List of all locations var locations = [CLLocation]() // List of all centroids var centroidLocations = [CLLocation]() centroidLocations.append(initialPoint) let maxDistance: CLLocationDistance = 200.0 // meters // Generate random centroids for i in 0..<3 { let angle = Double(arc4random() % 360) * 180.0 / M_PI let distance = 500 + Double(arc4random() % 100) let location = initialPoint.locationWithBearing(angle, distance: distance) centroidLocations.append(location) } // Generate random set of locations near each centroid for centroid in centroidLocations { for i in 0..<10 { let angle = Double(arc4random() % 360) * 180.0 / M_PI let distance = Double(arc4random() % 100) let location = centroid.locationWithBearing(angle, distance: distance) locations.append(location) } } let locationsRenderer = LocationsRenderer() locationsRenderer.locations = locations //locationsRenderer.renderInView(mapView) let centroids = clusterLocations(locations, maxDistance: maxDistance) let centroidsRenderer = CentroidsRenderer() centroidsRenderer.centroids = centroids print(centroids.count) print(centroids[0].points.count) centroidsRenderer.renderInView(mapView) XCPlaygroundPage.currentPage.liveView = mapView XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
187a8826533d05a86799c0320413e98b
31.244526
118
0.644482
4.889319
false
false
false
false
saagarjha/iina
iina/GifGenerator.swift
4
1151
// // GifGenerator.swift // iina // // Created by lhc on 19/12/2016. // Copyright © 2016 lhc. All rights reserved. // import Cocoa class GifGenerator: NSObject { func createGIF(from images: [NSImage], at url: URL, loopCount: Int = 0, frameDelay: Double) throws { let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]] let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]] guard let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, Int(images.count), nil) else { throw IINAError.gifCannotCreateDestination } CGImageDestinationSetProperties(destination, fileProperties as CFDictionary) for i in 0..<images.count { guard let cgimg = images[i].cgImage(forProposedRect: nil, context: nil, hints: nil) else { throw IINAError.gifCannotConvertImage } CGImageDestinationAddImage(destination, cgimg, frameProperties as CFDictionary) } if !CGImageDestinationFinalize(destination) { throw IINAError.gifCannotFinalize } } }
gpl-3.0
2ad54d89aae29209ab2b291a65b6a32a
30.944444
121
0.736522
4.545455
false
false
false
false
smdls/C0
C0/Other.swift
1
33832
/* Copyright 2017 S This file is part of C0. C0 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. C0 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 C0. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa struct BezierIntersection { var t: CGFloat, isLeft: Bool, point: CGPoint } struct Bezier2 { var p0 = CGPoint(), p1 = CGPoint(), p2 = CGPoint() static func linear(_ p0: CGPoint, _ p1: CGPoint) -> Bezier2 { return Bezier2(p0: p0, p1: p0.mid(p1), p2: p1) } var bounds: CGRect { var minX = min(p0.x, p2.x), maxX = max(p0.x, p2.x) var d = p2.x - 2*p1.x + p0.x if d != 0 { let t = (p0.x - p1.x)/d if t >= 0 && t <= 1 { let rt = 1 - t let tx = rt*rt*p0.x + 2*rt*t*p1.x + t*t*p2.x if tx < minX { minX = tx } else if tx > maxX { maxX = tx } } } var minY = min(p0.y, p2.y), maxY = max(p0.y, p2.y) d = p2.y - 2*p1.y + p0.y if d != 0 { let t = (p0.y - p1.y)/d if t >= 0 && t <= 1 { let rt = 1 - t let ty = rt*rt*p0.y + 2*rt*t*p1.y + t*t*p2.y if ty < minY { minY = ty } else if ty > maxY { maxY = ty } } } return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } var boundingBox: CGRect { return AABB(self).rect } func length(withFlatness flatness: Int = 128) -> CGFloat { var d = 0.0.cf, oldP = p0 let nd = 1/flatness.cf for i in 0 ..< flatness { let newP = position(withT: (i + 1).cf*nd) d += oldP.distance(newP) oldP = newP } return d } func t(withLength length: CGFloat, flatness: Int = 128) -> CGFloat { var d = 0.0.cf, oldP = p0 let nd = 1/flatness.cf for i in 0 ..< flatness { let t = (i + 1).cf*nd let newP = position(withT: t) d += oldP.distance(newP) if d > length { return t } oldP = newP } return 1 } func difference(withT t: CGFloat) -> CGPoint { return CGPoint(x: 2*(p1.x - p0.x) + 2*(p0.x - 2*p1.x + p2.x)*t, y: 2*(p1.y - p0.y) + 2*(p0.y - 2*p1.y + p2.y)*t) } func tangential(withT t: CGFloat) -> CGFloat { return atan2(2*(p1.y - p0.y) + 2*(p0.y - 2*p1.y + p2.y)*t, 2*(p1.x - p0.x) + 2*(p0.x - 2*p1.x + p2.x)*t) } func position(withT t: CGFloat) -> CGPoint { let rt = 1 - t return CGPoint(x: rt*rt*p0.x + 2*t*rt*p1.x + t*t*p2.x, y: rt*rt*p0.y + 2*t*rt*p1.y + t*t*p2.y) } func midSplit() -> (b0: Bezier2, b1: Bezier2) { let p0p1 = p0.mid(p1), p1p2 = p1.mid(p2) let p = p0p1.mid(p1p2) return (Bezier2(p0: p0, p1: p0p1, p2: p), Bezier2(p0: p, p1: p1p2, p2: p2)) } func clip(startT t0: CGFloat, endT t1: CGFloat) -> Bezier2 { let rt0 = 1 - t0, rt1 = 1 - t1 let t0p0p1 = CGPoint(x: rt0*p0.x + t0*p1.x, y: rt0*p0.y + t0*p1.y) let t0p1p2 = CGPoint(x: rt0*p1.x + t0*p2.x, y: rt0*p1.y + t0*p2.y) let np0 = CGPoint(x: rt0*t0p0p1.x + t0*t0p1p2.x, y: rt0*t0p0p1.y + t0*t0p1p2.y) let np1 = CGPoint(x: rt1*t0p0p1.x + t1*t0p1p2.x, y: rt1*t0p0p1.y + t1*t0p1p2.y) let t1p0p1 = CGPoint(x: rt1*p0.x + t1*p1.x, y: rt1*p0.y + t1*p1.y) let t1p1p2 = CGPoint(x: rt1*p1.x + t1*p2.x, y: rt1*p1.y + t1*p2.y) let np2 = CGPoint(x: rt1*t1p0p1.x + t1*t1p1p2.x, y: rt1*t1p0p1.y + t1*t1p1p2.y) return Bezier2(p0: np0, p1: np1, p2: np2) } func intersects(_ other: Bezier2) -> Bool { return intersects(other, 0, 1, 0, 1, isFlipped: false) } private let intersectsMinRange = 0.000001.cf private func intersects(_ other: Bezier2, _ min0: CGFloat, _ max0: CGFloat, _ min1: CGFloat, _ max1: CGFloat, isFlipped: Bool) -> Bool { let aabb0 = AABB(self), aabb1 = AABB(other) if !aabb0.intersects(aabb1) { return false } if max(aabb1.maxX - aabb1.minX, aabb1.maxY - aabb1.minY) < intersectsMinRange { return true } let range1 = max1 - min1 let nb = other.midSplit() if nb.b0.intersects(self, min1, min1 + 0.5*range1, min0, max0, isFlipped: !isFlipped) { return true } else { return nb.b1.intersects(self, min1 + 0.5*range1, min1 + range1, min0, max0, isFlipped: !isFlipped) } } func intersections(_ other: Bezier2) -> [BezierIntersection] { var results = [BezierIntersection]() intersections(other, &results, 0, 1, 0, 1, isFlipped: false) return results } private func intersections(_ other: Bezier2, _ results: inout [BezierIntersection], _ min0: CGFloat, _ max0: CGFloat, _ min1: CGFloat, _ max1: CGFloat, isFlipped: Bool) { let aabb0 = AABB(self), aabb1 = AABB(other) if !aabb0.intersects(aabb1) { return } let range1 = max1 - min1 if max(aabb1.maxX - aabb1.minX, aabb1.maxY - aabb1.minY) >= intersectsMinRange { let nb = other.midSplit() nb.b0.intersections(self, &results, min1, min1 + range1/2, min0, max0, isFlipped: !isFlipped) if results.count < 4 { nb.b1.intersections(self, &results, min1 + range1/2, min1 + range1, min0, max0, isFlipped: !isFlipped) } return } let newP = CGPoint(x: (aabb1.minX + aabb1.maxX)/2, y: (aabb1.minY + aabb1.maxY)/2) func isSolution() -> Bool { if !results.isEmpty { let oldP = results[results.count - 1].point let x = newP.x - oldP.x, y = newP.y - oldP.y if x*x + y*y < intersectsMinRange { return false } } return true } if !isSolution() { return } let b0t: CGFloat, b1t: CGFloat, b0: Bezier2, b1:Bezier2 if !isFlipped { b0t = (min0 + max0)/2 b1t = min1 + range1/2 b0 = self b1 = other } else { b1t = (min0 + max0)/2 b0t = min1 + range1/2 b0 = other b1 = self } let b0dp = b0.difference(withT: b0t), b1dp = b1.difference(withT: b1t) let b0b1Cross = b0dp.x*b1dp.y - b0dp.y*b1dp.x if b0b1Cross != 0 { results.append(BezierIntersection(t: b0t, isLeft: b0b1Cross > 0, point: newP)) } } } struct Bezier3 { var p0 = CGPoint(), cp0 = CGPoint(), cp1 = CGPoint(), p1 = CGPoint() func split(withT t: CGFloat) -> (b0: Bezier3, b1: Bezier3) { let b0cp0 = CGPoint.linear(p0, cp0, t: t), cp0cp1 = CGPoint.linear(cp0, cp1, t: t), b1cp1 = CGPoint.linear(cp1, p1, t: t) let b0cp1 = CGPoint.linear(b0cp0, cp0cp1, t: t), b1cp0 = CGPoint.linear(cp0cp1, b1cp1, t: t) let p = CGPoint.linear(b0cp1, b1cp0, t: t) return (Bezier3(p0: p0, cp0: b0cp0, cp1: b0cp1, p1: p), Bezier3(p0: p, cp0: b1cp0, cp1: b1cp1, p1: p1)) } func y(withX x: CGFloat) -> CGFloat { var y = 0.0.cf let sb = split(withT: 0.5) if !sb.b0.y(withX: x, y: &y) { _ = sb.b1.y(withX: x, y: &y) } return y } private let yMinRange = 0.000001.cf private func y(withX x: CGFloat, y: inout CGFloat) -> Bool { let aabb = AABB(self) if aabb.minX < x && aabb.maxX >= x { if aabb.maxY - aabb.minY < yMinRange { y = (aabb.minY + aabb.maxY)/2 return true } else { let sb = split(withT: 0.5) if sb.b0.y(withX: x, y: &y) { return true } else { return sb.b1.y(withX: x, y: &y) } } } else { return false } } func difference(withT t: CGFloat) -> CGPoint { let rt = 1 - t let dx = 3*(t*t*(p1.x - cp1.x)+2*t*rt*(cp1.x - cp0.x) + rt*rt*(cp0.x - p0.x)) let dy = 3*(t*t*(p1.y - cp1.y)+2*t*rt*(cp1.y - cp0.y) + rt*rt*(cp0.y - p0.y)) return CGPoint(x: dx, y: dy) } } struct AABB { var minX = 0.0.cf, maxX = 0.0.cf, minY = 0.0.cf, maxY = 0.0.cf init(minX: CGFloat = 0, maxX: CGFloat = 0, minY: CGFloat = 0, maxY: CGFloat = 0) { self.minX = minX self.minY = minY self.maxX = maxX self.maxY = maxY } init(_ rect: CGRect) { minX = rect.minX minY = rect.minY maxX = rect.maxX maxY = rect.maxY } init(_ b: Bezier2) { minX = min(b.p0.x, b.p1.x, b.p2.x) minY = min(b.p0.y, b.p1.y, b.p2.y) maxX = max(b.p0.x, b.p1.x, b.p2.x) maxY = max(b.p0.y, b.p1.y, b.p2.y) } init(_ b: Bezier3) { minX = min(b.p0.x, b.cp0.x, b.cp1.x, b.p1.x) minY = min(b.p0.y, b.cp0.y, b.cp1.y, b.p1.y) maxX = max(b.p0.x, b.cp0.x, b.cp1.x, b.p1.x) maxY = max(b.p0.y, b.cp0.y, b.cp1.y, b.p1.y) } var position: CGPoint { return CGPoint(x: minX, y: minY) } var rect: CGRect { return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } func nearestSquaredDistance(_ p: CGPoint) -> CGFloat { if p.x < minX { return p.y < minY ? hypot2(minX - p.x, minY - p.y) : (p.y <= maxY ? (minX - p.x).squared() : hypot2(minX - p.x, maxY - p.y)) } else if p.x <= maxX { return p.y < minY ? (minY - p.y).squared() : (p.y <= maxY ? 0 : (minY - p.y).squared()) } else { return p.y < minY ? hypot2(maxX - p.x, minY - p.y) : (p.y <= maxY ? (maxX - p.x).squared() : hypot2(maxX - p.x, maxY - p.y)) } } func intersects(_ other: AABB) -> Bool { return minX <= other.maxX && maxX >= other.minX && minY <= other.maxY && maxY >= other.minY } } final class LockTimer { private var count = 0 private(set) var wait = false func begin(_ endTimeLength: TimeInterval, beginHandler: () -> Void, endHandler: @escaping () -> Void) { if wait { count += 1 } else { beginHandler() wait = true } DispatchQueue.main.asyncAfter(deadline: .now() + endTimeLength) { if self.count == 0 { endHandler() self.wait = false } else { self.count -= 1 } } } private(set) var inUse = false private weak var timer: Timer? func begin(_ interval: TimeInterval, repeats: Bool = true, tolerance: TimeInterval = TimeInterval(0), handler: @escaping (Void) -> Void) { let time = interval + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, repeats ? interval : 0, 0, 0) { _ in handler() } CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .commonModes) self.timer = timer inUse = true self.timer?.tolerance = tolerance } func stop() { inUse = false timer?.invalidate() timer = nil } } final class Weak<T: AnyObject> { weak var value : T? init (value: T) { self.value = value } } func hypot2(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat { return lhs*lhs + rhs*rhs } protocol Copying: class { var deepCopy: Self { get } } protocol Interpolatable { static func linear(_ f0: Self, _ f1: Self, t: CGFloat) -> Self static func firstMonospline(_ f1: Self, _ f2: Self, _ f3: Self, with msx: MonosplineX) -> Self static func monospline(_ f0: Self, _ f1: Self, _ f2: Self, _ f3: Self, with msx: MonosplineX) -> Self static func endMonospline(_ f0: Self, _ f1: Self, _ f2: Self, with msx: MonosplineX) -> Self } extension Comparable { func clip(min: Self, max: Self) -> Self { return self < min ? min : (self > max ? max : self) } func isOver(old: Self, new: Self) -> Bool { return (new >= self && old < self) || (new <= self && old > self) } } extension Array { func withRemovedLast() -> Array { var array = self array.removeLast() return array } func withRemoved(at i: Int) -> Array { var array = self array.remove(at: i) return array } func withAppend(_ element: Element) -> Array { var array = self array.append(element) return array } func withInserted(_ element: Element, at i: Int) -> Array { var array = self array.insert(element, at: i) return array } func withReplaced(_ element: Element, at i: Int) -> Array { var array = self array[i] = element return array } } extension String { var localized: String { return NSLocalizedString(self, comment: self) } } extension Int { var cf: CGFloat { return CGFloat(self) } } extension Float { var cf: CGFloat { return CGFloat(self) } static func linear(_ f0: Float, _ f1: Float, t: CGFloat) -> Float { let tf = t.f return f0*(1 - tf) + f1*tf } } extension Double { var f: Float { return Float(self) } var cf: CGFloat { return CGFloat(self) } } struct MonosplineX { let h0: CGFloat, h1: CGFloat, h2: CGFloat, invertH0: CGFloat, invertH1: CGFloat, invertH2: CGFloat let invertH0H1: CGFloat, invertH1H2: CGFloat, invertH1H1: CGFloat, xx3: CGFloat, xx2: CGFloat, xx1: CGFloat init(x1: CGFloat, x2: CGFloat, x3: CGFloat, x: CGFloat) { h0 = 0 h1 = x2 - x1 h2 = x3 - x2 invertH0 = 0 invertH1 = 1/h1 invertH2 = 1/h2 invertH0H1 = 0 invertH1H2 = 1/(h1 + h2) invertH1H1 = 1/(h1*h1) xx1 = x - x1 xx2 = xx1*xx1 xx3 = xx1*xx1*xx1 } init(x0: CGFloat, x1: CGFloat, x2: CGFloat, x3: CGFloat, x: CGFloat) { h0 = x1 - x0 h1 = x2 - x1 h2 = x3 - x2 invertH0 = 1/h0 invertH1 = 1/h1 invertH2 = 1/h2 invertH0H1 = 1/(h0 + h1) invertH1H2 = 1/(h1 + h2) invertH1H1 = 1/(h1*h1) xx1 = x - x1 xx2 = xx1*xx1 xx3 = xx1*xx1*xx1 } init(x0: CGFloat, x1: CGFloat, x2: CGFloat, x: CGFloat) { h0 = x1 - x0 h1 = x2 - x1 h2 = 0 invertH0 = 1/h0 invertH1 = 1/h1 invertH2 = 0 invertH0H1 = 1/(h0 + h1) invertH1H2 = 0 invertH1H1 = 1/(h1*h1) xx1 = x - x1 xx2 = xx1*xx1 xx3 = xx1*xx1*xx1 } } extension CGFloat: Interpolatable { var f: Float { return Float(self) } var d: Double { return Double(self) } func interval(scale: CGFloat) -> CGFloat { if scale == 0 { return self } else { let t = floor(self / scale)*scale return self - t > scale/2 ? t + scale : t } } static func sectionIndex(value v: CGFloat, in values: [CGFloat]) -> (index: Int, interValue: CGFloat, sectionValue: CGFloat)? { if let firstValue = values.first { var oldV = 0.0.cf for i in (0 ..< values.count).reversed() { let value = values[i] if v >= value { return (i, v - value, oldV - value) } oldV = value } return (0, v - firstValue, oldV - firstValue) } else { return nil } } func differenceRotation(_ other: CGFloat) -> CGFloat { let a = self - other return a + (a > .pi ? -2*(.pi) : (a < -.pi ? 2*(.pi) : 0)) } static func differenceAngle(_ p0: CGPoint, p1: CGPoint, p2: CGPoint) -> CGFloat { let pa = p1 - p0 let pb = p2 - pa let ab = hypot(pa.x, pa.y)*hypot(pb.x, pb.y) return ab != 0 ? (pa.x*pb.y - pa.y*pb.x > 0 ? 1 : -1)*acos((pa.x*pb.x + pa.y*pb.y)/ab) : 0 } var clipRotation: CGFloat { return self < -.pi ? self + 2*(.pi) : (self > .pi ? self - 2*(.pi) : self) } func squared() -> CGFloat { return self*self } func loopValue(other: CGFloat, begin: CGFloat = 0, end: CGFloat = 1) -> CGFloat { if other < self { return self - other < (other - begin) + (end - self) ? self : self - (end - begin) } else { return other - self < (self - begin) + (end - other) ? self : self + (end - begin) } } func loopValue(_ begin: CGFloat = 0, end: CGFloat = 1) -> CGFloat { return self < begin ? self + (end - begin) : (self > end ? self - (end - begin) : self) } static func random(min: CGFloat, max: CGFloat) -> CGFloat { return (max - min)*(CGFloat(arc4random_uniform(UInt32.max))/CGFloat(UInt32.max)) + min } static func bilinear(x: CGFloat, y: CGFloat, a: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat) -> CGFloat { return x*y*(a - b - c + d) + x*(b - a) + y*(c - a) + a } static func linear(_ f0: CGFloat, _ f1: CGFloat, t: CGFloat) -> CGFloat { return f0*(1 - t) + f1*t } static func firstMonospline(_ f1: CGFloat, _ f2: CGFloat, _ f3: CGFloat, with msx: MonosplineX) -> CGFloat { let s1 = (f2 - f1)*msx.invertH1, s2 = (f3 - f2)*msx.invertH2 let signS1: CGFloat = s1 > 0 ? 1 : -1, signS2: CGFloat = s2 > 0 ? 1 : -1 let yPrime1 = s1 let yPrime2 = (signS1 + signS2)*Swift.min(abs(s1), abs(s2), 0.5*abs((msx.h2*s1 + msx.h1*s2)*msx.invertH1H2)) return _monospline(f1, s1, yPrime1, yPrime2, with: msx) } static func monospline(_ f0: CGFloat, _ f1: CGFloat, _ f2: CGFloat, _ f3: CGFloat, with msx: MonosplineX) -> CGFloat { let s0 = (f1 - f0)*msx.invertH0, s1 = (f2 - f1)*msx.invertH1, s2 = (f3 - f2)*msx.invertH2 let signS0: CGFloat = s0 > 0 ? 1 : -1, signS1: CGFloat = s1 > 0 ? 1 : -1, signS2: CGFloat = s2 > 0 ? 1 : -1 let yPrime1 = (signS0 + signS1)*Swift.min(abs(s0), abs(s1), 0.5*abs((msx.h1*s0 + msx.h0*s1)*msx.invertH0H1)) let yPrime2 = (signS1 + signS2)*Swift.min(abs(s1), abs(s2), 0.5*abs((msx.h2*s1 + msx.h1*s2)*msx.invertH1H2)) return _monospline(f1, s1, yPrime1, yPrime2, with: msx) } static func endMonospline(_ f0: CGFloat, _ f1: CGFloat, _ f2: CGFloat, with msx: MonosplineX) -> CGFloat { let s0 = (f1 - f0)*msx.invertH0, s1 = (f2 - f1)*msx.invertH1 let signS0: CGFloat = s0 > 0 ? 1 : -1, signS1: CGFloat = s1 > 0 ? 1 : -1 let yPrime1 = (signS0 + signS1)*Swift.min(abs(s0), abs(s1), 0.5*abs((msx.h1*s0 + msx.h0*s1)*msx.invertH0H1)) let yPrime2 = s1 return _monospline(f1, s1, yPrime1, yPrime2, with: msx) } private static func _monospline(_ f1: CGFloat, _ s1: CGFloat, _ yPrime1: CGFloat, _ yPrime2: CGFloat, with msx: MonosplineX) -> CGFloat { let a = (yPrime1 + yPrime2 - 2*s1)*msx.invertH1H1, b = (3*s1 - 2*yPrime1 - yPrime2)*msx.invertH1, c = yPrime1, d = f1 return a*msx.xx3 + b*msx.xx2 + c*msx.xx1 + d } } extension CGPoint: Interpolatable { func mid(_ other: CGPoint) -> CGPoint { return CGPoint(x: (x + other.x)/2, y: (y + other.y)/2) } static func linear(_ f0: CGPoint, _ f1: CGPoint, t: CGFloat) -> CGPoint { return CGPoint(x: CGFloat.linear(f0.x, f1.x, t: t), y: CGFloat.linear(f0.y, f1.y, t: t)) } static func firstMonospline(_ f1: CGPoint, _ f2: CGPoint, _ f3: CGPoint, with msx: MonosplineX) -> CGPoint { return CGPoint( x: CGFloat.firstMonospline(f1.x, f2.x, f3.x, with: msx), y: CGFloat.firstMonospline(f1.y, f2.y, f3.y, with: msx) ) } static func monospline(_ f0: CGPoint, _ f1: CGPoint, _ f2: CGPoint, _ f3: CGPoint, with msx: MonosplineX) -> CGPoint { return CGPoint( x: CGFloat.monospline(f0.x, f1.x, f2.x, f3.x, with: msx), y: CGFloat.monospline(f0.y, f1.y, f2.y, f3.y, with: msx) ) } static func endMonospline(_ f0: CGPoint, _ f1: CGPoint, _ f2: CGPoint, with msx: MonosplineX) -> CGPoint { return CGPoint( x: CGFloat.endMonospline(f0.x, f1.x, f2.x, with: msx), y: CGFloat.endMonospline(f0.y, f1.y, f2.y, with: msx) ) } static func intersection(p0: CGPoint, p1: CGPoint, q0: CGPoint, q1: CGPoint) -> Bool { let a0 = (p0.x - p1.x)*(q0.y - p0.y) + (p0.y - p1.y)*(p0.x - q0.x), b0 = (p0.x - p1.x)*(q1.y - p0.y) + (p0.y - p1.y)*(p0.x - q1.x) if a0*b0 < 0 { let a1 = (q0.x - q1.x)*(p0.y - q0.y) + (q0.y - q1.y)*(q0.x - p0.x), b1 = (q0.x - q1.x)*(p1.y - q0.y) + (q0.y - q1.y)*(q0.x - p1.x) if a1*b1 < 0 { return true } } return false } func tangential(_ other: CGPoint) -> CGFloat { return atan2(other.y - y, other.x - x) } func crossVector(_ other: CGPoint) -> CGFloat { return x*other.y - y*other.x } func distance(_ other: CGPoint) -> CGFloat { return hypot(other.x - x, other.y - y) } func distanceWithLine(ap: CGPoint, bp: CGPoint) -> CGFloat { return abs((bp - ap).crossVector(self - ap))/ap.distance(bp) } func distanceWithLineSegment(ap: CGPoint, bp: CGPoint) -> CGFloat { if ap == bp { return distance(ap) } else { let bav = bp - ap, pav = self - ap let r = (bav.x*pav.x + bav.y*pav.y)/(bav.x*bav.x + bav.y*bav.y) if r <= 0 { return distance(ap) } else if r > 1 { return distance(bp) } else { return abs(bav.crossVector(pav))/ap.distance(bp) } } } func squaredDistance(other: CGPoint) -> CGFloat { let nx = x - other.x, ny = y - other.y return nx*nx + ny*ny } static func differenceAngle(p0: CGPoint, p1: CGPoint, p2: CGPoint) -> CGFloat { return differenceAngle(a: p1 - p0, b: p2 - p1) } static func differenceAngle(a: CGPoint, b: CGPoint) -> CGFloat { return atan2(a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y) } static func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } static func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } static func * (left: CGPoint, right: CGFloat) -> CGPoint { return CGPoint(x: left.x*right, y: left.y*right) } } extension CGRect { func squaredDistance(_ point: CGPoint) -> CGFloat { return AABB(self).nearestSquaredDistance(point) } func unionNotEmpty(_ other: CGRect) -> CGRect { return other.isEmpty ? self : (isEmpty ? other : union(other)) } var circleBounds: CGRect { let r = hypot(width, height)/2 return CGRect(x: midX - r, y: midY - r, width: r*2, height: r*2) } func inset(by width: CGFloat) -> CGRect { return insetBy(dx: width, dy: width) } } extension CGAffineTransform { func flippedHorizontal(by width: CGFloat) -> CGAffineTransform { return translatedBy(x: width, y: 0).scaledBy(x: -1, y: 1) } } extension CGColor { final func multiplyAlpha(_ a: CGFloat) -> CGColor { return copy(alpha: a*alpha) ?? self } final func multiplyWhite(_ w: CGFloat) -> CGColor { if let components = components, let colorSpace = colorSpace { let cs = components.enumerated().map { $0.0 < components.count - 1 ? $0.1 + (1 - $0.1)*w : $0.1 } return CGColor(colorSpace: colorSpace, components: cs) ?? self } else { return self } } } extension CGPath { static func checkerboard(with size: CGSize, in frame: CGRect) -> CGPath { let path = CGMutablePath() let xCount = Int(frame.width/size.width) , yCount = Int(frame.height/(size.height*2)) for xi in 0 ..< xCount { let x = frame.maxX - (xi + 1).cf*size.width let fy = xi % 2 == 0 ? size.height : 0 for yi in 0 ..< yCount { let y = frame.minY + yi.cf*size.height*2 + fy path.addRect(CGRect(x: x, y: y, width: size.width, height: size.height)) } } return path } } extension CGContext { func addBezier(_ b: Bezier3) { move(to: b.p0) addCurve(to: b.p1, control1: b.cp0, control2: b.cp1) } func flipHorizontal(by width: CGFloat) { translateBy(x: width, y: 0) scaleBy(x: -1, y: 1) } func drawBlurWith(color fillColor: CGColor, width: CGFloat, strength: CGFloat, isLuster: Bool, path: CGPath, with di: DrawInfo) { let nFillColor: CGColor if fillColor.alpha < 1 { saveGState() setAlpha(fillColor.alpha) nFillColor = fillColor.copy(alpha: 1) ?? fillColor } else { nFillColor = fillColor } let pathBounds = path.boundingBoxOfPath.insetBy(dx: -width, dy: -width) let lineColor = strength == 1 ? nFillColor : nFillColor.multiplyAlpha(strength) beginTransparencyLayer(in: boundingBoxOfClipPath.intersection(pathBounds), auxiliaryInfo: nil) if isLuster { setShadow(offset: CGSize(), blur: width*di.scale, color: lineColor) } else { let shadowY = hypot(pathBounds.size.width, pathBounds.size.height) translateBy(x: 0, y: shadowY) let shadowOffset = CGSize(width: shadowY*di.scale*sin(di.rotation), height: -shadowY*di.scale*cos(di.rotation)) setShadow(offset: shadowOffset, blur: width*di.scale/2, color: lineColor) setLineWidth(width) setLineJoin(.round) setStrokeColor(lineColor) addPath(path) strokePath() translateBy(x: 0, y: -shadowY) } setFillColor(nFillColor) addPath(path) fillPath() endTransparencyLayer() if fillColor.alpha < 1 { restoreGState() } } } extension CTLine { var typographicBounds: CGRect { var ascent = 0.0.cf, descent = 0.0.cf, leading = 0.0.cf let width = CTLineGetTypographicBounds(self, &ascent, &descent, &leading).cf return CGRect(x: 0, y: descent + leading, width: width, height: ascent + descent) } } extension Bundle { var version: Int { return Int(infoDictionary?[String(kCFBundleVersionKey)] as? String ?? "0") ?? 0 } } extension NSCoding { static func with(_ data: Data) -> Self? { return data.isEmpty ? nil : NSKeyedUnarchiver.unarchiveObject(with: data) as? Self } var data: Data { return NSKeyedArchiver.archivedData(withRootObject: self) } } extension NSCoder { func decodeStruct<T: ByteCoding>(forKey key: String) -> T? { return T(coder: self, forKey: key) } func encodeStruct(_ byteCoding: ByteCoding, forKey key: String) { byteCoding.encode(in: self, forKey: key) } } protocol ByteCoding { init?(coder: NSCoder, forKey key: String) func encode(in coder: NSCoder, forKey key: String) init(data: Data) var data: Data { get } } extension ByteCoding { init?(coder: NSCoder, forKey key: String) { var length = 0 if let ptr = coder.decodeBytes(forKey: key, returnedLength: &length) { self = UnsafeRawPointer(ptr).assumingMemoryBound(to: Self.self).pointee } else { return nil } } func encode(in coder: NSCoder, forKey key: String) { var t = self withUnsafePointer(to: &t) { coder.encodeBytes(UnsafeRawPointer($0).bindMemory(to: UInt8.self, capacity: 1), length: MemoryLayout<Self>.size, forKey: key) } } init(data: Data) { self = data.withUnsafeBytes { UnsafeRawPointer($0).assumingMemoryBound(to: Self.self).pointee } } var data: Data { var t = self return Data(buffer: UnsafeBufferPointer(start: &t, count: 1)) } } extension Array: ByteCoding { init?(coder: NSCoder, forKey key: String) { var length = 0 if let ptr = coder.decodeBytes(forKey: key, returnedLength: &length) { let count = length/MemoryLayout<Element>.stride self = count == 0 ? [] : ptr.withMemoryRebound(to: Element.self, capacity: 1) { Array(UnsafeBufferPointer<Element>(start: $0, count: count)) } } else { return nil } } func encode(in coder: NSCoder, forKey key: String) { withUnsafeBufferPointer { ptr in ptr.baseAddress?.withMemoryRebound(to: UInt8.self, capacity: 1) { coder.encodeBytes($0, length: ptr.count*MemoryLayout<Element>.stride, forKey: key) } } } } extension NSColor { final class func checkerboardColor(_ color: NSColor, subColor: NSColor, size s: CGFloat = 5.0) -> NSColor { let size = NSSize(width: s*2, height: s*2) let image = NSImage(size: size) { ctx in let rect = CGRect(origin: CGPoint(), size: size) ctx.setFillColor(color.cgColor) ctx.fill(rect) ctx.fill(CGRect(x: 0, y: s, width: s, height: s)) ctx.fill(CGRect(x: s, y: 0, width: s, height: s)) ctx.setFillColor(subColor.cgColor) ctx.fill(CGRect(x: 0, y: 0, width: s, height: s)) ctx.fill(CGRect(x: s, y: s, width: s, height: s)) } return NSColor(patternImage: image) } static func polkaDotColorWith(color: NSColor?, dotColor: NSColor, radius r: CGFloat = 1.0, distance d: CGFloat = 4.0) -> NSColor { let tw = (2*r + d)*cos(.pi/3), th = (2*r + d)*sin(.pi/3) let bw = (tw - 2*r)/2, bh = (th - 2*r)/2 let size = CGSize(width: floor(bw*2 + tw + r*2), height: floor(bh*2 + th + r*2)) let image = NSImage(size: size) { ctx in if let color = color { ctx.setFillColor(color.cgColor) ctx.fill(CGRect(origin: CGPoint(), size: size)) } ctx.setFillColor(dotColor.cgColor) ctx.fillEllipse(in: CGRect(x: bw, y: bh, width: r*2, height: r*2)) ctx.fillEllipse(in: CGRect(x: bw + tw, y: bh + th, width: r*2, height: r*2)) } return NSColor(patternImage: image) } } extension NSImage { convenience init(size: CGSize, handler: (CGContext) -> Void) { self.init(size: size) lockFocus() if let ctx = NSGraphicsContext.current()?.cgContext { handler(ctx) } unlockFocus() } final var bitmapSize: CGSize { if let tiffRepresentation = tiffRepresentation { if let bitmap = NSBitmapImageRep(data: tiffRepresentation) { return CGSize(width: bitmap.pixelsWide, height: bitmap.pixelsHigh) } } return CGSize() } final var PNGRepresentation: Data? { if let tiffRepresentation = tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiffRepresentation) { return bitmap.representation(using: .PNG, properties: [NSImageInterlaced: false]) } else { return nil } } static func exportAppIcon() { let panel = NSOpenPanel() panel.canChooseDirectories = true panel.begin { [unowned panel] result in if result == NSFileHandlingPanelOKButton, let url = panel.url { for s in [16.0.cf, 32.0.cf, 64.0.cf, 128.0.cf, 256.0.cf, 512.0.cf, 1024.0.cf] { try? NSImage(size: CGSize(width: s, height: s), flipped: false) { rect -> Bool in let ctx = NSGraphicsContext.current()!.cgContext, c = s*0.5, r = s*0.43, l = s*0.008, fs = s*0.45, fillColor = NSColor(white: 1, alpha: 1), fontColor = NSColor(white: 0.4, alpha: 1) ctx.setFillColor(fillColor.cgColor) ctx.setStrokeColor(fontColor.cgColor) ctx.setLineWidth(l) ctx.addEllipse(in: CGRect(x: c - r, y: c - r, width: r*2, height: r*2)) ctx.drawPath(using: .fillStroke) var textLine = TextLine() textLine.string = "C\u{2080}" textLine.font = NSFont(name: "Avenir Next Regular", size: fs) ?? NSFont.systemFont(ofSize: fs) textLine.color = fontColor.cgColor textLine.isHorizontalCenter = true textLine.isCenterWithImageBounds = true textLine.draw(in: rect, in: ctx) return true }.PNGRepresentation?.write(to: url.appendingPathComponent("\(String(Int(s))).png")) } } } } } extension NSAttributedString { static func attributes(_ font: NSFont, color: CGColor) -> [String: Any] { return [String(kCTFontAttributeName): font, String(kCTForegroundColorAttributeName): color] } }
gpl-3.0
25c5e05c4b8fa202512407238eae4130
37.056243
205
0.538898
3.184488
false
false
false
false
hoomazoid/CTSlidingUpPanel
Example/CTSlidingUpPanel/TableViewController.swift
1
3161
// // TableViewController.swift // CTSlidingUpPanel_Example // // Created by Giorgi Andriadze on 1/26/18. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import CTSlidingUpPanel class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var bottomController:CTBottomSlideController?; @IBOutlet weak var parrent: UIView! @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var heightConstr: NSLayoutConstraint! let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat", "Eagle", "Smeagle", "Dreagle", "Feagle", "Foogo"] // cell reuse id (cells that scroll out of view can be reused) let cellReuseIdentifier = "cell" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. bottomController = CTBottomSlideController(topConstraint: topConstraint, heightConstraint: heightConstr, parent: view, bottomView: parrent, tabController: self.tabBarController!, navController: self.navigationController, visibleHeight: 64) bottomController?.set(table: tableView) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) tableView.delegate = self tableView.dataSource = self tableView.setEditing(true, animated: true) } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true; } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.animals.count } // create a cell for each table view row func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // create a new cell if needed or reuse an old one let cell:UITableViewCell = (self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier))! // set the text from the data model cell.textLabel?.text = self.animals[indexPath.row] return cell } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { } // method to run when table view cell is tapped func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("You tapped cell number \(indexPath.row).") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
8c232a588956429555bc9bdd68235741
34.909091
247
0.689873
5.14658
false
false
false
false
mindbody/Conduit
Sources/Conduit/Auth/AuthorizationCodeGrant/iOS/OAuth2SafariAuthorizationStrategy.swift
1
3089
// // OAuth2SafariAuthorizationStrategy.swift // Conduit // // Created by John Hammerlund on 6/28/17. // Copyright © 2017 MINDBODY. All rights reserved. // #if os(iOS) import Foundation import SafariServices /// Directs a potential resource owner to a web-based authorization request in an SFSafariViewController @available(iOS 9, *) public class OAuth2SafariAuthorizationStrategy: NSObject, OAuth2AuthorizationStrategy { private let presentingViewController: UIViewController private let authorizationRequestEndpoint: URL /// The redirect handler used for authorization responses via a custom URL scheme public var redirectHandler: OAuth2AuthorizationRedirectHandler = .default /// Creates a new OAuth2SafariAuthorizationStrategy /// - Parameters: /// - presentingViewController: The view controller from which to present the SFSafariViewController with an authorization request /// - authorizationRequestEndpoint: The unformatted endpoint at which authorization requests are sent public init(presentingViewController: UIViewController, authorizationRequestEndpoint: URL) { self.presentingViewController = presentingViewController self.authorizationRequestEndpoint = authorizationRequestEndpoint super.init() } public func authorize(request: OAuth2AuthorizationRequest, completion: @escaping Result<OAuth2AuthorizationResponse>.Block) { let requestURL = makeAuthorizationRequestURL(request: request) logger.debug("Attempting authorization at URL: \(requestURL)") DispatchQueue.main.async { let safariViewController = SFSafariViewController(url: requestURL) safariViewController.delegate = self self.presentingViewController.present(safariViewController, animated: true, completion: nil) self.redirectHandler.register { result in DispatchQueue.main.async { safariViewController.dismiss(animated: true, completion: nil) completion(result) } } } } private func makeAuthorizationRequestURL(request: OAuth2AuthorizationRequest) -> URL { let requestBuilder = HTTPRequestBuilder(url: authorizationRequestEndpoint) var parameters = request.additionalParameters ?? [:] parameters["client_id"] = request.clientIdentifier parameters["response_type"] = "code" parameters["redirect_uri"] = request.redirectURI?.absoluteString parameters["scope"] = request.scope parameters["state"] = request.state requestBuilder.queryStringParameters = parameters guard let request = try? requestBuilder.build() else { return authorizationRequestEndpoint } return request.url ?? authorizationRequestEndpoint } } @available(iOS 9, *) extension OAuth2SafariAuthorizationStrategy: SFSafariViewControllerDelegate { public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { redirectHandler.cancel() } } #endif
apache-2.0
975444f4fa9cc0ff296be7c54a811588
36.658537
136
0.724093
5.686924
false
false
false
false
sora0077/Nata
Sources/XPathFromCSS.swift
1
3373
// // XPathFromCSS.swift // Nata // // Created by 林達也 on 2015/12/31. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation private struct CSSRegex { static let id = try! NSRegularExpression(pattern: "\\#([\\w-_]+)", options: []) static let `class` = try! NSRegularExpression(pattern: "\\.([^\\.]+)", options: []) static let attribute = try! NSRegularExpression(pattern: "\\[(\\w+)\\]", options: []) } internal func XPathFromCSS(CSS: String) -> String { var XPathExpressions: [String] = [] for expression in CSS.componentsSeparatedByString(",") { guard expression.characters.count > 0 else { continue } var XPathComponents: [String] = ["./"] var prefix: String? = nil for (idx, token) in expression.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) .componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) .enumerate() { var token = token switch token { case "*" where idx != 0: XPathComponents.append("/*") case ">": prefix = "" case "+": prefix = "following-sibling::*[1]/self::" case "~": prefix = "following-sibling::" default: if empty(prefix) && idx != 0 { prefix = "descendant::" } if let symbolRange = token.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "#.[]")) { var XPathComponent = token.substringToIndex(symbolRange.startIndex) let range = NSMakeRange(0, token.characters.count) let symbol = symbolRange.startIndex == token.startIndex ? "*" : "" do { if let result = CSSRegex.id.firstMatchInString(token, options: [], range: range) where result.numberOfRanges > 1 { XPathComponent += "\(symbol)[@id = '\(token[result.rangeAtIndex(1)])']" } } do { for result in CSSRegex.`class`.matchesInString(token, options: [], range: range) { if result.numberOfRanges > 1 { XPathComponent += "\(symbol)[contains(concat(' ',normalize-space(@class),' '),' \(token[result.rangeAtIndex(1)]) ')]" } } } do { for result in CSSRegex.attribute.matchesInString(token, options: [], range: range) { if result.numberOfRanges > 1 { XPathComponent += "[@\(token[result.rangeAtIndex(1)])]" } } } token = XPathComponent } if let prefix = prefix { token = prefix + token } prefix = nil XPathComponents.append(token) } } XPathExpressions.append(XPathComponents.joinWithSeparator("/")) } return XPathExpressions.joinWithSeparator(" | ") }
mit
77273eac98cec10f73ec20fdbb501a1a
39.542169
149
0.484542
5.54201
false
false
false
false
Jobot/ChainRight
ChainRightTest/ChainRightTest/ViewController.swift
1
1472
// // ViewController.swift // ChainRightTest // // Created by Joseph Dixon on 3/6/15. // Copyright (c) 2015 Joseph Dixon. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { let listStatus = ChainRight.readUsernames() switch listStatus { case let .Success(usernames): println("Found users: \(usernames)") case let .Failure(error): println("Failure: \(error)") } let status = ChainRight.readPasswordForUsername("joseph") switch status { case let .Success(password): println("Found password: \(password)") case let .Failure(error): println("Failure: \(error)") } } @IBAction func didPressAddUserButton(sender: AnyObject) { let username = usernameField.text let password = passwordField.text let status = ChainRight.writePassword(password, forUsername: username) switch status { case .Success: println("User added successfully") case let .Failure(error): println("Failure: \(error)") } } }
mit
06fe1391f6a5d7c42ded36878cf0cb4a
26.773585
80
0.608696
4.717949
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableviewCells/Challenges/ChallengeDetailInfoTableViewCell.swift
1
4677
// // ChallengeDetailInfoTableViewCell.swift // Habitica // // Created by Elliot Schrock on 10/24/17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import Habitica_Models class ChallengeDetailInfoTableViewCell: UITableViewCell, ChallengeConfigurable { @IBOutlet weak var challengeTitleLabel: UILabel! @IBOutlet weak var expirationLabel: UILabel! @IBOutlet weak var rewardCurrencyCountView: HRPGCurrencyCountView! @IBOutlet weak var participantsLabel: UILabel! @IBOutlet weak var tagHolderView: UIView! @IBOutlet weak var participantsWrapper: UIView! @IBOutlet weak var prizeWrapper: UIView! override func awakeFromNib() { super.awakeFromNib() rewardCurrencyCountView.currency = .gem rewardCurrencyCountView.viewSize = .large } func configure(with challenge: ChallengeProtocol) { challengeTitleLabel.text = challenge.name?.unicodeEmoji rewardCurrencyCountView.amount = challenge.prize participantsLabel.text = "\(challenge.memberCount)" tagHolderView.translatesAutoresizingMaskIntoConstraints = false addTags(for: challenge) let theme = ThemeService.shared.theme contentView.backgroundColor = theme.windowBackgroundColor participantsWrapper.backgroundColor = theme.contentBackgroundColor prizeWrapper.backgroundColor = theme.contentBackgroundColor } func addTags(for challenge: ChallengeProtocol) { for view in tagHolderView.subviews { view.removeFromSuperview() } var tags: [UILabel] = [] if challenge.isOwner() { tags.append(ownerTag()) } if challenge.official { tags.append(officialTag()) } /*if challenge.user != nil { tags.append(joinedTag()) }*/ if let shortName = challenge.shortName { tags.append(nameTag(shortName)) } for (index, tag) in tags.enumerated() { tagHolderView.addSubview(tag) tag.translatesAutoresizingMaskIntoConstraints = false tag.addHeightConstraint(height: 22) tag.updateLayout() if index == 0 { tagHolderView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tag]", options: .init(rawValue: 0), metrics: nil, views: ["tag": tag])) } else { let previousTag = tags[index-1] tagHolderView.addConstraint(NSLayoutConstraint(item: tag, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: .equal, toItem: previousTag, attribute: .trailing, multiplier: 1.0, constant: 8)) } tagHolderView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[tag]-0-|", options: .init(rawValue: 0), metrics: nil, views: ["tag": tag])) if index == tags.count - 1 { tagHolderView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[tag]-0-|", options: .init(rawValue: 0), metrics: nil, views: ["tag": tag])) } } tagHolderView.updateLayout() contentView.updateLayout() } func ownerTag() -> UILabel { let label = emptyTagLabel() label.text = " Owner " label.textColor = UIColor.white label.backgroundColor = UIColor.blue50 return label } func officialTag() -> UILabel { let label = emptyTagLabel() label.text = " Official " label.textColor = UIColor.white label.backgroundColor = UIColor.purple300 return label } func joinedTag() -> UILabel { let label = emptyTagLabel() label.text = " Joined " label.textColor = UIColor.white label.backgroundColor = UIColor.green100 return label } func nameTag(_ shortName: String) -> UILabel { let label = emptyTagLabel() label.text = " \(shortName.unicodeEmoji) " label.textColor = UIColor.gray200 label.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor return label } func emptyTagLabel() -> UILabel { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.cornerRadius = 11 return label } } extension UIView { func updateLayout() { self.setNeedsUpdateConstraints() self.updateConstraints() self.setNeedsLayout() self.layoutIfNeeded() } }
gpl-3.0
e489f25e7399583ccd71988d76e6fd8c
33.131387
215
0.620188
5.132821
false
false
false
false
yakirlee/TwitterDemo
TwitterDemo/TwitterDemo/CellActionsView.swift
1
4435
// // CellActionsView.swift // TwitterDemo // // Created by Yakir on 16/4/25. // Copyright © 2016年 李. All rights reserved. // import UIKit import YYKit private let margin = 50 class CellActionsView: UIView { var user: User? { didSet { retweetLabel.text = "\(user!.listed_count ?? 0)" favoriteLabel.text = "\(user!.favourites_count ?? 0)" } } // MARK: - 私有控件 // 回复 private lazy var replyButton = UIButton(ykImageName: "icn_social_proof_conversation_default", title: nil) // 转发 private lazy var retweetButton = UIButton(type: UIButtonType.Custom) private lazy var retweetImage = UIImageView(ylImageName: "icn_activity_rt_tweet") private lazy var retweetLabel = UILabel(ykText: "3") // 点赞 private lazy var favoriteButton = UIButton(type: UIButtonType.Custom) private lazy var favoriteImage = UIImageView(ylImageName: "icn_tweet_action_inline_favorite") private lazy var favoriteLabel = UILabel(ykText: "15") override init(frame: CGRect) { super.init(frame: frame) setupUI() buttonAddEvent() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 点击事件 extension CellActionsView { func buttonAddEvent() { retweetButton.addTarget(self, action: #selector(CellActionsView.selectedRetweet), forControlEvents: .TouchUpInside) favoriteButton.addTarget(self, action: #selector(CellActionsView.selectedFavorite), forControlEvents: .TouchUpInside) } @objc func selectedRetweet() { UIView.animateWithDuration(0.4) { let listCount = (self.user?.listed_count ?? 0) + 1 self.retweetLabel.text = "\(listCount)" self.retweetImage.image = UIImage(named: "icn_activity_rt_tweet_Selected") self.retweetImage.snp_updateConstraints { (make) in make.top.equalTo(self.retweetButton).offset(2) } } } @objc func selectedFavorite() { UIView.animateWithDuration(0.4) { let favoriteCount = (self.user?.favourites_count ?? 0) + 1 self.favoriteLabel.text = "\(favoriteCount)" self.favoriteImage.image = UIImage(named: "icn_tweet_action_inline_favorite_Selected") let basicAni = CABasicAnimation.init(keyPath: "transform.scale") basicAni.duration = 0.25 basicAni.toValue = 0.5 basicAni.fromValue = 1 self.favoriteImage.layer.addAnimation(basicAni, forKey: "Animation") } } } // MARK: - UI设计 extension CellActionsView { func setupUI() { prepaerButton() addSubview(replyButton) addSubview(retweetButton) addSubview(favoriteButton) replyButton.snp_makeConstraints { (make) in make.left.equalTo(self) make.top.equalTo(self) } retweetButton .snp_makeConstraints { (make) in make.left.equalTo(replyButton.snp_right).offset(margin) make.top.equalTo(replyButton) } favoriteButton.snp_makeConstraints { (make) in make.top.equalTo(retweetButton) make.left.equalTo(retweetButton.snp_right).offset(margin) make.bottom.equalTo(self).offset(12) } } func prepaerButton() { retweetButton.addSubview(retweetImage) retweetButton.addSubview(retweetLabel) favoriteButton.addSubview(favoriteImage) favoriteButton.addSubview(favoriteLabel) retweetImage.contentMode = .ScaleAspectFill retweetImage.snp_makeConstraints { (make) in make.left.equalTo(retweetButton) make.top.equalTo(retweetButton).offset(-2) } retweetLabel.snp_makeConstraints { (make) in make.left.equalTo(retweetImage.snp_right).offset(4) make.top.equalTo(retweetButton) } favoriteImage.snp_makeConstraints { (make) in make.left.equalTo(favoriteButton) make.top.equalTo(favoriteButton) } favoriteImage.contentMode = .ScaleAspectFill favoriteLabel.snp_makeConstraints { (make) in make.left.equalTo(favoriteImage.snp_right).offset(4) make.top.equalTo(favoriteButton) } } }
mit
8e7273160d4be399ee1e943b738d1f16
32.325758
125
0.627331
4.358771
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/HabitButton.swift
1
4476
// // HabitButton.swift // Habitica // // Created by Phillip Thelen on 06.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import UIKit import Habitica_Models class HabitButton: UIView { private let label = UIImageView() private let roundedView = UIView() private let interactionOverlay = UIView() private let tapArea = UIView() private var buttonSize: CGFloat = 24 private var isActive = false var dimmOverlayView: UIView = { let view = UIView() view.backgroundColor = ThemeService.shared.theme.taskOverlayTint view.isHidden = true view.isUserInteractionEnabled = false return view }() var action: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { addSubview(roundedView) roundedView.layer.cornerRadius = buttonSize / 2 label.contentMode = .scaleAspectFit isUserInteractionEnabled = true roundedView.layer.borderWidth = 2 addSubview(dimmOverlayView) addSubview(label) interactionOverlay.backgroundColor = .init(white: 1.0, alpha: 0.4) interactionOverlay.isUserInteractionEnabled = false interactionOverlay.alpha = 0 addSubview(interactionOverlay) addSubview(tapArea) tapArea.isUserInteractionEnabled = true tapArea.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap))) } func configure(task: TaskProtocol, isNegative: Bool) { isActive = isNegative ? task.down : task.up let theme = ThemeService.shared.theme if isNegative { label.image = Asset.minus.image.withRenderingMode(.alwaysTemplate) } else { label.image = Asset.plus.image.withRenderingMode(.alwaysTemplate) } if isActive { backgroundColor = UIColor.forTaskValueLight(Int(task.value)) if task.value >= -1 && task.value < 1 { if ThemeService.shared.theme.isDark { roundedView.backgroundColor = UIColor.yellow10 } else { roundedView.backgroundColor = UIColor.yellow10 } } else { roundedView.backgroundColor = UIColor.forTaskValue(Int(task.value)) } roundedView.layer.borderColor = UIColor.clear.cgColor label.tintColor = .white } else { backgroundColor = theme.windowBackgroundColor roundedView.layer.borderColor = theme.separatorColor.cgColor roundedView.backgroundColor = theme.windowBackgroundColor label.tintColor = theme.separatorColor } dimmOverlayView.isHidden = !theme.isDark dimmOverlayView.backgroundColor = theme.taskOverlayTint } override func layoutSubviews() { let verticalCenter = frame.size.height / 2 let horizontalCenter = frame.size.width / 2 roundedView.frame = CGRect(x: horizontalCenter - buttonSize/2, y: verticalCenter - buttonSize/2, width: buttonSize, height: buttonSize) label.frame = CGRect(x: horizontalCenter - 6, y: verticalCenter - 6, width: 12, height: 12) dimmOverlayView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height) interactionOverlay.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height) tapArea.frame = CGRect(x: -20, y: -4, width: frame.size.width + 40, height: frame.size.height + 8) super.layoutSubviews() } @objc private func handleTap() { if isActive { if let action = action { action() } UIView.animate(withDuration: 0.2, animations: {[weak self] in self?.interactionOverlay.alpha = 1 }, completion: {[weak self] (_) in UIView.animate(withDuration: 0.2, delay: 0.1, options: .curveEaseInOut, animations: { self?.interactionOverlay.alpha = 0 }, completion: nil) }) } } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return bounds.insetBy(dx: -20, dy: -4).contains(point) } }
gpl-3.0
e3be3389088473088a2096ea17d295dc
35.983471
143
0.614749
4.77588
false
false
false
false
pawan007/ExpenseTracker
ExpenseTracker/CustomView/LineChart_New.swift
1
25057
import UIKit import QuartzCore // delegate method public protocol LineChartDelegate { func didSelectDataPoint(x: CGFloat, yValues: [CGFloat]) } /** * Define graph Y axis line height */ let GRAPH_Y_AXIS_HEIGHT:CGFloat = 30 /** * LineChart */ public class LineChart: UIView { /** * Helpers class */ private class Helpers { /** * Convert hex color to UIColor */ private class func UIColorFromHex(hex: Int) -> UIColor { let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0xFF00) >> 8) / 255.0 let blue = CGFloat((hex & 0xFF)) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1) } /** * Lighten color. */ private class func lightenUIColor(color: UIColor) -> UIColor { var h: CGFloat = 0 var s: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 color.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return UIColor(hue: h, saturation: s, brightness: b * 1.5, alpha: a) } } func setGradientBackground() { let colorTop = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).CGColor let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).CGColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ colorTop, colorBottom] gradientLayer.locations = [ 0.0, 1.0] gradientLayer.frame = self.bounds // self.layer.addSublayer(gradientLayer) let context = UIGraphicsGetCurrentContext() let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [colorTop, colorBottom], [0, 1])! // Draw Path let path = UIBezierPath(rect: CGRectMake(0, 0, frame.width, frame.height)) CGContextSaveGState(context!) path.addClip() CGContextDrawLinearGradient(context!, gradient, CGPointMake(frame.width / 2, 0), CGPointMake(frame.width / 2, frame.height), CGGradientDrawingOptions()) CGContextRestoreGState(context!) } public struct Labels { public var visible: Bool = true public var values: [String] = [] } public struct Grid { public var visible: Bool = true public var count: CGFloat = 10 // #eeeeee public var color: UIColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 0.3) } public struct Axis { public var visible: Bool = true // #607d8b // public var color: UIColor = UIColor(red: 96/255.0, green: 125/255.0, blue: 139/255.0, alpha: 1) public var color: UIColor = UIColor(red: 255/255.0, green: 225/255.0, blue: 255/255.0, alpha: 0.6) public var inset: CGFloat = 15 } public struct Coordinate { // public public var labels: Labels = Labels() public var grid: Grid = Grid() public var axis: Axis = Axis() // private private var linear: LinearScale! private var scale: ((CGFloat) -> CGFloat)! private var invert: ((CGFloat) -> CGFloat)! private var ticks: (CGFloat, CGFloat, CGFloat)! } public struct Animation { public var enabled: Bool = true public var duration: CFTimeInterval = 1 } public struct Dots { public var visible: Bool = true public var color: UIColor = UIColor.whiteColor() public var innerRadius: CGFloat = 2 public var outerRadius: CGFloat = 4 public var innerRadiusHighlighted: CGFloat = 2 public var outerRadiusHighlighted: CGFloat = 4 } // default configuration public var area: Bool = true public var animation: Animation = Animation() public var dots: Dots = Dots() public var lineWidth: CGFloat = 2 public var x: Coordinate = Coordinate() public var y: Coordinate = Coordinate() // values calculated on init private var drawingHeight: CGFloat = 0 { didSet { let max = getMaximumValue() let min = getMinimumValue() y.linear = LinearScale(domain: [min, max], range: [0, drawingHeight]) y.scale = y.linear.scale() y.ticks = y.linear.ticks(Int(y.grid.count)) } } private var drawingWidth: CGFloat = 0 { didSet { let data = dataStore[0] x.linear = LinearScale(domain: [0.0, CGFloat(data.count - 1)], range: [0, drawingWidth]) x.scale = x.linear.scale() x.invert = x.linear.invert() x.ticks = x.linear.ticks(Int(x.grid.count)) } } public var delegate: LineChartDelegate? // data stores private var dataStore: [[CGFloat]] = [] private var dotsDataStore: [[DotCALayer]] = [] private var lineLayerStore: [CAShapeLayer] = [] private var removeAll: Bool = false // category10 colors from d3 - https://github.com/mbostock/d3/wiki/Ordinal-Scales /* public var colors: [UIColor] = [ UIColor(red: 0.121569, green: 0.466667, blue: 0.705882, alpha: 1), UIColor(red: 1, green: 0.498039, blue: 0.054902, alpha: 1), UIColor(red: 0.172549, green: 0.627451, blue: 0.172549, alpha: 1), UIColor(red: 0.839216, green: 0.152941, blue: 0.156863, alpha: 1), UIColor(red: 0.580392, green: 0.403922, blue: 0.741176, alpha: 1), UIColor(red: 0.54902, green: 0.337255, blue: 0.294118, alpha: 1), UIColor(red: 0.890196, green: 0.466667, blue: 0.760784, alpha: 1), UIColor(red: 0.498039, green: 0.498039, blue: 0.498039, alpha: 1), UIColor(red: 0.737255, green: 0.741176, blue: 0.133333, alpha: 1), UIColor(red: 0.0901961, green: 0.745098, blue: 0.811765, alpha: 1) ] */ public var colors: [UIColor] = [ UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.8), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.79), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.75), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.72), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.70), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.68), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.64), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.60), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.55), UIColor(red: 244/255.0, green: 190/255.0, blue: 51/255.0, alpha: 0.50) ] override public init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } convenience init() { self.init(frame: CGRectZero) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func drawRect(rect: CGRect) { if removeAll { let context = UIGraphicsGetCurrentContext() CGContextClearRect(context!, rect) return } //----------------------------------------// self.setGradientBackground() //round coner let width = rect.width let height = rect.height let ctx: CGContextRef = UIGraphicsGetCurrentContext()! CGContextSaveGState(ctx) let rect = CGRectMake(0, 0, width, height) let clipPath: CGPathRef = UIBezierPath(roundedRect: rect, cornerRadius: 4.0).CGPath CGContextAddPath(ctx, clipPath) CGContextSetFillColorWithColor(ctx, UIColor.clearColor().CGColor) CGContextClosePath(ctx) CGContextFillPath(ctx) CGContextRestoreGState(ctx) let maskForYourPath = CAShapeLayer() maskForYourPath.path = clipPath layer.mask = maskForYourPath //--------------------------------------// self.drawingHeight = -GRAPH_Y_AXIS_HEIGHT + self.bounds.height - (2 * y.axis.inset) // Narender self.drawingWidth = self.bounds.width - (2 * x.axis.inset) // remove all labels for view: AnyObject in self.subviews { view.removeFromSuperview() } // remove all lines on device rotation for lineLayer in lineLayerStore { lineLayer.removeFromSuperlayer() } lineLayerStore.removeAll() // remove all dots on device rotation for dotsData in dotsDataStore { for dot in dotsData { dot.removeFromSuperlayer() } } dotsDataStore.removeAll() // draw grid if x.grid.visible && y.grid.visible { drawGrid() } // draw axes if x.axis.visible && y.axis.visible { drawAxes() } // draw labels if x.labels.visible { drawXLabels() } if y.labels.visible { drawYLabels() } // draw lines for (lineIndex, _) in dataStore.enumerate() { drawLine(lineIndex) // draw dots if dots.visible { drawDataDots(lineIndex) } // draw area under line chart if area { drawAreaBeneathLineChart(lineIndex) } } } /** * Get y value for given x value. Or return zero or maximum value. */ private func getYValuesForXValue(x: Int) -> [CGFloat] { var result: [CGFloat] = [] for lineData in dataStore { if x < 0 { result.append(lineData[0]) } else if x > lineData.count - 1 { result.append(lineData[lineData.count - 1]) } else { result.append(lineData[x]) } } return result } /** * Handle touch events. */ private func handleTouchEvents(touches: NSSet!, event: UIEvent) { if (self.dataStore.isEmpty) { return } let point: AnyObject! = touches.anyObject() let xValue = point.locationInView(self).x let inverted = self.x.invert(xValue - x.axis.inset) let rounded = Int(round(Double(inverted))) let yValues: [CGFloat] = getYValuesForXValue(rounded) highlightDataPoints(rounded) delegate?.didSelectDataPoint(CGFloat(rounded), yValues: yValues) } /** * Listen on touch end event. */ override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { handleTouchEvents(touches, event: event!) } /** * Listen on touch move event */ override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { handleTouchEvents(touches, event: event!) } /** * Highlight data points at index. */ private func highlightDataPoints(index: Int) { for (lineIndex, dotsData) in dotsDataStore.enumerate() { // make all dots white again for dot in dotsData { dot.backgroundColor = dots.color.CGColor } // highlight current data point var dot: DotCALayer if index < 0 { dot = dotsData[0] } else if index > dotsData.count - 1 { dot = dotsData[dotsData.count - 1] } else { dot = dotsData[index] } dot.backgroundColor = Helpers.lightenUIColor(colors[lineIndex]).CGColor } } /** * Draw small dot at every data point. */ private func drawDataDots(lineIndex: Int) { var dotLayers: [DotCALayer] = [] var data = self.dataStore[lineIndex] for index in 0..<data.count { let xValue = self.x.scale(CGFloat(index)) + x.axis.inset - dots.outerRadius/2 let yValue = self.bounds.height - self.y.scale(data[index]) - y.axis.inset - dots.outerRadius/2 // draw custom layer with another layer in the center let dotLayer = DotCALayer() dotLayer.dotInnerColor = colors[lineIndex] dotLayer.innerRadius = dots.innerRadius dotLayer.backgroundColor = dots.color.CGColor dotLayer.cornerRadius = dots.outerRadius / 2 dotLayer.frame = CGRect(x: xValue, y: yValue, width: dots.outerRadius, height: dots.outerRadius) self.layer.addSublayer(dotLayer) dotLayers.append(dotLayer) // animate opacity if animation.enabled { let anim = CABasicAnimation(keyPath: "opacity") anim.duration = animation.duration anim.fromValue = 0 anim.toValue = 1 dotLayer.addAnimation(anim, forKey: "opacity") } } dotsDataStore.append(dotLayers) } /** * Draw x and y axis. */ private func drawAxes() { let height = self.bounds.height let width = self.bounds.width let path = UIBezierPath() // draw x-axis x.axis.color.setStroke() let y0 = height - self.y.scale(0) - y.axis.inset path.moveToPoint(CGPoint(x: x.axis.inset, y: y0)) path.addLineToPoint(CGPoint(x: width - x.axis.inset, y: y0)) path.stroke() // draw y-axis y.axis.color.setStroke() path.moveToPoint(CGPoint(x: x.axis.inset, y: height - y.axis.inset)) path.addLineToPoint(CGPoint(x: x.axis.inset, y: +GRAPH_Y_AXIS_HEIGHT+y.axis.inset)) // Narender path.stroke() // draw Top x-axis x.axis.color.setStroke() let y00:CGFloat = 35//height - self.y.scale(0) - y.axis.inset path.moveToPoint(CGPoint(x: -20+x.axis.inset, y: y00)) //20 Narender path.addLineToPoint(CGPoint(x: 20+width - x.axis.inset, y: y00)) //20 Narender path.stroke() } /** * Get maximum value in all arrays in data store. */ private func getMaximumValue() -> CGFloat { var max: CGFloat = 1 for data in dataStore { let newMax = data.maxElement()! if newMax > max { max = newMax } } return max } /** * Get maximum value in all arrays in data store. */ private func getMinimumValue() -> CGFloat { var min: CGFloat = 0 for data in dataStore { let newMin = data.minElement()! if newMin < min { min = newMin } } return min } /** * Draw line. */ private func drawLine(lineIndex: Int) { var data = self.dataStore[lineIndex] let path = UIBezierPath() var xValue = self.x.scale(0) + x.axis.inset var yValue = self.bounds.height - self.y.scale(data[0]) - y.axis.inset path.moveToPoint(CGPoint(x: xValue, y: yValue)) for index in 1..<data.count { xValue = self.x.scale(CGFloat(index)) + x.axis.inset yValue = self.bounds.height - self.y.scale(data[index]) - y.axis.inset path.addLineToPoint(CGPoint(x: xValue, y: yValue)) } let layer = CAShapeLayer() layer.frame = self.bounds layer.path = path.CGPath layer.strokeColor = UIColor.whiteColor().CGColor //colors[lineIndex].CGColor Line Color layer.fillColor = nil layer.lineWidth = lineWidth self.layer.addSublayer(layer) // animate line drawing if animation.enabled { let anim = CABasicAnimation(keyPath: "strokeEnd") anim.duration = animation.duration anim.fromValue = 0 anim.toValue = 1 layer.addAnimation(anim, forKey: "strokeEnd") } // add line layer to store lineLayerStore.append(layer) } /** * Fill area between line chart and x-axis. */ private func drawAreaBeneathLineChart(lineIndex: Int) { var data = self.dataStore[lineIndex] let path = UIBezierPath() colors[lineIndex].colorWithAlphaComponent(0.2).setFill() // move to origin path.moveToPoint(CGPoint(x: x.axis.inset, y: self.bounds.height - self.y.scale(0) - y.axis.inset)) // add line to first data point path.addLineToPoint(CGPoint(x: x.axis.inset, y: self.bounds.height - self.y.scale(data[0]) - y.axis.inset)) // draw whole line chart for index in 1..<data.count { let x1 = self.x.scale(CGFloat(index)) + x.axis.inset let y1 = self.bounds.height - self.y.scale(data[index]) - y.axis.inset path.addLineToPoint(CGPoint(x: x1, y: y1)) } // move down to x axis path.addLineToPoint(CGPoint(x: self.x.scale(CGFloat(data.count - 1)) + x.axis.inset, y: self.bounds.height - self.y.scale(0) - y.axis.inset)) // move to origin path.addLineToPoint(CGPoint(x: x.axis.inset, y: self.bounds.height - self.y.scale(0) - y.axis.inset)) path.fill() } /** * Draw x grid. */ private func drawXGrid() { x.grid.color.setStroke() let path = UIBezierPath() var x1: CGFloat let y1: CGFloat = self.bounds.height - y.axis.inset let y2: CGFloat = 50//y.axis.inset //50 Narender let (start, stop, step) = self.x.ticks for var i: CGFloat = start; i <= stop; i += step { x1 = self.x.scale(i) + x.axis.inset path.moveToPoint(CGPoint(x: x1, y: y1)) path.addLineToPoint(CGPoint(x: x1, y: y2)) } path.stroke() } /** * Draw y grid. */ private func drawYGrid() { self.y.grid.color.setStroke() let path = UIBezierPath() let x1: CGFloat = x.axis.inset let x2: CGFloat = self.bounds.width - x.axis.inset var y1: CGFloat let (start, stop, step) = self.y.ticks for var i: CGFloat = start; i <= stop; i += step { y1 = self.bounds.height - self.y.scale(i) - y.axis.inset path.moveToPoint(CGPoint(x: x1, y: y1)) path.addLineToPoint(CGPoint(x: x2, y: y1)) } path.stroke() } /** * Draw grid. */ private func drawGrid() { drawXGrid() drawYGrid() } /** * Draw x labels. */ private func drawXLabels() { let xAxisData = self.dataStore[0] let y = self.bounds.height - x.axis.inset let (_, _, step) = x.linear.ticks(xAxisData.count) let width = x.scale(step) var text: String for (index, _) in xAxisData.enumerate() { let xValue = self.x.scale(CGFloat(index)) + x.axis.inset - (width / 2) let label = UILabel(frame: CGRect(x: xValue, y: y, width: width, height: x.axis.inset)) label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) label.textAlignment = .Center if (x.labels.values.count != 0) { //text = x.labels.values[index] if(x.labels.values.count > index) { text = x.labels.values[index] } else { text = "" } } else { text = String(index) } label.text = text label.textColor = UIColor(red: 255/255.0, green: 225/255.0, blue: 255/255.0, alpha: 0.8) self.addSubview(label) } } /** * Draw y labels. */ private func drawYLabels() { var yValue: CGFloat let (start, stop, step) = self.y.ticks for var i: CGFloat = start; i <= stop; i += step { yValue = self.bounds.height - self.y.scale(i) - (y.axis.inset * 1.5) let label = UILabel(frame: CGRect(x: 0, y: yValue, width: y.axis.inset, height: y.axis.inset)) label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) label.textAlignment = .Center label.text = String(Int(round(i))) label.textColor = UIColor(red: 255/255.0, green: 225/255.0, blue: 255/255.0, alpha: 0.8) self.addSubview(label) } } /** * Add line chart */ public func addLine(data: [CGFloat]) { self.dataStore.append(data) self.setNeedsDisplay() } /** * Make whole thing white again. */ public func clearAll() { self.removeAll = true clear() self.setNeedsDisplay() self.removeAll = false } /** * Remove charts, areas and labels but keep axis and grid. */ public func clear() { // clear data dataStore.removeAll() self.setNeedsDisplay() } } /** * DotCALayer */ class DotCALayer: CALayer { var innerRadius: CGFloat = 8 var dotInnerColor = UIColor.blackColor() override init() { super.init() } override init(layer: AnyObject) { super.init(layer: layer) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSublayers() { super.layoutSublayers() let inset = self.bounds.size.width - innerRadius let innerDotLayer = CALayer() innerDotLayer.frame = CGRectInset(self.bounds, inset/2, inset/2) innerDotLayer.backgroundColor = dotInnerColor.CGColor innerDotLayer.cornerRadius = innerRadius / 2 self.addSublayer(innerDotLayer) } } /** * LinearScale */ public class LinearScale { var domain: [CGFloat] var range: [CGFloat] public init(domain: [CGFloat] = [0, 1], range: [CGFloat] = [0, 1]) { self.domain = domain self.range = range } public func scale() -> (x: CGFloat) -> CGFloat { return bilinear(domain, range: range, uninterpolate: uninterpolate, interpolate: interpolate) } public func invert() -> (x: CGFloat) -> CGFloat { return bilinear(range, range: domain, uninterpolate: uninterpolate, interpolate: interpolate) } public func ticks(m: Int) -> (CGFloat, CGFloat, CGFloat) { return scale_linearTicks(domain, m: m) } private func scale_linearTicks(domain: [CGFloat], m: Int) -> (CGFloat, CGFloat, CGFloat) { return scale_linearTickRange(domain, m: m) } private func scale_linearTickRange(domain: [CGFloat], m: Int) -> (CGFloat, CGFloat, CGFloat) { var extent = scaleExtent(domain) let span = extent[1] - extent[0] var step = CGFloat(pow(10, floor(log(Double(span) / Double(m)) / M_LN10))) let err = CGFloat(m) / span * step // Filter ticks to get closer to the desired count. if (err <= 0.15) { step *= 10 } else if (err <= 0.35) { step *= 5 } else if (err <= 0.75) { step *= 2 } // Round start and stop values to step interval. let start = ceil(extent[0] / step) * step let stop = floor(extent[1] / step) * step + step * 0.5 // inclusive return (start, stop, step) } private func scaleExtent(domain: [CGFloat]) -> [CGFloat] { let start = domain[0] let stop = domain[domain.count - 1] return start < stop ? [start, stop] : [stop, start] } private func interpolate(a: CGFloat, b: CGFloat) -> (c: CGFloat) -> CGFloat { var diff = b - a func f(c: CGFloat) -> CGFloat { return (a + diff) * c } return f } private func uninterpolate(a: CGFloat, b: CGFloat) -> (c: CGFloat) -> CGFloat { var diff = b - a var re = diff != 0 ? 1 / diff : 0 func f(c: CGFloat) -> CGFloat { return (c - a) * re } return f } private func bilinear(domain: [CGFloat], range: [CGFloat], uninterpolate: (a: CGFloat, b: CGFloat) -> (c: CGFloat) -> CGFloat, interpolate: (a: CGFloat, b: CGFloat) -> (c: CGFloat) -> CGFloat) -> (c: CGFloat) -> CGFloat { var u: (c: CGFloat) -> CGFloat = uninterpolate(a: domain[0], b: domain[1]) var i: (c: CGFloat) -> CGFloat = interpolate(a: range[0], b: range[1]) func f(d: CGFloat) -> CGFloat { return i(c: u(c: d)) } return f } }
apache-2.0
f4e8790f84b343284cc940a813108e0e
31.042199
225
0.550625
4.069677
false
false
false
false
segmentio/analytics-swift
Examples/other_plugins/ConsoleLogger.swift
1
2486
// // ConsoleLogger.swift // SegmentUIKitExample // // Created by Brandon Sneed on 4/9/21. // // NOTE: You can see this plugin in use in the SwiftUIKitExample application. // // This plugin is NOT SUPPORTED by Segment. It is here merely as an example, // and for your convenience should you find it useful. // MIT License // // Copyright (c) 2021 Segment // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Segment /** A generic console logging plugin. The type `.after` signifies that this plugin will run at the end of the event timeline, at which point it will print event data to the Xcode console window. */ class ConsoleLogger: Plugin { let type = PluginType.after let name: String weak var analytics: Analytics? = nil var identifier: String? = nil required init(name: String) { self.name = name } // we want to log every event, so lets override `execute`. func execute<T: RawEvent>(event: T?) -> T? { if let json = event?.prettyPrint() { analytics?.log(message: "event received on instance: \(name)") analytics?.log(message: "\(json)\n") } return event } // we also want to know when settings are retrieved or changed. func update(settings: Settings) { let json = settings.prettyPrint() analytics?.log(message: "settings updated on instance: \(name)\nPayload: \(json)") } }
mit
8d9c5b02206fd8eb7115851d5ba611f6
35.558824
107
0.700322
4.369069
false
false
false
false
apple/swift-tools-support-core
Sources/TSCBasic/Process.swift
1
44509
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 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 protocol Foundation.CustomNSError import var Foundation.NSLocalizedDescriptionKey import class Foundation.NSLock import class Foundation.ProcessInfo #if os(Windows) import Foundation #endif @_implementationOnly import TSCclibc import TSCLibc import Dispatch /// Process result data which is available after process termination. public struct ProcessResult: CustomStringConvertible { public enum Error: Swift.Error { /// The output is not a valid UTF8 sequence. case illegalUTF8Sequence /// The process had a non zero exit. case nonZeroExit(ProcessResult) } public enum ExitStatus: Equatable { /// The process was terminated normally with a exit code. case terminated(code: Int32) #if os(Windows) /// The process was terminated abnormally. case abnormal(exception: UInt32) #else /// The process was terminated due to a signal. case signalled(signal: Int32) #endif } /// The arguments with which the process was launched. public let arguments: [String] /// The environment with which the process was launched. public let environment: [String: String] /// The exit status of the process. public let exitStatus: ExitStatus /// The output bytes of the process. Available only if the process was /// asked to redirect its output and no stdout output closure was set. public let output: Result<[UInt8], Swift.Error> /// The output bytes of the process. Available only if the process was /// asked to redirect its output and no stderr output closure was set. public let stderrOutput: Result<[UInt8], Swift.Error> /// Create an instance using a POSIX process exit status code and output result. /// /// See `waitpid(2)` for information on the exit status code. public init( arguments: [String], environment: [String: String], exitStatusCode: Int32, normal: Bool, output: Result<[UInt8], Swift.Error>, stderrOutput: Result<[UInt8], Swift.Error> ) { let exitStatus: ExitStatus #if os(Windows) if normal { exitStatus = .terminated(code: exitStatusCode) } else { exitStatus = .abnormal(exception: UInt32(exitStatusCode)) } #else if WIFSIGNALED(exitStatusCode) { exitStatus = .signalled(signal: WTERMSIG(exitStatusCode)) } else { precondition(WIFEXITED(exitStatusCode), "unexpected exit status \(exitStatusCode)") exitStatus = .terminated(code: WEXITSTATUS(exitStatusCode)) } #endif self.init(arguments: arguments, environment: environment, exitStatus: exitStatus, output: output, stderrOutput: stderrOutput) } /// Create an instance using an exit status and output result. public init( arguments: [String], environment: [String: String], exitStatus: ExitStatus, output: Result<[UInt8], Swift.Error>, stderrOutput: Result<[UInt8], Swift.Error> ) { self.arguments = arguments self.environment = environment self.output = output self.stderrOutput = stderrOutput self.exitStatus = exitStatus } /// Converts stdout output bytes to string, assuming they're UTF8. public func utf8Output() throws -> String { return String(decoding: try output.get(), as: Unicode.UTF8.self) } /// Converts stderr output bytes to string, assuming they're UTF8. public func utf8stderrOutput() throws -> String { return String(decoding: try stderrOutput.get(), as: Unicode.UTF8.self) } public var description: String { return """ <ProcessResult: exit: \(exitStatus), output: \((try? utf8Output()) ?? "") > """ } } /// Process allows spawning new subprocesses and working with them. /// /// Note: This class is thread safe. public final class Process { /// Errors when attempting to invoke a process public enum Error: Swift.Error { /// The program requested to be executed cannot be found on the existing search paths, or is not executable. case missingExecutableProgram(program: String) /// The current OS does not support the workingDirectory API. case workingDirectoryNotSupported } public enum OutputRedirection { /// Do not redirect the output case none /// Collect stdout and stderr output and provide it back via ProcessResult object. If redirectStderr is true, /// stderr be redirected to stdout. case collect(redirectStderr: Bool) /// Stream stdout and stderr via the corresponding closures. If redirectStderr is true, stderr be redirected to /// stdout. case stream(stdout: OutputClosure, stderr: OutputClosure, redirectStderr: Bool) /// Default collect OutputRedirection that defaults to not redirect stderr. Provided for API compatibility. public static let collect: OutputRedirection = .collect(redirectStderr: false) /// Default stream OutputRedirection that defaults to not redirect stderr. Provided for API compatibility. public static func stream(stdout: @escaping OutputClosure, stderr: @escaping OutputClosure) -> Self { return .stream(stdout: stdout, stderr: stderr, redirectStderr: false) } public var redirectsOutput: Bool { switch self { case .none: return false case .collect, .stream: return true } } public var outputClosures: (stdoutClosure: OutputClosure, stderrClosure: OutputClosure)? { switch self { case let .stream(stdoutClosure, stderrClosure, _): return (stdoutClosure: stdoutClosure, stderrClosure: stderrClosure) case .collect, .none: return nil } } public var redirectStderr: Bool { switch self { case let .collect(redirectStderr): return redirectStderr case let .stream(_, _, redirectStderr): return redirectStderr default: return false } } } // process execution mutable state private enum State { case idle case readingOutput(sync: DispatchGroup) case outputReady(stdout: Result<[UInt8], Swift.Error>, stderr: Result<[UInt8], Swift.Error>) case complete(ProcessResult) case failed(Swift.Error) } /// Typealias for process id type. #if !os(Windows) public typealias ProcessID = pid_t #else public typealias ProcessID = DWORD #endif /// Typealias for stdout/stderr output closure. public typealias OutputClosure = ([UInt8]) -> Void /// Typealias for logging handling closure public typealias LoggingHandler = (String) -> Void private static var _loggingHandler: LoggingHandler? private static let loggingHandlerLock = NSLock() /// Global logging handler. Use with care! preferably use instance level instead of setting one globally. public static var loggingHandler: LoggingHandler? { get { Self.loggingHandlerLock.withLock { self._loggingHandler } } set { Self.loggingHandlerLock.withLock { self._loggingHandler = newValue } } } // deprecated 2/2022, remove once client migrate to logging handler @available(*, deprecated) public static var verbose: Bool { get { Self.loggingHandler != nil } set { Self.loggingHandler = newValue ? Self.logToStdout: .none } } private var _loggingHandler: LoggingHandler? // the log and setter are only required to backward support verbose setter. // remove and make loggingHandler a let property once verbose is deprecated private let loggingHandlerLock = NSLock() public private(set) var loggingHandler: LoggingHandler? { get { self.loggingHandlerLock.withLock { self._loggingHandler } } set { self.loggingHandlerLock.withLock { self._loggingHandler = newValue } } } // deprecated 2/2022, remove once client migrate to logging handler // also simplify loggingHandler (see above) once this is removed @available(*, deprecated) public var verbose: Bool { get { self.loggingHandler != nil } set { self.loggingHandler = newValue ? Self.logToStdout : .none } } /// The current environment. @available(*, deprecated, message: "use ProcessEnv.vars instead") static public var env: [String: String] { return ProcessInfo.processInfo.environment } /// The arguments to execute. public let arguments: [String] /// The environment with which the process was executed. public let environment: [String: String] /// The path to the directory under which to run the process. public let workingDirectory: AbsolutePath? /// The process id of the spawned process, available after the process is launched. #if os(Windows) private var _process: Foundation.Process? public var processID: ProcessID { return DWORD(_process?.processIdentifier ?? 0) } #else public private(set) var processID = ProcessID() #endif // process execution mutable state private var state: State = .idle private let stateLock = NSLock() private static let sharedCompletionQueue = DispatchQueue(label: "org.swift.tools-support-core.process-completion") private var completionQueue = Process.sharedCompletionQueue /// The result of the process execution. Available after process is terminated. /// This will block while the process is awaiting result @available(*, deprecated, message: "use waitUntilExit instead") public var result: ProcessResult? { return self.stateLock.withLock { switch self.state { case .complete(let result): return result default: return nil } } } // ideally we would use the state for this, but we need to access it while the waitForExit is locking state private var _launched = false private let launchedLock = NSLock() public var launched: Bool { return self.launchedLock.withLock { return self._launched } } /// How process redirects its output. public let outputRedirection: OutputRedirection /// Indicates if a new progress group is created for the child process. private let startNewProcessGroup: Bool /// Cache of validated executables. /// /// Key: Executable name or path. /// Value: Path to the executable, if found. private static var validatedExecutablesMap = [String: AbsolutePath?]() private static let validatedExecutablesMapLock = NSLock() /// Create a new process instance. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - workingDirectory: The path to the directory under which to run the process. /// - outputRedirection: How process redirects its output. Default value is .collect. /// - startNewProcessGroup: If true, a new progress group is created for the child making it /// continue running even if the parent is killed or interrupted. Default value is true. /// - loggingHandler: Handler for logging messages /// @available(macOS 10.15, *) public init( arguments: [String], environment: [String: String] = ProcessEnv.vars, workingDirectory: AbsolutePath, outputRedirection: OutputRedirection = .collect, startNewProcessGroup: Bool = true, loggingHandler: LoggingHandler? = .none ) { self.arguments = arguments self.environment = environment self.workingDirectory = workingDirectory self.outputRedirection = outputRedirection self.startNewProcessGroup = startNewProcessGroup self.loggingHandler = loggingHandler ?? Process.loggingHandler } // deprecated 2/2022 @_disfavoredOverload @available(*, deprecated, message: "use version without verbosity flag") @available(macOS 10.15, *) public convenience init( arguments: [String], environment: [String: String] = ProcessEnv.vars, workingDirectory: AbsolutePath, outputRedirection: OutputRedirection = .collect, verbose: Bool, startNewProcessGroup: Bool = true ) { self.init( arguments: arguments, environment: environment, workingDirectory: workingDirectory, outputRedirection: outputRedirection, startNewProcessGroup: startNewProcessGroup, loggingHandler: verbose ? { message in stdoutStream <<< message <<< "\n" stdoutStream.flush() } : nil ) } /// Create a new process instance. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - outputRedirection: How process redirects its output. Default value is .collect. /// - verbose: If true, launch() will print the arguments of the subprocess before launching it. /// - startNewProcessGroup: If true, a new progress group is created for the child making it /// continue running even if the parent is killed or interrupted. Default value is true. /// - loggingHandler: Handler for logging messages public init( arguments: [String], environment: [String: String] = ProcessEnv.vars, outputRedirection: OutputRedirection = .collect, startNewProcessGroup: Bool = true, loggingHandler: LoggingHandler? = .none ) { self.arguments = arguments self.environment = environment self.workingDirectory = nil self.outputRedirection = outputRedirection self.startNewProcessGroup = startNewProcessGroup self.loggingHandler = loggingHandler ?? Process.loggingHandler } @_disfavoredOverload @available(*, deprecated, message: "use version without verbosity flag") public convenience init( arguments: [String], environment: [String: String] = ProcessEnv.vars, outputRedirection: OutputRedirection = .collect, verbose: Bool = Process.verbose, startNewProcessGroup: Bool = true ) { self.init( arguments: arguments, environment: environment, outputRedirection: outputRedirection, startNewProcessGroup: startNewProcessGroup, loggingHandler: verbose ? Self.logToStdout : .none ) } public convenience init( args: String..., environment: [String: String] = ProcessEnv.vars, outputRedirection: OutputRedirection = .collect, loggingHandler: LoggingHandler? = .none ) { self.init( arguments: args, environment: environment, outputRedirection: outputRedirection, loggingHandler: loggingHandler ) } /// Returns the path of the the given program if found in the search paths. /// /// The program can be executable name, relative path or absolute path. public static func findExecutable( _ program: String, workingDirectory: AbsolutePath? = nil ) -> AbsolutePath? { if let abs = try? AbsolutePath(validating: program) { return abs } let cwdOpt = workingDirectory ?? localFileSystem.currentWorkingDirectory // The program might be a multi-component relative path. if let rel = try? RelativePath(validating: program), rel.components.count > 1 { if let cwd = cwdOpt { let abs = AbsolutePath(cwd, rel) if localFileSystem.isExecutableFile(abs) { return abs } } return nil } // From here on out, the program is an executable name, i.e. it doesn't contain a "/" let lookup: () -> AbsolutePath? = { let envSearchPaths = getEnvSearchPaths( pathString: ProcessEnv.path, currentWorkingDirectory: cwdOpt ) let value = lookupExecutablePath( filename: program, currentWorkingDirectory: cwdOpt, searchPaths: envSearchPaths ) return value } // This should cover the most common cases, i.e. when the cache is most helpful. if workingDirectory == localFileSystem.currentWorkingDirectory { return Process.validatedExecutablesMapLock.withLock { if let value = Process.validatedExecutablesMap[program] { return value } let value = lookup() Process.validatedExecutablesMap[program] = value return value } } else { return lookup() } } /// Launch the subprocess. Returns a WritableByteStream object that can be used to communicate to the process's /// stdin. If needed, the stream can be closed using the close() API. Otherwise, the stream will be closed /// automatically. @discardableResult public func launch() throws -> WritableByteStream { precondition(arguments.count > 0 && !arguments[0].isEmpty, "Need at least one argument to launch the process.") self.launchedLock.withLock { precondition(!self._launched, "It is not allowed to launch the same process object again.") self._launched = true } // Print the arguments if we are verbose. if let loggingHandler = self.loggingHandler { loggingHandler(arguments.map({ $0.spm_shellEscaped() }).joined(separator: " ")) } // Look for executable. let executable = arguments[0] guard let executablePath = Process.findExecutable(executable, workingDirectory: workingDirectory) else { throw Process.Error.missingExecutableProgram(program: executable) } #if os(Windows) let process = Foundation.Process() _process = process process.arguments = Array(arguments.dropFirst()) // Avoid including the executable URL twice. process.executableURL = executablePath.asURL process.environment = environment let stdinPipe = Pipe() process.standardInput = stdinPipe let group = DispatchGroup() var stdout: [UInt8] = [] let stdoutLock = Lock() var stderr: [UInt8] = [] let stderrLock = Lock() if outputRedirection.redirectsOutput { let stdoutPipe = Pipe() let stderrPipe = Pipe() group.enter() stdoutPipe.fileHandleForReading.readabilityHandler = { (fh : FileHandle) -> Void in let data = fh.availableData if (data.count == 0) { stdoutPipe.fileHandleForReading.readabilityHandler = nil group.leave() } else { let contents = data.withUnsafeBytes { Array<UInt8>($0) } self.outputRedirection.outputClosures?.stdoutClosure(contents) stdoutLock.withLock { stdout += contents } } } group.enter() stderrPipe.fileHandleForReading.readabilityHandler = { (fh : FileHandle) -> Void in let data = fh.availableData if (data.count == 0) { stderrPipe.fileHandleForReading.readabilityHandler = nil group.leave() } else { let contents = data.withUnsafeBytes { Array<UInt8>($0) } self.outputRedirection.outputClosures?.stderrClosure(contents) stderrLock.withLock { stderr += contents } } } process.standardOutput = stdoutPipe process.standardError = stderrPipe } // first set state then start reading threads let sync = DispatchGroup() sync.enter() self.stateLock.withLock { self.state = .readingOutput(sync: sync) } group.notify(queue: self.completionQueue) { self.stateLock.withLock { self.state = .outputReady(stdout: .success(stdout), stderr: .success(stderr)) } sync.leave() } try process.run() return stdinPipe.fileHandleForWriting #elseif (!canImport(Darwin) || os(macOS)) // Initialize the spawn attributes. #if canImport(Darwin) || os(Android) || os(OpenBSD) var attributes: posix_spawnattr_t? = nil #else var attributes = posix_spawnattr_t() #endif posix_spawnattr_init(&attributes) defer { posix_spawnattr_destroy(&attributes) } // Unmask all signals. var noSignals = sigset_t() sigemptyset(&noSignals) posix_spawnattr_setsigmask(&attributes, &noSignals) // Reset all signals to default behavior. #if canImport(Darwin) var mostSignals = sigset_t() sigfillset(&mostSignals) sigdelset(&mostSignals, SIGKILL) sigdelset(&mostSignals, SIGSTOP) posix_spawnattr_setsigdefault(&attributes, &mostSignals) #else // On Linux, this can only be used to reset signals that are legal to // modify, so we have to take care about the set we use. var mostSignals = sigset_t() sigemptyset(&mostSignals) for i in 1 ..< SIGSYS { if i == SIGKILL || i == SIGSTOP { continue } sigaddset(&mostSignals, i) } posix_spawnattr_setsigdefault(&attributes, &mostSignals) #endif // Set the attribute flags. var flags = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF if startNewProcessGroup { // Establish a separate process group. flags |= POSIX_SPAWN_SETPGROUP posix_spawnattr_setpgroup(&attributes, 0) } posix_spawnattr_setflags(&attributes, Int16(flags)) // Setup the file actions. #if canImport(Darwin) || os(Android) || os(OpenBSD) var fileActions: posix_spawn_file_actions_t? = nil #else var fileActions = posix_spawn_file_actions_t() #endif posix_spawn_file_actions_init(&fileActions) defer { posix_spawn_file_actions_destroy(&fileActions) } if let workingDirectory = workingDirectory?.pathString { #if canImport(Darwin) // The only way to set a workingDirectory is using an availability-gated initializer, so we don't need // to handle the case where the posix_spawn_file_actions_addchdir_np method is unavailable. This check only // exists here to make the compiler happy. if #available(macOS 10.15, *) { posix_spawn_file_actions_addchdir_np(&fileActions, workingDirectory) } #elseif os(Linux) guard SPM_posix_spawn_file_actions_addchdir_np_supported() else { throw Process.Error.workingDirectoryNotSupported } SPM_posix_spawn_file_actions_addchdir_np(&fileActions, workingDirectory) #else throw Process.Error.workingDirectoryNotSupported #endif } var stdinPipe: [Int32] = [-1, -1] try open(pipe: &stdinPipe) let stdinStream = try LocalFileOutputByteStream(filePointer: fdopen(stdinPipe[1], "wb"), closeOnDeinit: true) // Dupe the read portion of the remote to 0. posix_spawn_file_actions_adddup2(&fileActions, stdinPipe[0], 0) // Close the other side's pipe since it was dupped to 0. posix_spawn_file_actions_addclose(&fileActions, stdinPipe[0]) posix_spawn_file_actions_addclose(&fileActions, stdinPipe[1]) var outputPipe: [Int32] = [-1, -1] var stderrPipe: [Int32] = [-1, -1] if outputRedirection.redirectsOutput { // Open the pipe. try open(pipe: &outputPipe) // Open the write end of the pipe. posix_spawn_file_actions_adddup2(&fileActions, outputPipe[1], 1) // Close the other ends of the pipe since they were dupped to 1. posix_spawn_file_actions_addclose(&fileActions, outputPipe[0]) posix_spawn_file_actions_addclose(&fileActions, outputPipe[1]) if outputRedirection.redirectStderr { // If merged was requested, send stderr to stdout. posix_spawn_file_actions_adddup2(&fileActions, 1, 2) } else { // If no redirect was requested, open the pipe for stderr. try open(pipe: &stderrPipe) posix_spawn_file_actions_adddup2(&fileActions, stderrPipe[1], 2) // Close the other ends of the pipe since they were dupped to 2. posix_spawn_file_actions_addclose(&fileActions, stderrPipe[0]) posix_spawn_file_actions_addclose(&fileActions, stderrPipe[1]) } } else { posix_spawn_file_actions_adddup2(&fileActions, 1, 1) posix_spawn_file_actions_adddup2(&fileActions, 2, 2) } var resolvedArgs = arguments if workingDirectory != nil { resolvedArgs[0] = executablePath.pathString } let argv = CStringArray(resolvedArgs) let env = CStringArray(environment.map({ "\($0.0)=\($0.1)" })) let rv = posix_spawnp(&processID, argv.cArray[0]!, &fileActions, &attributes, argv.cArray, env.cArray) guard rv == 0 else { throw SystemError.posix_spawn(rv, arguments) } // Close the local read end of the input pipe. try close(fd: stdinPipe[0]) let group = DispatchGroup() if !outputRedirection.redirectsOutput { // no stdout or stderr in this case self.stateLock.withLock { self.state = .outputReady(stdout: .success([]), stderr: .success([])) } } else { var pending: Result<[UInt8], Swift.Error>? let pendingLock = NSLock() let outputClosures = outputRedirection.outputClosures // Close the local write end of the output pipe. try close(fd: outputPipe[1]) // Create a thread and start reading the output on it. group.enter() let stdoutThread = Thread { [weak self] in if let readResult = self?.readOutput(onFD: outputPipe[0], outputClosure: outputClosures?.stdoutClosure) { pendingLock.withLock { if let stderrResult = pending { self?.stateLock.withLock { self?.state = .outputReady(stdout: readResult, stderr: stderrResult) } } else { pending = readResult } } group.leave() } else if let stderrResult = (pendingLock.withLock { pending }) { // TODO: this is more of an error self?.stateLock.withLock { self?.state = .outputReady(stdout: .success([]), stderr: stderrResult) } group.leave() } } // Only schedule a thread for stderr if no redirect was requested. var stderrThread: Thread? = nil if !outputRedirection.redirectStderr { // Close the local write end of the stderr pipe. try close(fd: stderrPipe[1]) // Create a thread and start reading the stderr output on it. group.enter() stderrThread = Thread { [weak self] in if let readResult = self?.readOutput(onFD: stderrPipe[0], outputClosure: outputClosures?.stderrClosure) { pendingLock.withLock { if let stdoutResult = pending { self?.stateLock.withLock { self?.state = .outputReady(stdout: stdoutResult, stderr: readResult) } } else { pending = readResult } } group.leave() } else if let stdoutResult = (pendingLock.withLock { pending }) { // TODO: this is more of an error self?.stateLock.withLock { self?.state = .outputReady(stdout: stdoutResult, stderr: .success([])) } group.leave() } } } else { pendingLock.withLock { pending = .success([]) // no stderr in this case } } // first set state then start reading threads self.stateLock.withLock { self.state = .readingOutput(sync: group) } stdoutThread.start() stderrThread?.start() } return stdinStream #else preconditionFailure("Process spawning is not available") #endif // POSIX implementation } /// Blocks the calling process until the subprocess finishes execution. @discardableResult public func waitUntilExit() throws -> ProcessResult { let group = DispatchGroup() group.enter() var processResult : Result<ProcessResult, Swift.Error>? self.waitUntilExit() { result in processResult = result group.leave() } group.wait() return try processResult.unsafelyUnwrapped.get() } /// Executes the process I/O state machine, calling completion block when finished. private func waitUntilExit(_ completion: @escaping (Result<ProcessResult, Swift.Error>) -> Void) { self.stateLock.lock() switch self.state { case .idle: defer { self.stateLock.unlock() } preconditionFailure("The process is not yet launched.") case .complete(let result): self.stateLock.unlock() completion(.success(result)) case .failed(let error): self.stateLock.unlock() completion(.failure(error)) case .readingOutput(let sync): self.stateLock.unlock() sync.notify(queue: self.completionQueue) { self.waitUntilExit(completion) } case .outputReady(let stdoutResult, let stderrResult): defer { self.stateLock.unlock() } // Wait until process finishes execution. #if os(Windows) precondition(_process != nil, "The process is not yet launched.") let p = _process! p.waitUntilExit() let exitStatusCode = p.terminationStatus let normalExit = p.terminationReason == .exit #else var exitStatusCode: Int32 = 0 var result = waitpid(processID, &exitStatusCode, 0) while result == -1 && errno == EINTR { result = waitpid(processID, &exitStatusCode, 0) } if result == -1 { self.state = .failed(SystemError.waitpid(errno)) } let normalExit = !WIFSIGNALED(result) #endif // Construct the result. let executionResult = ProcessResult( arguments: arguments, environment: environment, exitStatusCode: exitStatusCode, normal: normalExit, output: stdoutResult, stderrOutput: stderrResult ) self.state = .complete(executionResult) self.completionQueue.async { self.waitUntilExit(completion) } } } #if !os(Windows) /// Reads the given fd and returns its result. /// /// Closes the fd before returning. private func readOutput(onFD fd: Int32, outputClosure: OutputClosure?) -> Result<[UInt8], Swift.Error> { // Read all of the data from the output pipe. let N = 4096 var buf = [UInt8](repeating: 0, count: N + 1) var out = [UInt8]() var error: Swift.Error? = nil loop: while true { let n = read(fd, &buf, N) switch n { case -1: if errno == EINTR { continue } else { error = SystemError.read(errno) break loop } case 0: // Close the read end of the output pipe. // We should avoid closing the read end of the pipe in case // -1 because the child process may still have content to be // flushed into the write end of the pipe. If the read end of the // pipe is closed, then a write will cause a SIGPIPE signal to // be generated for the calling process. If the calling process is // ignoring this signal, then write fails with the error EPIPE. close(fd) break loop default: let data = buf[0..<n] if let outputClosure = outputClosure { outputClosure(Array(data)) } else { out += data } } } // Construct the output result. return error.map(Result.failure) ?? .success(out) } #endif /// Send a signal to the process. /// /// Note: This will signal all processes in the process group. public func signal(_ signal: Int32) { #if os(Windows) if signal == SIGINT { _process?.interrupt() } else { _process?.terminate() } #else assert(self.launched, "The process is not yet launched.") _ = TSCLibc.kill(startNewProcessGroup ? -processID : processID, signal) #endif } } extension Process { /// Execute a subprocess and calls completion block when it finishes execution /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - loggingHandler: Handler for logging messages /// - queue: Queue to use for callbacks /// - completion: A completion handler to return the process result static public func popen( arguments: [String], environment: [String: String] = ProcessEnv.vars, loggingHandler: LoggingHandler? = .none, queue: DispatchQueue? = nil, completion: @escaping (Result<ProcessResult, Swift.Error>) -> Void ) { let completionQueue = queue ?? Self.sharedCompletionQueue do { let process = Process( arguments: arguments, environment: environment, outputRedirection: .collect, loggingHandler: loggingHandler ) process.completionQueue = completionQueue try process.launch() process.waitUntilExit(completion) } catch { completionQueue.async { completion(.failure(error)) } } } /// Execute a subprocess and block until it finishes execution /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - loggingHandler: Handler for logging messages /// - Returns: The process result. @discardableResult static public func popen( arguments: [String], environment: [String: String] = ProcessEnv.vars, loggingHandler: LoggingHandler? = .none ) throws -> ProcessResult { let process = Process( arguments: arguments, environment: environment, outputRedirection: .collect, loggingHandler: loggingHandler ) try process.launch() return try process.waitUntilExit() } /// Execute a subprocess and block until it finishes execution /// /// - Parameters: /// - args: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - loggingHandler: Handler for logging messages /// - Returns: The process result. @discardableResult static public func popen( args: String..., environment: [String: String] = ProcessEnv.vars, loggingHandler: LoggingHandler? = .none ) throws -> ProcessResult { return try Process.popen(arguments: args, environment: environment, loggingHandler: loggingHandler) } /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - loggingHandler: Handler for logging messages /// - Returns: The process output (stdout + stderr). @discardableResult static public func checkNonZeroExit( arguments: [String], environment: [String: String] = ProcessEnv.vars, loggingHandler: LoggingHandler? = .none ) throws -> String { let process = Process( arguments: arguments, environment: environment, outputRedirection: .collect, loggingHandler: loggingHandler ) try process.launch() let result = try process.waitUntilExit() // Throw if there was a non zero termination. guard result.exitStatus == .terminated(code: 0) else { throw ProcessResult.Error.nonZeroExit(result) } return try result.utf8Output() } /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - loggingHandler: Handler for logging messages /// - Returns: The process output (stdout + stderr). @discardableResult static public func checkNonZeroExit( args: String..., environment: [String: String] = ProcessEnv.vars, loggingHandler: LoggingHandler? = .none ) throws -> String { return try checkNonZeroExit(arguments: args, environment: environment, loggingHandler: loggingHandler) } } extension Process: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } public static func == (lhs: Process, rhs: Process) -> Bool { ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } } // MARK: - Private helpers #if !os(Windows) #if canImport(Darwin) private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t? #else private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t #endif private func WIFEXITED(_ status: Int32) -> Bool { return _WSTATUS(status) == 0 } private func _WSTATUS(_ status: Int32) -> Int32 { return status & 0x7f } private func WIFSIGNALED(_ status: Int32) -> Bool { return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f) } private func WEXITSTATUS(_ status: Int32) -> Int32 { return (status >> 8) & 0xff } private func WTERMSIG(_ status: Int32) -> Int32 { return status & 0x7f } /// Open the given pipe. private func open(pipe: inout [Int32]) throws { let rv = TSCLibc.pipe(&pipe) guard rv == 0 else { throw SystemError.pipe(rv) } } /// Close the given fd. private func close(fd: Int32) throws { func innerClose(_ fd: inout Int32) throws { let rv = TSCLibc.close(fd) guard rv == 0 else { throw SystemError.close(rv) } } var innerFd = fd try innerClose(&innerFd) } extension Process.Error: CustomStringConvertible { public var description: String { switch self { case .missingExecutableProgram(let program): return "could not find executable for '\(program)'" case .workingDirectoryNotSupported: return "workingDirectory is not supported in this platform" } } } extension Process.Error: CustomNSError { public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: self.description] } } #endif extension ProcessResult.Error: CustomStringConvertible { public var description: String { switch self { case .illegalUTF8Sequence: return "illegal UTF8 sequence output" case .nonZeroExit(let result): let stream = BufferedOutputByteStream() switch result.exitStatus { case .terminated(let code): stream <<< "terminated(\(code)): " #if os(Windows) case .abnormal(let exception): stream <<< "abnormal(\(exception)): " #else case .signalled(let signal): stream <<< "signalled(\(signal)): " #endif } // Strip sandbox information from arguments to keep things pretty. var args = result.arguments // This seems a little fragile. if args.first == "sandbox-exec", args.count > 3 { args = args.suffix(from: 3).map({$0}) } stream <<< args.map({ $0.spm_shellEscaped() }).joined(separator: " ") // Include the output, if present. if let output = try? result.utf8Output() + result.utf8stderrOutput() { // We indent the output to keep it visually separated from everything else. let indentation = " " stream <<< " output:\n" <<< indentation <<< output.replacingOccurrences(of: "\n", with: "\n" + indentation) if !output.hasSuffix("\n") { stream <<< "\n" } } return stream.bytes.description } } } #if os(Windows) extension FileHandle: WritableByteStream { public var position: Int { return Int(offsetInFile) } public func write(_ byte: UInt8) { write(Data([byte])) } public func write<C: Collection>(_ bytes: C) where C.Element == UInt8 { write(Data(bytes)) } public func flush() { synchronizeFile() } } #endif extension Process { @available(*, deprecated) fileprivate static func logToStdout(_ message: String) { stdoutStream <<< message <<< "\n" stdoutStream.flush() } }
apache-2.0
174557daca6cfcf58a9fff8aa7f10451
35.723597
125
0.596531
4.925741
false
false
false
false
Shvier/Dota2Helper
Dota2Helper/Dota2Helper/Global/View/UISegmentedMenu.swift
1
6819
// // UISegmentedMenu.swift // SimplerSegmentMenu // // Created by Shvier on 9/30/16. // Copyright © 2016 Shvier. All rights reserved. // import UIKit public protocol UISegmentedMenuDelegate { func segmentedMenu(didSelectIndex index: NSInteger) } public enum UISegmentedMenuType: Int { // button width by text case plain // button width by avarage case fill } let defaultFontSize: CGFloat = 16 let highlightFontSize: CGFloat = 18 let kTag: NSInteger = 1000 let kDivideViewHeight: CGFloat = 4 public class UISegmentedMenu: UIView { public var titleDataSource: NSArray? public var contentDataSource: NSArray? let min = { (float1: CGFloat, float2: CGFloat) -> CGFloat in return float1 > float2 ? float2 : float1 } let max = { (float1: CGFloat, float2: CGFloat) -> CGFloat in return float1 > float2 ? float1 : float2 } var contentView: UIScrollView? var selectedIndex: NSInteger? var delegate: UISegmentedMenuDelegate? var divideView: UIView? var divideLineView: UIView? var font: UIFont? var selectIndex: NSInteger? var widthArray: NSArray? var totalWidth: CGFloat? var type: UISegmentedMenuType? public func updateContentDateSource(contentDataSource: NSArray?) { self.contentDataSource = contentDataSource } public func updateTitleDataSource(titleDataSource: NSArray?, selectedIndex: NSInteger) { let widthArray: NSMutableArray = NSMutableArray() self.titleDataSource = titleDataSource var totalWidth: CGFloat = 0 var index: NSInteger = 0 for title in self.titleDataSource as! [String] { var buttonWidth: CGFloat switch self.type! { case .plain: buttonWidth = title.sizeOfContent(font: font!).width + 20 break; case .fill: buttonWidth = self.bounds.size.width/CGFloat((self.titleDataSource?.count)!) break; } widthArray.add(NSNumber(value: Float(buttonWidth))) let button: UIButton = UIButton(frame: CGRect(x: totalWidth, y: 0, width: buttonWidth, height: bounds.size.height)) button.tag = kTag + index button.setTitleColor(.black, for: .normal) button.setTitleColor(.red, for: .selected) button.setTitle(title, for: .normal) button.addTarget(self, action: #selector(self.clickSegmentedButton(button:)), for: .touchUpInside) button.titleLabel?.font = font self.contentView?.addSubview(button) totalWidth += buttonWidth if index == selectedIndex { button.isSelected = true divideView?.frame = CGRect(x: 0, y: (contentView?.bounds.size.height)! - kDivideViewHeight, width: buttonWidth, height: kDivideViewHeight) self.selectedIndex = selectedIndex } index += 1 } self.widthArray = NSArray(array: widthArray) self.totalWidth = totalWidth self.contentView?.contentSize = CGSize(width: totalWidth, height: 0) self.divideLineView?.frame = CGRect(x: 0, y: (self.contentView?.bounds.size.height)! - kDivideViewHeight, width: totalWidth, height: kDivideViewHeight) self.didSelectIndex(index: selectedIndex) } public func currentSelectedIndex() -> NSInteger { return selectedIndex ?? 0 } public func currentSelectedButton() -> UIButton { return self.contentView?.viewWithTag(selectedIndex! + kTag) as! UIButton } @objc func clickSegmentedButton(button: UIButton) { let lastSelectedButton: UIButton = self.contentView?.viewWithTag(selectedIndex! + kTag) as! UIButton lastSelectedButton.isSelected = false lastSelectedButton.titleLabel?.font = UIFont.systemFont(ofSize: defaultFontSize) selectedIndex = button.tag - kTag button.isSelected = true var totalWidth: CGFloat = 0 if selectedIndex! == 0 { totalWidth = 0 } else { for i in 0...selectedIndex!-1 { totalWidth += CGFloat((widthArray?[i] as! NSNumber).floatValue) } } let selectedWidth: CGFloat if let width = widthArray?[selectedIndex!] { selectedWidth = CGFloat((width as! NSNumber).floatValue) } else { selectedWidth = 0 } var offsetX: CGFloat = totalWidth + (selectedWidth - self.bounds.size.width) * 0.5 offsetX = min(self.totalWidth! - self.bounds.size.width, max(0, offsetX)) contentView?.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) delegate?.segmentedMenu(didSelectIndex: selectedIndex!) UIView.animate(withDuration: 0.1) { self.divideView?.frame = CGRect(x: totalWidth - offsetX, y: (self.divideView?.frame.origin.y)!, width: selectedWidth, height: (self.divideView?.frame.size.height)!) button.titleLabel?.font = UIFont.systemFont(ofSize: highlightFontSize) } } func didSelectIndex(index: NSInteger) { let selectButton: UIButton = contentView?.viewWithTag(kTag + index) as! UIButton clickSegmentedButton(button: selectButton) } public init(frame: CGRect, contentDataSource: NSArray, titleDataSource: NSArray, type: UISegmentedMenuType) { super.init(frame: frame) font = UIFont(name: "Helvetica", size: defaultFontSize) self.type = type contentView = UIScrollView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - 0.5)) contentView?.clipsToBounds = true contentView?.backgroundColor = UIColor.white contentView?.showsHorizontalScrollIndicator = false contentView?.showsVerticalScrollIndicator = false self.addSubview(contentView!) divideLineView = UIView() divideLineView?.backgroundColor = UIColor.groupTableViewBackground self.addSubview(divideLineView!) divideView = UIView() divideView?.backgroundColor = UIColor.red self.addSubview(divideView!) let divideImageView = UIImageView(frame: CGRect(x: 0, y: bounds.size.height - 1, width: bounds.size.width, height: 0.5)) divideImageView.image = UIImage(named: "divider_line_image") self.addSubview(divideImageView) self.updateContentDateSource(contentDataSource: contentDataSource) self.updateTitleDataSource(titleDataSource: titleDataSource, selectedIndex: 0) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
cfc0d0a86964b45ce0660045072cb001
37.519774
176
0.64183
4.767832
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/UI/Form/AddressFieldView.swift
1
1610
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit class AddressFieldView: UIView { let pasteButton: Button = Button(size: .normal, style: .borderless) let qrButton: UIButton = UIButton(type: .custom) init() { super.init(frame: .zero) pasteButton.translatesAutoresizingMaskIntoConstraints = false pasteButton.setTitle(R.string.localizable.sendPasteButtonTitle(), for: .normal) qrButton.translatesAutoresizingMaskIntoConstraints = false qrButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44) qrButton.setImage(R.image.qr_code_icon(), for: .normal) qrButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let recipientRightView = UIStackView(arrangedSubviews: [ pasteButton, qrButton, ]) recipientRightView.translatesAutoresizingMaskIntoConstraints = false recipientRightView.distribution = .equalSpacing recipientRightView.spacing = 2 recipientRightView.axis = .horizontal addSubview(recipientRightView) NSLayoutConstraint.activate([ recipientRightView.topAnchor.constraint(equalTo: topAnchor), recipientRightView.leadingAnchor.constraint(equalTo: leadingAnchor), recipientRightView.bottomAnchor.constraint(equalTo: bottomAnchor), recipientRightView.trailingAnchor.constraint(equalTo: trailingAnchor), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
36b2390cdf60b2d5aaa891034426bde3
37.333333
91
0.69441
5.094937
false
false
false
false
timgrohmann/vertretungsplan_ios
Vertretungsplan/Fadable.swift
1
1611
// // UIView.swift // Vertretungsplan // // Created by Tim Grohmann on 17.09.16. // Copyright © 2016 Tim Grohmann. All rights reserved. // import Foundation import UIKit /** The _Fadable_ protocol is used to fade views in/out from/to a specified area. - fadingView: Used to store location of start/end point. Initialize to UIView() */ protocol Fadable { var fadingView: UIView {get set} } extension Fadable where Self: UIView{ func fadeIn(from start: UIView, size: CGSize){ self.center = start.center self.center.x -= ((start.superview as? UIScrollView)?.contentOffset.x ?? 0) self.center.y += start.superview!.frame.origin.y self.bounds = start.bounds fadingView.frame = self.frame self.clipsToBounds = true self.layoutIfNeeded() self.alpha = 0 self.layer.cornerRadius = 10 UIView.animate(withDuration: 0.2, animations: { self.alpha = 1 self.center = CGPoint(x: size.width*0.5, y: size.height*0.5) self.bounds = CGRect(x: 0,y: 0, width: size.width - 40, height: size.height*0.4) self.layoutIfNeeded() }) } func fadeOut(_ completion: @escaping ()->()){ UIView.animate(withDuration: 0.2, animations: { self.center = self.fadingView.center self.bounds = self.fadingView.bounds self.alpha = 0.0 self.layoutIfNeeded() }, completion: { finished in completion() }) } }
apache-2.0
2864c44a9059ebe7a7336dca9c4d4a03
26.758621
92
0.574534
4.065657
false
false
false
false
DDSSwiftTech/SwiftGtk
Sources/Container.swift
2
593
// // Copyright © 2015 Tomas Linhart. All rights reserved. // import CGtk open class Container: Widget { var widgets: [Widget] = [] public func add(_ widget: Widget) { widgets.append(widget) widget.parentWidget = self gtk_container_add(castedPointer(), widget.widgetPointer) } public func remove(_ widget: Widget) { if let index = widgets.index(where: { $0 === widget }) { gtk_container_remove(castedPointer(), widget.widgetPointer) widgets.remove(at: index) widget.parentWidget = nil } } }
mit
3a4c4c308835ddae6e29ff1aed10eff0
24.73913
71
0.60473
4.111111
false
false
false
false
aikizoku/Library-iOS
Library/System.swift
1
2542
import Foundation import UIKit class System: NSObject { /** iPhoneか判定する */ static let isPhone = { () -> Bool in return UIDevice.current.userInterfaceIdiom == .phone }() /** iPadか判定する */ static let isPad = { () -> Bool in return UIDevice.current.userInterfaceIdiom == .pad }() /** 端末の名前(プラットフォームコード)を取得する */ static func deviceName() -> String { var systemInfo = utsname() uname(&systemInfo) let mirror = Mirror(reflecting: systemInfo.machine) var identifier = "" for child in mirror.children { if let value = child.value as? Int8, value != 0 { identifier.append(UnicodeScalar(UInt8(value)).escaped(asASCII: true)) } } return identifier } /** 端末のOSバージョンを取得する */ static func osVersion() -> String { return UIDevice.current.systemVersion } /** アプリの識別子を取得する */ static func bundleIdentifier() -> String { return Bundle.main.bundleIdentifier ?? "" } /** Info.plistから値を取得する */ static func object<T>(forInfoDictionaryKey: String) -> T? { if let value = Bundle.main.object(forInfoDictionaryKey: forInfoDictionaryKey) as? T { return value } return nil } /** ビルドのバージョンを取得する */ static func buildVersion() -> String { if let value: String = object(forInfoDictionaryKey: "CFBundleVersion") { return value } else { return "" } } /** アプリのバージョンを取得する */ static func appVersion() -> String { if let value: String = object(forInfoDictionaryKey: "CFBundleShortVersionString") { return value } else { return "" } } /** 現在設定されている端末の言語を取得する */ static func currentLanguage() -> String { return NSLocale.preferredLanguages.first ?? "" } /** 現在設定されている端末のタイムゾーンを取得する */ static func currentTimeZone() -> String { let fmt = DateFormatter() fmt.timeZone = TimeZone.current fmt.dateFormat = "ZZZ" return fmt.string(from: Date()) } }
mit
1a587d8e142c5231d672ce4534590509
22.163265
93
0.543612
4.54
false
false
false
false
aferodeveloper/sango
Source/Extentions.swift
1
23340
/** * Copyright 2016 Afero, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Cocoa public enum AspectMode: String { case fill case fit case none } public extension NSImage { /// The height of the image. var height: CGFloat { return size.height } /// The width of the image. var width: CGFloat { return size.width } /// A PNG representation of the image. var PNGRepresentation: Data? { if let tiff = self.tiffRepresentation, let tiffData = NSBitmapImageRep(data: tiff) { return tiffData.representation(using: .png, properties: [:]) } return nil } /// Saves the PNG representation of the image to the supplied URL parameter. /// /// - Parameter url: The URL to save the image data to. /// - Throws: An NSImageExtensionError if unwrapping the image data fails. /// An error in the Cocoa domain, if there is an error writing to the URL. func savePngTo(url: URL) throws { guard let png = self.PNGRepresentation else { throw NSImageExtensionError.unwrappingPNGRepresentationFailed } try png.write(to: url, options: .atomicWrite) } /// Calculate the image size for a given aspect mode. /// /// - Parameters: /// - targetSize: The size the image should be resized to /// - aspectMode: The aspect mode to calculate the actual image size /// - Returns: The new image size private func calculateAspectSize(withTargetSize targetSize: NSSize, aspectMode: AspectMode) -> NSSize? { if aspectMode == .fit { return self.calculateFitAspectSize(widthRatio: targetSize.width / self.width, heightRatio: targetSize.height / self.height) } if aspectMode == .fill { return self.calculateFillAspectSize(widthRatio: targetSize.width / self.width, heightRatio: targetSize.height / self.height) } return nil } /// Calculate the size for an image to be resized in aspect fit mode; That is resizing it without /// cropping the image. /// /// - Parameters: /// - widthRatio: The width ratio of the image and the target size the image should be resized to. /// - heightRatio: The height retio of the image and the targed size the image should be resized to. /// - Returns: The maximum size the image can have, to fit inside the targed size, without cropping anything. private func calculateFitAspectSize(widthRatio: CGFloat, heightRatio: CGFloat) -> NSSize { if widthRatio < heightRatio { return NSSize(width: floor(self.width * widthRatio), height: floor(self.height * widthRatio)) } return NSSize(width: floor(self.width * heightRatio), height: floor(self.height * heightRatio)) } /// Calculate the size for an image to be resized in aspect fill mode; That is resizing it and cropping /// the edges of the image, if necessary. /// /// - Parameters: /// - widthRatio: The width ratio of the image and the target size the image should be resized to. /// - heightRatio: The height retio of the image and the targed size the image should be resized to. /// - Returns: The minimum size the image needs to have to fill the complete target area. private func calculateFillAspectSize(widthRatio: CGFloat, heightRatio: CGFloat) -> NSSize? { if widthRatio > heightRatio { return NSSize(width: floor(self.width * widthRatio), height: floor(self.height * widthRatio)) } return NSSize(width: floor(self.width * heightRatio), height: floor(self.height * heightRatio)) } /** * Given a file path, load and return an NSImage */ static func loadFrom(_ file: String) -> NSImage! { // Loading directly with NSImage, doesn't take in account of scale if let imageReps = NSBitmapImageRep.imageReps(withContentsOfFile: file) { var width = 0 var height = 0 for rep in imageReps { if (rep.pixelsWide > width) { width = rep.pixelsWide } if (rep.pixelsHigh > height) { height = rep.pixelsHigh } } let newImage = NSImage(size: NSMakeSize(CGFloat(width), CGFloat(height))) newImage.setName(NSImage.Name(rawValue: file.lastPathComponent())) newImage.addRepresentations(imageReps) return newImage } return nil } /** * Given a file, image.png, [email protected], [email protected], return the scaling factor * 1, 2, 3 */ static func getScaleFrom(_ file :String) -> (scale: Int, file: String) { var scale = 1 var fileName = file.lastPathComponent() fileName = (fileName as NSString).deletingPathExtension if (fileName.hasSuffix("@1x")) { scale = 1 fileName = fileName.replacingOccurrences(of: "@1x", with: "") } else if (fileName.hasSuffix("@2x")) { scale = 2 fileName = fileName.replacingOccurrences(of: "@2x", with: "") } else if (fileName.hasSuffix("@3x")) { scale = 3 fileName = fileName.replacingOccurrences(of: "@3x", with: "") } return (scale: scale, file: fileName) } func saveTo(_ file: String) -> Bool { let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(self.size.width), pixelsHigh: Int(self.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! bitmap.size = self.size NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap) self.draw(at: NSPoint.zero, from: NSRect.zero, operation: .sourceOver, fraction: 1.0) NSGraphicsContext.restoreGraphicsState() var ok = false if let imageData = bitmap.representation(using: NSBitmapImageRep.FileType.png, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: 1.0]) { ok = (try? imageData.write(to: URL(fileURLWithPath: (file as NSString).standardizingPath), options: [.atomic])) != nil } if (ok == false) { Utils.error("Error: Can't save image to \(file)") } return ok } func scale(_ percent: CGFloat) -> NSImage { if (percent == 100) { return self } else { var newR = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) let Width = newR.width let Height = newR.height let newWidth = (Width * percent) / 100.0 let newHeight = (Height * percent) / 100.0 let ratioOld = Width / Height let ratioNew = newWidth / newHeight if (ratioOld > ratioNew) { newR.size.width = newWidth // width of mapped rect newR.size.height = newR.size.width / ratioOld // height of mapped rect newR.origin.x = 0 // x-coord of mapped rect newR.origin.y = (newHeight - newR.size.height) / 2 // y-coord of centered mapped rect } else { newR.size.height = newHeight newR.size.width = newR.size.height * ratioOld newR.origin.y = 0 newR.origin.x = (newWidth - newR.size.width) / 2 } return resize(newR.width, height: newR.height) } } func tint(_ color: NSColor) -> NSImage { let destSize = self.size let rect = NSMakeRect(0, 0, self.size.width, self.size.height) let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(destSize.width), pixelsHigh: Int(destSize.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! bitmap.size = destSize NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: bitmap) context?.imageInterpolation = .high context?.shouldAntialias = true NSGraphicsContext.current = context self.draw(in: NSMakeRect(0, 0, destSize.width, destSize.height), from: NSMakeRect(0, 0, self.size.width, self.size.height), operation: .sourceOver, fraction: 1.0) // tint with Source Atop operation, via // http://www.w3.org/TR/2014/CR-compositing-1-20140220/#porterduffcompositingoperators color.set() rect.fill(using: .sourceAtop) NSGraphicsContext.restoreGraphicsState() let newImage = NSImage(size: destSize) newImage.addRepresentation(bitmap) return NSImage(data: newImage.tiffRepresentation!)! } func roundCorner(_ radiusX: CGFloat, _ radiusY : CGFloat) -> NSImage? { let imageFrame = NSMakeRect(0, 0, self.size.width, self.size.height) let composedImage = NSImage(size: imageFrame.size) composedImage.lockFocus() guard let context = NSGraphicsContext.current else { composedImage.unlockFocus() return nil } context.imageInterpolation = .high context.shouldAntialias = true let clipPath = NSBezierPath(roundedRect: imageFrame, xRadius: radiusX, yRadius: radiusY) clipPath.windingRule = NSBezierPath.WindingRule.evenOddWindingRule clipPath.addClip() self.draw(at: NSPoint.zero, from: imageFrame, operation: NSCompositingOperation.sourceOver, fraction: 1) composedImage.unlockFocus() return composedImage } func resize(_ width: CGFloat, height: CGFloat) -> NSImage { let destSize = NSMakeSize(width, height) let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(destSize.width), pixelsHigh: Int(destSize.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! bitmap.size = destSize NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: bitmap) context?.imageInterpolation = .high context?.shouldAntialias = true NSGraphicsContext.current = context self.draw(in: NSMakeRect(0, 0, destSize.width, destSize.height), from: NSMakeRect(0, 0, self.size.width, self.size.height), operation: .sourceOver, fraction: 1.0) NSGraphicsContext.restoreGraphicsState() let newImage = NSImage(size: destSize) newImage.addRepresentation(bitmap) return NSImage(data: newImage.tiffRepresentation!)! } /// Resize the image to the given size. /// /// - Parameter size: The size to resize the image to. /// - Returns: The resized image. func resize(toSize targetSize: NSSize, aspectMode: AspectMode) -> NSImage? { let newSize = self.calculateAspectSize(withTargetSize: targetSize, aspectMode: aspectMode) ?? targetSize let xCoordinate = round((targetSize.width - newSize.width) / 2) let yCoordinate = round((targetSize.height - newSize.height) / 2) let targetFrame = NSRect(origin: NSPoint.zero, size: targetSize) let frame = NSRect(origin: NSPoint(x: xCoordinate, y: yCoordinate), size: newSize) var backColor = NSColor.clear if let tiff = self.tiffRepresentation, let tiffData = NSBitmapImageRep(data: tiff) { backColor = tiffData.colorAt(x: 0, y: 0) ?? NSColor.clear } return NSImage(size: targetSize, flipped: false) { (_: NSRect) -> Bool in backColor.setFill() NSBezierPath.fill(targetFrame) guard let rep = self.bestRepresentation(for: NSRect(origin: NSPoint.zero, size: newSize), context: nil, hints: nil) else { return false } return rep.draw(in: frame) } } } public func + (left: [String: [String: Any]]?, right: [String: [String: Any]]?) -> [String: [String: Any]]? { let localLeft: [String: [String: Any]] = left ?? [:] let localRight: [String: [String: Any]] = right ?? [:] return localRight.reduce(localLeft) { curr, next in var ret = curr ret[next.0] = next.1 return ret } } public func + (left: Dictionary<String, Array<Any>>?, right: Dictionary<String, Array<Any>>?) -> Dictionary<String, Array<Any>> { let localLeft: [String: Array<Any>] = left ?? [:] let localRight: [String: Array<Any>] = right ?? [:] return localRight.reduce(localLeft) { curr, next in var ret = curr ret[next.0] = [ret[next.0], next.1].compactMap({$0}) return ret } } public func + (left: Dictionary<String, Any>, right: Dictionary<String, Any>) -> Dictionary<String, Any> { var map = left for (k, v) in right { // merge arrays if let _v = v as? [Any] { if let la = map[k] as? [Any] { map[k] = la + _v } else { map[k] = v } } else if let _v = v as? Dictionary<String, Any>, let la = map[k] as? Dictionary<String, Any> { map[k] = la + _v } else { map[k] = v } } return map } public func roundTo3f(value: Double) -> Double { return round(1000.0 * value) / 1000.0 } public func roundTo2f(value: Double) -> Double { return round(100.0 * value) / 100.0 } public extension Character { func unicodeScalarCodePoint() -> UnicodeScalar { let characterString = String(self) let scalars = characterString.unicodeScalars return scalars[scalars.startIndex] } } public extension String { func lowercasedFirst() -> String { let first = String(prefix(1)).lowercased() return first + String(dropFirst()) } func uppercasedFirst() -> String { let first = String(prefix(1)).uppercased() return first + String(dropFirst()) } func removeFirst() -> String { return String(dropFirst()) } func snakeCaseToCamelCase() -> String { let items = self.components(separatedBy: "_") var camelCase = "" items.enumerated().forEach { if ($1.isInteger()) { // this is a special case, so we can support a label: // Green_50 camelCase += "_"; } camelCase += $1.capitalized } return camelCase } // from http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf func escapeStr() -> String { let set = [ "\"":"\u{005C}\"", "/":"\\/", "\u{0001}":"", "\u{0002}":"", "\u{0003}":"", "\u{0004}":"", "\u{0005}":"", "\u{0006}":"", "\u{0007}":"", "\u{0008}":"\\b", "\u{0009}":"\\t", "\u{000A}":"\\n", "\u{000B}":"", "\u{000C}":"\\f", "\u{000D}":"\\r", "\u{000E}":"", "\u{000F}":"", "\u{0010}":"", "\u{0011}":"", "\u{0012}":"", "\u{0013}":"", "\u{0014}":"", "\u{0015}":"", "\u{0016}":"", "\u{0017}":"", "\u{0018}":"", "\u{0019}":"", "\u{001A}":"", "\u{001B}":"", "\u{001C}":"", "\u{001D}":"", "\u{001E}":"", "\u{001F}":"" ] var escaped = self for (key, value) in set { escaped = escaped.replacingOccurrences(of: key, with: value) } return escaped } func lastPathComponent() -> String { return (self as NSString).lastPathComponent } func pathOnlyComponent() -> String { return (self as NSString).deletingLastPathComponent } func fileExtention() -> String { return (self as NSString).pathExtension.lowercased() } func fileNameOnly() -> String { let fileName = self.lastPathComponent() return (fileName as NSString).deletingPathExtension } func removeScale() -> String { var file = self.replacingOccurrences(of: "@1x", with: "") file = file.replacingOccurrences(of: "@2x", with: "") return file.replacingOccurrences(of: "@3x", with: "") } /** * File-based resource names must contain only lowercase a-z, 0-9, or underscore */ func isAndroidCompatible() -> Bool { let set:NSMutableCharacterSet = NSMutableCharacterSet() set.formUnion(with: CharacterSet.lowercaseLetters) set.formUnion(with: CharacterSet.decimalDigits) set.addCharacters(in: "_.") let inverted = set.inverted let file = self.lastPathComponent().removeScale() if let _ = file.rangeOfCharacter(from: inverted, options: .caseInsensitive) { return false } return true } /** * Remove digits from the start of a string only */ func removeDigitsPrefix() -> String { var newString = String() let numbers = CharacterSet.decimalDigits var finished = false for (_, c) in self.enumerated() { let uc = c.unicodeScalarCodePoint() if (numbers.contains(uc) == false) || finished { newString.append(c) finished = true } } return newString } func removeWhitespace() -> String { return self.removeCharacters(.whitespacesAndNewlines) } func removeCharacters(_ set: CharacterSet) -> String { var newString = String() for (_, c) in self.enumerated() { let uc = c.unicodeScalarCodePoint() if set.contains(uc) == false { newString.append(c) } } return newString } func trunc(_ length: Int, trailing: String? = "…") -> String { if self.count > length { return String(self.prefix(length)) + (trailing ?? "") } else { return String(self) } } func isInteger() -> Bool { let numberCharacters = CharacterSet.decimalDigits.inverted return !self.isEmpty && self.rangeOfCharacter(from: numberCharacters) == nil } func isFloat() -> Bool { var floaty = false if (!self.isEmpty) { let numberCharacters = NSMutableCharacterSet.decimalDigit() numberCharacters.addCharacters(in: ".") numberCharacters.invert() if (self.rangeOfCharacter(from: numberCharacters as CharacterSet) == nil) { if (self.contains(".")) { floaty = true } } } return floaty } func isBoolean() -> Bool { return !self.isEmpty && self.lowercased() == "true" } } public func hasArrayBoolean(_ list: [Any]) -> Bool { var valid = false for itm in list { if let itm = itm as? String { if (itm.isBoolean()) { valid = true break } } else if itm is Bool { let strItm = String(describing: itm) if (strItm.isBoolean()) { valid = true break } } } return valid } public func hasArrayFloats(_ list: [Any]) -> Bool { var valid = false for itm in list { if let itm = itm as? String { if (itm.isFloat()) { valid = true break } } else if itm is Double || itm is Int { let strItm = String(describing: itm) if (strItm.isFloat()) { valid = true break } } } return valid } public func hasArrayInts(_ list: [Any]) -> Bool { var valid = false for itm in list { if let itm = itm as? String { if (itm.isInteger()) { valid = true break } } else if itm is Int { let strItm = String(describing: itm) if (strItm.isInteger()) { valid = true break } } } return valid } func test() -> Void { let a = "123".isAndroidCompatible() let b = "ANB".isAndroidCompatible() let c = "asd_234".isAndroidCompatible() let d = ",,:asd".isAndroidCompatible() let e = "&%#asd".isAndroidCompatible() let f = "fe_12_😀".isAndroidCompatible() print(a, b, c, d, e, f) }
apache-2.0
d04d54ff940c0275245264d62175627e
34.143072
130
0.530876
4.762245
false
false
false
false
mario-kang/HClient
HClient/SearchView.swift
1
34793
// // SearchView.swift // HClient // // Created by 강희찬 on 2017. 7. 17.. // Copyright © 2017년 mario-kang. All rights reserved. // import UIKit import SafariServices class SearchCell: UITableViewCell { @IBOutlet weak var DJImage: UIImageView! @IBOutlet weak var DJSeries: UILabel! @IBOutlet weak var DJTitle: UILabel! @IBOutlet weak var DJLang: UILabel! @IBOutlet weak var DJTag: UILabel! @IBOutlet weak var DJArtist: UILabel! } class SearchView: UITableViewController, UIViewControllerPreviewingDelegate, UIPickerViewDelegate, UIPickerViewDataSource { var activityController:UIActivityIndicatorView! var type = "" var tag = "" var arr:[Any] = [] var arr2:[Any] = [] var arr3:[Any] = [] var celllist:[String] = [] var hitomiNumber = "" var numberDic:[String:String] = [:] var pages = false var numbered = false var page:UInt = 0 var previewingContext:Any? var langIndex = 0 override func viewDidLoad() { super.viewDidLoad() activityController = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 32, height: 32)) activityController?.autoresizingMask = [.flexibleBottomMargin, .flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin] activityController.activityIndicatorViewStyle = .whiteLarge if !numbered { self.navigationItem.title = Strings.decode("\(type):\(tag)") } else { let numb = Int(hitomiNumber) self.navigationItem.title = String(format: NSLocalizedString("Hitomi number %d", comment: ""), numb!) } pages = false self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 154.0 if self.traitCollection.forceTouchCapability == UIForceTouchCapability.available { self.previewingContext = self.registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: self.view) } page = 1 if !numbered { downloadTask(page, langindex:langIndex) } else { downloadNumber() } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr2.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:SearchCell = tableView.dequeueReusableCell(withIdentifier: "list", for: indexPath) as! SearchCell if !numbered { let list:String = arr[indexPath.row] as! String let ar = list.components(separatedBy: "</a></h1>") let title = ar[0].components(separatedBy: ".html\">")[2] let etc = ar[1].components(separatedBy: "</div>") let artlist = etc[0].components(separatedBy: "list\">")[1] var artist = "" if artlist.contains("N/A") { artist.append("N/A") } else { let a = artlist.components(separatedBy: "</a></li>") let b = a.count-2 for i in 0...b { artist.append(a[i].components(separatedBy: ".html\">")[1]) if i != b { artist.append(", ") } } } let etc1 = etc[1].components(separatedBy: "</td>") var series = NSLocalizedString("Series: ", comment: "") if etc1[1].contains("N/A") { series.append("N/A") } else { let a = etc1[1].components(separatedBy: "</a></li>") let b = a.count-2 for i in 0...b { series.append(a[i].components(separatedBy: ".html\">")[1]) if i != b { series.append(", ") } } } var language = NSLocalizedString("Language: ", comment: "") if etc1[5].contains("N/A") { language.append("N/A") } else { language.append(etc1[5].components(separatedBy: ".html\">")[1].components(separatedBy: "</a>")[0]) } var tag1 = NSLocalizedString("Tags: ", comment: "") let taga = etc1[7].components(separatedBy: "</a></li>") let tagb = taga.count if tagb == 1 { tag1.append("N/A") } else { for i in 0...tagb-2 { tag1.append(taga[i].components(separatedBy: ".html\">")[1]) if i != tagb-2 { tag1.append(", ") } } } let session = URLSession.shared let request = URLRequest(url: URL(string:arr2[indexPath.row] as! String)!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0) if arr3[indexPath.row] is UIImage { cell.DJImage.image = arr3[indexPath.row] as? UIImage } else { cell.DJImage.image = nil } if !(celllist.contains(where: {$0 == "\(indexPath.row)"})) { UIApplication.shared.isNetworkActivityIndicatorVisible = true let sessionTask = session.dataTask(with: request, completionHandler: { (data, _, error) in if error == nil { let image = UIImage(data: data!) self.arr3[indexPath.row] = image! DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false cell.DJImage.image = image } } }) sessionTask.resume() } cell.DJImage.contentMode = .scaleAspectFit cell.DJTitle.text = Strings.decode(title) cell.DJArtist.text = Strings.decode(artist) cell.DJSeries.text = Strings.decode(series) cell.DJLang.text = Strings.decode(language) cell.DJTag.text = Strings.decode(tag1) if !(celllist.contains {$0 == "\(indexPath.row)"}) { celllist.append("\(indexPath.row)") } return cell } else { cell.DJImage.contentMode = .scaleAspectFit cell.DJTitle.text = Strings.decode(numberDic["title"]) cell.DJArtist.text = Strings.decode(numberDic["artist"]) cell.DJSeries.text = Strings.decode(numberDic["series"]) cell.DJLang.text = Strings.decode(numberDic["language"]) cell.DJTag.text = Strings.decode(numberDic["tag"]) let session = URLSession.shared let request = URLRequest(url: URL(string:arr2[indexPath.row] as! String)!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0) if arr3[indexPath.row] is UIImage { cell.DJImage.image = arr3[indexPath.row] as? UIImage } else { cell.DJImage.image = nil } if !(celllist.contains(where: {$0 == "\(indexPath.row)"})) { UIApplication.shared.isNetworkActivityIndicatorVisible = true let sessionTask = session.dataTask(with: request, completionHandler: { (data, _, error) in if error == nil { let image = UIImage(data: data!) self.arr3[indexPath.row] = image! DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false cell.DJImage.image = image } } }) sessionTask.resume() } if !(celllist.contains {$0 == "\(indexPath.row)"}) { celllist.append("\(indexPath.row)") } return cell } } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row + 1 == arr2.count && !pages && !numbered { page += 1 downloadTask(page, langindex:langIndex) pages = true } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var djURL = "" let segued:InfoDetail = segue.destination as! InfoDetail if segue.identifier == "djDetail3" && !numbered { let path = self.tableView.indexPathForSelectedRow let title = (arr[(path?.row)!] as! String).components(separatedBy: ".html\">")[0].components(separatedBy: "<a href=\"")[1] djURL = "https://hitomi.la\(title).html" } else if segue.identifier == "djDetail3" && numbered { let numb = Int(hitomiNumber) djURL = "https://hitomi.la/galleries/\(numb!).html" segued.URL1 = djURL } segued.URL1 = djURL } func downloadTask(_ ind:UInt, langindex:Int) { var overlay:UIView if self.splitViewController != nil { overlay = UIView(frame: (self.splitViewController?.view.frame)!) overlay.backgroundColor = UIColor.black overlay.alpha = 0.8 activityController.center = (self.splitViewController?.view.center)! self.splitViewController?.view.addSubview(overlay) } else { overlay = UIView(frame: self.view.frame) overlay.backgroundColor = UIColor.black overlay.alpha = 0.8 activityController.center = self.view.center self.view.addSubview(overlay) } overlay.addSubview(activityController) activityController.isHidden = false activityController.startAnimating() var taga = tag taga = taga.replacingOccurrences(of: " ", with: "%20") var url:URL if let path = Bundle.main.path(forResource: "Language", ofType: "plist") { if let array = NSArray(contentsOfFile: path) as? [[String]] { var array2 = array.sorted {$0[1] < $1[1]} array2.insert(["all","all"], at: 0) let str:String! = array2[langindex][0] if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(type):\(taga)-\(str!)-\(ind).html")! } else if type == "language" { url = URL(string: "https://hitomi.la/index-\(taga)-\(ind).html")! } else { url = URL(string: "https://hitomi.la/\(type)/\(taga)-\(str!)-\(ind).html")! } } else { if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(type):\(taga)-all-\(ind).html")! } else if type == "language" { url = URL(string: "https://hitomi.la/index-\(taga)-\(ind).html")! } else { url = URL(string: "https://hitomi.la/\(type)/\(taga)-all-\(ind).html")! } } } else { if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(type):\(taga)-all-\(ind).html")! } else if type == "language" { url = URL(string: "https://hitomi.la/index-\(taga)-\(ind).html")! } else { url = URL(string: "https://hitomi.la/\(type)/\(taga)-all-\(ind).html")! } } UIApplication.shared.isNetworkActivityIndicatorVisible = true let session = URLSession.shared let request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0) let task = session.dataTask(with: request) { (data, response, error) in if error == nil && (response as! HTTPURLResponse).statusCode == 200 { var str = String(data:data!, encoding:.utf8) str = Strings.replacingOccurrences(str) let temp = str?.components(separatedBy: "<div class=\"dj\">") for i in 1...(temp?.count)!-1 { let list = temp?[i] let img = list?.components(separatedBy: "\"> </div>")[0] let imga = img?.components(separatedBy: "<img src=\"")[1] let urlString = "https:\(imga!)" self.arr.append(temp![i]) self.arr2.append(urlString) self.arr3.append(NSNull()) } DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.tableView.reloadData() self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() self.pages = false } } else if error == nil && (response as! HTTPURLResponse).statusCode != 200 { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() self.pages = true } } else { OperationQueue.main.addOperation { UIApplication.shared.isNetworkActivityIndicatorVisible = false let alert = UIAlertController(title: NSLocalizedString("Error Occured.", comment: ""), message: error?.localizedDescription, preferredStyle: .alert) let action = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() } } } task.resume() self.tableView.reloadData() } func downloadNumber() { var overlay:UIView if self.splitViewController != nil { overlay = UIView(frame: (self.splitViewController?.view.frame)!) overlay.backgroundColor = UIColor.black overlay.alpha = 0.8 activityController.center = (self.splitViewController?.view.center)! self.splitViewController?.view.addSubview(overlay) } else { overlay = UIView(frame: self.view.frame) overlay.backgroundColor = UIColor.black overlay.alpha = 0.8 activityController.center = self.view.center self.view.addSubview(overlay) } overlay.addSubview(activityController) activityController.isHidden = false activityController.startAnimating() let numb = Int(hitomiNumber) let url = URL(string: "https://hitomi.la/galleries/\(numb!).html") UIApplication.shared.isNetworkActivityIndicatorVisible = true let session = URLSession.shared let request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0) let task = session.dataTask(with: request) { (data, response, error) in if error == nil && (response as! HTTPURLResponse).statusCode == 200 { let str = String(data: data!, encoding: .utf8) let anime = str?.components(separatedBy: "<td>Type</td><td>")[1].components(separatedBy: "</a></td>")[0] var title:String var pic:String if (anime?.contains("anime"))! { title = (str?.components(separatedBy: "<h1>")[2].components(separatedBy: "</h1>")[0])! pic = (str?.components(separatedBy: "\"cover\"><img src=\"")[1].components(separatedBy: "\"></div>")[0])! } else { title = (str?.components(separatedBy: "</a></h1>")[0].components(separatedBy: "<h1>")[3].components(separatedBy: ".html\">")[1])! pic = (str?.components(separatedBy: ".html\"><img src=\"")[1].components(separatedBy: "\"></a></div>")[0])! } let artist1 = str?.components(separatedBy: "</h2>")[0].components(separatedBy: "<h2>")[1] var artist = NSLocalizedString("Artist: ", comment: "") let artistlist = artist1?.components(separatedBy: "</a></li>") if (artist1?.contains("N/A"))! { artist.append("N/A") } else { for i in 0...(artistlist?.count)!-2 { artist.append(Strings.decode(artistlist?[i].components(separatedBy: ".html\">")[1])) if i != (artistlist?.count)! - 2 { artist.append(", ") } } } var language = NSLocalizedString("Language: ", comment: "") let lang = str?.components(separatedBy: "Language")[1].components(separatedBy: "</a></td>")[0] if (lang?.contains("N/A"))! { language.append("N/A") } else { language.append(Strings.decode(lang?.components(separatedBy: ".html\">")[1])) } var series = NSLocalizedString("Series: ", comment: "") let series1 = str?.components(separatedBy: "Series")[1].components(separatedBy: "</td>")[1] let series2 = series1?.components(separatedBy: "</a></li>") if (series1?.contains("N/A"))! { series.append("N/A") } else { for i in 0...(series2?.count)!-2 { series.append(Strings.decode(series2?[i].components(separatedBy: ".html\">")[1])) if i != (series2?.count)! - 2 { series.append(", ") } } } var tags = NSLocalizedString("Tags: ", comment: "") let tags1 = str?.components(separatedBy: "Tags")[1].components(separatedBy: "</td>")[1] let tags2 = tags1?.components(separatedBy: "</a></li>") if tags2?.count == 1 { tags.append("N/A") } else { for i in 0...(tags2?.count)!-2 { tags.append(Strings.decode(tags2?[i].components(separatedBy: ".html\">")[1])) if i != (tags2?.count)! - 2 { tags.append(", ") } } } let picurl = "https:\(pic)" self.numberDic["title"] = Strings.decode(title) self.numberDic["artist"] = artist self.numberDic["language"] = language self.numberDic["series"] = series self.numberDic["tag"] = tags self.arr2.append(picurl) self.arr3.append(NSNull()) DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.tableView.reloadData() self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() self.pages = true } } else if error == nil && (response as! HTTPURLResponse).statusCode != 200 { DispatchQueue.main.async { self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() self.pages = true OperationQueue.main.addOperation { UIApplication.shared.isNetworkActivityIndicatorVisible = false let alert = UIAlertController(title: String(format:NSLocalizedString("Could not find number %ld.", comment: ""),numb!), message: nil, preferredStyle: .alert) let action = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() } } } else { OperationQueue.main.addOperation { UIApplication.shared.isNetworkActivityIndicatorVisible = false let alert = UIAlertController(title: NSLocalizedString("Error Occured.", comment: ""), message: error?.localizedDescription, preferredStyle: .alert) let action = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) self.activityController.isHidden = true self.activityController.stopAnimating() overlay.removeFromSuperview() } } } task.resume() self.tableView.reloadData() } @IBAction func Action(_ sender: Any) { var url:URL if !numbered { var taga = tag taga = taga.replacingOccurrences(of: " ", with: "%20") if let path = Bundle.main.path(forResource: "Language", ofType: "plist") { if let array = NSArray(contentsOfFile: path) as? [[String]] { var array2 = array.sorted {$0[1] < $1[1]} array2.insert(["all",NSLocalizedString("All", comment: "")], at: 0) let str:String! = array2[self.langIndex][0] if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(type):\(taga)-\(str!)-1.html")! } else if type == "language" { url = URL(string: "https://hitomi.la/index-\(taga)-1.html")! } else { url = URL(string: "https://hitomi.la/\(type)/\(taga)-\(str!)-1.html")! } } else { if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(type):\(taga)-all-1.html")! } else if type == "language" { url = URL(string: "https://hitomi.la/index-\(taga)-1.html")! } else { url = URL(string: "https://hitomi.la/\(type)/\(taga)-all-1.html")! } } } else { if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(type):\(taga)-all-1.html")! } else if type == "language" { url = URL(string: "https://hitomi.la/index-\(taga)-1.html")! } else { url = URL(string: "https://hitomi.la/\(type)/\(taga)-all-1.html")! } } } else { let numb = Int(hitomiNumber) url = URL(string: "https://hitomi.la/galleries/\(numb!).html")! } let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let activity = UIAlertAction(title: NSLocalizedString("Share URL", comment: ""), style: .default) { (_) in let activitys = UIActivityViewController(activityItems: [url], applicationActivities: nil) activitys.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem self.present(activitys, animated: true, completion: nil) } let open = UIAlertAction(title: NSLocalizedString("Open in Safari", comment: ""), style: .default) { (_) in let safari = SFSafariViewController(url: url) if #available(iOS 10.0, *) { safari.preferredBarTintColor = UIColor(hue: 235.0/360.0, saturation: 0.77, brightness: 0.47, alpha: 1.0) } self.present(safari, animated: true, completion: nil) } let favorites = UserDefaults.standard var favoriteslist:[String] var bookmark:UIAlertAction if !numbered { if let a = favorites.array(forKey: "favoritesKey") as? [String] { favoriteslist = a } else { favoriteslist = [] } if !(favoriteslist.contains {$0 == "\(type):\(tag)"}) { bookmark = UIAlertAction(title: NSLocalizedString("Add to favorites", comment: ""), style: .default, handler: { (_) in favoriteslist.append("\(self.type):\(self.tag)") favorites.set(favoriteslist, forKey: "favoritesKey") favorites.synchronize() }) } else { bookmark = UIAlertAction(title: NSLocalizedString("Remove from favorites", comment: ""), style: .default, handler: { (_) in if let index = favoriteslist.index(of: "\(self.type):\(self.tag)") { favoriteslist.remove(at: index) favorites.set(favoriteslist, forKey: "favoritesKey") favorites.synchronize() } }) } } else { let numb = Int(hitomiNumber) if let a = favorites.array(forKey: "favorites") as? [String] { favoriteslist = a } else { favoriteslist = [] } if !(favoriteslist.contains {$0 == "https://hitomi.la/galleries/\(numb!).html"}) { bookmark = UIAlertAction(title: NSLocalizedString("Add to favorites", comment: ""), style: .default, handler: { (_) in favoriteslist.append("https://hitomi.la/galleries/\(numb!).html") favorites.set(favoriteslist, forKey: "favorites") favorites.synchronize() }) } else { bookmark = UIAlertAction(title: NSLocalizedString("Remove from favorites", comment: ""), style: .default, handler: { (_) in if let index = favoriteslist.index(of: "https://hitomi.la/galleries/\(numb!).html") { favoriteslist.remove(at: index) favorites.set(favoriteslist, forKey: "favorites") favorites.synchronize() } }) } } let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) sheet.addAction(activity) sheet.addAction(open) if !numbered && type != "language" { let lang = UIAlertAction(title: NSLocalizedString("Language", comment: ""), style: .default, handler: { (_) in let langAlert = UIAlertController(title: NSLocalizedString("Select the language.\n\n\n\n\n\n\n\n", comment: ""), message: nil, preferredStyle: .actionSheet) var frame:CGRect if UIDevice.current.userInterfaceIdiom == .phone && (UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight) { frame = CGRect(x: langAlert.view.bounds.size.height/2-145, y: 52, width: 270, height: 150) } else if UIDevice.current.userInterfaceIdiom == .phone { frame = CGRect(x: langAlert.view.bounds.size.width/2-145, y: 52, width: 270, height: 150) } else { frame = CGRect(x: 17, y: 52, width: 270, height: 150) } let picker = UIPickerView(frame: frame) picker.delegate = self picker.dataSource = self picker.selectRow(self.langIndex, inComponent: 0, animated: true) langAlert.view.addSubview(picker) let langOK = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: { (_) in if let path = Bundle.main.path(forResource: "Language", ofType: "plist") { if (NSArray(contentsOfFile: path) as? [[String]]) != nil { self.langIndex = picker.selectedRow(inComponent: 0) self.arr = [] self.arr2 = [] self.arr3 = [] self.celllist = [] self.page = 1 self.pages = false self.numberDic = [:] self.downloadTask(self.page, langindex: self.langIndex) } } }) let langCancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) langAlert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem langAlert.addAction(langOK) langAlert.addAction(langCancel) self.present(langAlert, animated: true, completion: nil) }) sheet.addAction(lang) } sheet.addAction(bookmark) sheet.addAction(cancel) sheet.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem self.present(sheet, animated: true, completion: nil) } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if let path = Bundle.main.path(forResource: "Language", ofType: "plist") { if let array = NSArray(contentsOfFile: path) as? [[String]] { return array.count + 1 } else { return 0 } } else { return 0 } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if let path = Bundle.main.path(forResource: "Language", ofType: "plist") { if let array = NSArray(contentsOfFile: path) as? [[String]] { var array2 = array.sorted {$0[1] < $1[1]} array2.insert(["all",NSLocalizedString("All", comment: "")], at: 0) return array2[row][1] } else { return nil } } else { return nil } } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let cellPosition = self.tableView.convert(location, to: self.view) let path = self.tableView.indexPathForRow(at: cellPosition) var djURL = "" if path != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let segued:InfoDetail = storyboard.instantiateViewController(withIdentifier: "io.github.mario-kang.HClient.infodetail") as! InfoDetail if !numbered { let title1 = arr[(path?.row)!] let title2 = (title1 as! String).components(separatedBy: ".html\">")[0] let title3 = title2.components(separatedBy: "<a href=\"")[1] djURL = "https://hitomi.la\(title3).html" } else { let numb = Int(hitomiNumber) djURL = "https://hitomi.la/galleries/\(numb!).html" } segued.URL1 = djURL return segued } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.navigationController?.show(viewControllerToCommit, sender: nil) } override var previewActionItems: [UIPreviewActionItem] { var url:URL if !numbered { var taga = tag taga = taga.replacingOccurrences(of: " ", with: "%20") if type == "male" || type == "female" { url = URL(string: "https://hitomi.la/tag/\(self.type):\(taga)-all-1.html")! } else { url = URL(string: "https://hitomi.la/\(self.type)/\(taga)-all-1.html")! } } else { let numb = Int(hitomiNumber) url = URL(string: "https://hitomi.la/galleries/\(numb!).html")! } let share = UIPreviewAction(title: NSLocalizedString("Share URL", comment: ""), style: .default) { (_, _) in let activitys = UIActivityViewController(activityItems: [url], applicationActivities: nil) activitys.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem UIApplication.shared.delegate?.window??.rootViewController?.present(activitys, animated: true, completion: nil) } let open = UIPreviewAction(title: NSLocalizedString("Open in Safari", comment: ""), style: .default) { (_, _) in let safari = SFSafariViewController(url: url) if #available(iOS 10.0, *) { safari.preferredBarTintColor = UIColor(hue: 235.0/360.0, saturation: 0.77, brightness: 0.47, alpha: 1.0) } UIApplication.shared.delegate?.window??.rootViewController?.present(safari, animated: true, completion: nil) } return [share,open] } }
mit
de904997daf1f5c0462ccd84cf90ff6a
46.454297
181
0.518399
4.897086
false
false
false
false
banxi1988/BXForm
Pod/Classes/View/TagLabel.swift
1
1535
// // TagLabel.swift // Pods // // Created by Haizhen Lee on 16/2/25. // // import Foundation // // OvalLabel.swift // Pods // // Created by Haizhen Lee on 15/12/29. // // import UIKit open class TagLabel:UILabel{ open var horizontalPadding:CGFloat = 4 open var outlineStyle = BXOutlineStyle.oval{ didSet{ updateOvalPath() } } open var tagColor:UIColor = UIColor.gray{ didSet{ updateOvalPath() } } open var cornerRadius:CGFloat = 4.0 { didSet{ updateOvalPath() } } lazy var maskLayer : CAShapeLayer = { [unowned self] in let maskLayer = CAShapeLayer() maskLayer.frame = self.frame self.layer.insertSublayer(maskLayer,at:0) return maskLayer }() open override func layoutSubviews() { super.layoutSubviews() maskLayer.frame = bounds updateOvalPath() } fileprivate func updateOvalPath(){ if bounds.size.width < 1{ return } var radius:CGFloat switch outlineStyle{ case .rounded: radius = cornerRadius case .oval: radius = bounds.width * 0.5 case .semicircle: radius = bounds.width * 0.5 case .none: radius = 0 } let image = UIImage.bx_roundImage(tagColor, size: bounds.size, cornerRadius: radius) maskLayer.contents = image.cgImage } open override var intrinsicContentSize : CGSize { let size = super.intrinsicContentSize return CGSize(width: size.width + horizontalPadding, height: size.height + horizontalPadding) } }
mit
b7194bd5c10414a1dcdaf0d98b253c05
18.43038
97
0.642345
3.946015
false
false
false
false
vapor/vapor
Sources/Vapor/Response/Response+Body.swift
1
8365
extension Response { struct BodyStream { let count: Int let callback: (BodyStreamWriter) -> () } /// Represents a `Response`'s body. /// /// let body = Response.Body(string: "Hello, world!") /// /// This can contain any data (streaming or static) and should match the message's `"Content-Type"` header. public struct Body: CustomStringConvertible, ExpressibleByStringLiteral { /// The internal HTTP body storage enum. This is an implementation detail. internal enum Storage { /// Cases case none case buffer(ByteBuffer) case data(Data) case dispatchData(DispatchData) case staticString(StaticString) case string(String) case stream(BodyStream) } /// An empty `Response.Body`. public static let empty: Body = .init() public var string: String? { switch self.storage { case .buffer(var buffer): return buffer.readString(length: buffer.readableBytes) case .data(let data): return String(decoding: data, as: UTF8.self) case .dispatchData(let dispatchData): return String(decoding: dispatchData, as: UTF8.self) case .staticString(let staticString): return staticString.description case .string(let string): return string default: return nil } } /// The size of the HTTP body's data. /// `-1` is a chunked stream. public var count: Int { switch self.storage { case .data(let data): return data.count case .dispatchData(let data): return data.count case .staticString(let staticString): return staticString.utf8CodeUnitCount case .string(let string): return string.utf8.count case .buffer(let buffer): return buffer.readableBytes case .none: return 0 case .stream(let stream): return stream.count } } /// Returns static data if not streaming. public var data: Data? { switch self.storage { case .buffer(var buffer): return buffer.readData(length: buffer.readableBytes) case .data(let data): return data case .dispatchData(let dispatchData): return Data(dispatchData) case .staticString(let staticString): return Data(bytes: staticString.utf8Start, count: staticString.utf8CodeUnitCount) case .string(let string): return Data(string.utf8) case .none: return nil case .stream: return nil } } public var buffer: ByteBuffer? { switch self.storage { case .buffer(let buffer): return buffer case .data(let data): let buffer = self.byteBufferAllocator.buffer(bytes: data) return buffer case .dispatchData(let dispatchData): let buffer = self.byteBufferAllocator.buffer(dispatchData: dispatchData) return buffer case .staticString(let staticString): let buffer = self.byteBufferAllocator.buffer(staticString: staticString) return buffer case .string(let string): let buffer = self.byteBufferAllocator.buffer(string: string) return buffer case .none: return nil case .stream: return nil } } public func collect(on eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer?> { switch self.storage { case .stream(let stream): let collector = ResponseBodyCollector(eventLoop: eventLoop, byteBufferAllocator: self.byteBufferAllocator) stream.callback(collector) return collector.promise.futureResult .map { $0 } default: return eventLoop.makeSucceededFuture(self.buffer) } } /// See `CustomDebugStringConvertible`. public var description: String { switch storage { case .none: return "<no body>" case .buffer(let buffer): return buffer.getString(at: 0, length: buffer.readableBytes) ?? "n/a" case .data(let data): return String(data: data, encoding: .ascii) ?? "n/a" case .dispatchData(let data): return String(data: Data(data), encoding: .ascii) ?? "n/a" case .staticString(let string): return string.description case .string(let string): return string case .stream: return "<stream>" } } internal var storage: Storage internal let byteBufferAllocator: ByteBufferAllocator /// Creates an empty body. Useful for `GET` requests where HTTP bodies are forbidden. public init(byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator self.storage = .none } /// Create a new body wrapping `Data`. public init(data: Data, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator storage = .data(data) } /// Create a new body wrapping `DispatchData`. public init(dispatchData: DispatchData, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator storage = .dispatchData(dispatchData) } /// Create a new body from the UTF8 representation of a `StaticString`. public init(staticString: StaticString, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator storage = .staticString(staticString) } /// Create a new body from the UTF8 representation of a `String`. public init(string: String, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator self.storage = .string(string) } /// Create a new body from a Swift NIO `ByteBuffer`. public init(buffer: ByteBuffer, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator self.storage = .buffer(buffer) } public init(stream: @escaping (BodyStreamWriter) -> (), count: Int, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.byteBufferAllocator = byteBufferAllocator self.storage = .stream(.init(count: count, callback: stream)) } public init(stream: @escaping (BodyStreamWriter) -> (), byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) { self.init(stream: stream, count: -1, byteBufferAllocator: byteBufferAllocator) } /// `ExpressibleByStringLiteral` conformance. public init(stringLiteral value: String) { self.byteBufferAllocator = ByteBufferAllocator() self.storage = .string(value) } /// Internal init. internal init(storage: Storage, byteBufferAllocator: ByteBufferAllocator) { self.byteBufferAllocator = byteBufferAllocator self.storage = storage } } } private final class ResponseBodyCollector: BodyStreamWriter { var buffer: ByteBuffer var eventLoop: EventLoop var promise: EventLoopPromise<ByteBuffer> init(eventLoop: EventLoop, byteBufferAllocator: ByteBufferAllocator) { self.buffer = byteBufferAllocator.buffer(capacity: 0) self.eventLoop = eventLoop self.promise = self.eventLoop.makePromise(of: ByteBuffer.self) } func write(_ result: BodyStreamResult, promise: EventLoopPromise<Void>?) { switch result { case .buffer(var buffer): self.buffer.writeBuffer(&buffer) case .error(let error): self.promise.fail(error) case .end: self.promise.succeed(self.buffer) } promise?.succeed(()) } }
mit
eb6443860c8b08e286db3d8a80109c30
41.897436
143
0.608966
5.536069
false
false
false
false