hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
168413a83e54e0927aa22bb54247b4d6714b1220 | 19,489 | //
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import UIKit
private enum BannerState {
case showing, hidden, gone
}
/// Wheter the banner should appear at the top or the bottom of the screen.
///
/// - Top: The banner will appear at the top.
/// - Bottom: The banner will appear at the bottom.
public enum BannerPosition {
case top, bottom
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case none, slight, heavy
fileprivate var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .none: return (damping: 1.0, velocity: 1.0)
case .slight: return (damping: 0.7, velocity: 1.5)
case .heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
open class Banner: UIView {
@objc class func topWindow() -> UIWindow? {
for window in UIApplication.shared.windows.reversed() {
if window.windowLevel == UIWindow.Level.normal && window.isKeyWindow && window.frame != CGRect.zero { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
@objc open var animationDuration: TimeInterval = 0.4
/// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`.
///
/// If the banner's `adjustsStatusBarStyle` is false, this property does nothing.
@objc open var preferredStatusBarStyle = UIStatusBarStyle.lightContent
/// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`.
@objc open var adjustsStatusBarStyle = false
/// Wheter the banner should appear at the top or the bottom of the screen. Defaults to `.Top`.
open var position = BannerPosition.top
/// How 'springy' the banner should display. Defaults to `.Slight`
open var springiness = BannerSpringiness.slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
@objc open var textColor = UIColor.white {
didSet {
resetTintColor()
}
}
/// The height of the banner. Default is 80.
@objc open var minimumHeight: CGFloat = 80
/// Whether or not the banner should show a shadow when presented.
@objc open var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override open var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override open var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
@objc open var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
@objc open var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
@objc open var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
@objc open var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
@objc open var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
@objc public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The label that displays the banner's subtitle.
@objc public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.subheadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The image on the left of the banner.
@objc let image: UIImage?
/// The image view that displays the `image`.
@objc public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
private var bannerState = BannerState.hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// - parameter title: The title of the banner. Optional. Defaults to nil.
/// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil.
/// - parameter image: The image on the left of the banner. Optional. Defaults to nil.
/// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
@objc public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.black, didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRect.zero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
imageView.image = image
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
guard let superview = superview, let showingConstraint = showingConstraint, let hiddenConstraint = hiddenConstraint else { return }
switch bannerState {
case .hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
// Managing different -layoutIfNeeded behaviours among iOS versions (for more, read the UIKit iOS 10 release notes)
if #available(iOS 10.0, *) {
superview.layoutIfNeeded()
} else {
layoutIfNeeded()
}
updateConstraintsIfNeeded()
}
@objc internal func didTap(_ recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
@objc internal func didSwipe(_ recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(Banner.didTap(_:))))
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(Banner.didSwipe(_:)))
swipe.direction = .up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.withRenderingMode(.alwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private var contentTopOffsetConstraint: NSLayoutConstraint!
private var minimumHeightConstraint: NSLayoutConstraint!
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
minimumHeightConstraint = backgroundView.constraintWithAttribute(.height, .greaterThanOrEqual, to: minimumHeight)
addConstraint(minimumHeightConstraint) // Arbitrary, but looks nice.
addConstraints(backgroundView.constraintsEqualToSuperview())
backgroundView.backgroundColor = backgroundColor
backgroundView.addSubview(contentView)
labelView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]|", views: views))
backgroundView.addConstraint(contentView.constraintWithAttribute(.bottom, .equal, to: .bottom, of: backgroundView))
contentTopOffsetConstraint = contentView.constraintWithAttribute(.top, .equal, to: .top, of: backgroundView)
backgroundView.addConstraint(contentTopOffsetConstraint)
let leftConstraintText: String
if image == nil {
leftConstraintText = "|"
} else {
contentView.addSubview(imageView)
contentView.addConstraint(imageView.constraintWithAttribute(.leading, .equal, to: contentView, constant: 15.0))
contentView.addConstraint(imageView.constraintWithAttribute(.centerY, .equal, to: contentView))
imageView.addConstraint(imageView.constraintWithAttribute(.width, .equal, to: 25.0))
imageView.addConstraint(imageView.constraintWithAttribute(.height, .equal, to: .width))
leftConstraintText = "[imageView]"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, views: views))
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", views: views))
backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .alignAllCenterY, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", views: views))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override open func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview, bannerState != .gone else { return }
commonConstraints = self.constraintsWithAttributes([.width], .equal, to: superview)
superview.addConstraints(commonConstraints)
switch self.position {
case .top:
showingConstraint = self.constraintWithAttribute(.top, .equal, to: .top, of: superview)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
hiddenConstraint = self.constraintWithAttribute(.bottom, .equal, to: .top, of: superview, constant: yOffset)
case .bottom:
showingConstraint = self.constraintWithAttribute(.bottom, .equal, to: .bottom, of: superview)
let yOffset: CGFloat = 7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
hiddenConstraint = self.constraintWithAttribute(.top, .equal, to: .bottom, of: superview, constant: yOffset)
}
}
open override func layoutSubviews() {
super.layoutSubviews()
adjustHeightOffset()
layoutIfNeeded()
}
private func adjustHeightOffset() {
guard let superview = superview else { return }
if superview === Banner.topWindow() && self.position == .top {
let statusBarSize = UIApplication.shared.statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
contentTopOffsetConstraint.constant = heightOffset
minimumHeightConstraint.constant = statusBarSize.height > 0 ? minimumHeight : 40
} else {
contentTopOffsetConstraint.constant = 0
minimumHeightConstraint.constant = 0
}
}
/// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
open func show(_ view: UIView? = nil, duration: TimeInterval? = nil) {
let viewToUse = view ?? Banner.topWindow()
guard let view = viewToUse else {
print("[Banner]: Could not find view. Aborting.")
return
}
view.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
let oldStatusBarStyle = UIApplication.shared.statusBarStyle
if adjustsStatusBarStyle {
UIApplication.shared.setStatusBarStyle(preferredStatusBarStyle, animated: true)
}
UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: {
self.bannerState = .showing
}, completion: { finished in
guard let duration = duration else { return }
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(1000.0 * duration))) {
self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil)
}
})
}
/// Dismisses the banner.
open func dismiss(_ oldStatusBarStyle: UIStatusBarStyle? = nil) {
let (damping, velocity) = self.springiness.springValues
UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: {
self.bannerState = .hidden
if let oldStatusBarStyle = oldStatusBarStyle {
UIApplication.shared.setStatusBarStyle(oldStatusBarStyle, animated: true)
}
}, completion: { finished in
self.bannerState = .gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
extension NSLayoutConstraint {
@objc class func defaultConstraintsWithVisualFormat(_ format: String, options: NSLayoutConstraint.FormatOptions = NSLayoutConstraint.FormatOptions(), metrics: [String: AnyObject]? = nil, views: [String: AnyObject] = [:]) -> [NSLayoutConstraint] {
return NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views)
}
}
extension UIView {
@objc func constraintsEqualToSuperview(_ edgeInsets: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] {
self.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
if let superview = self.superview {
constraints.append(self.constraintWithAttribute(.leading, .equal, to: superview, constant: edgeInsets.left))
constraints.append(self.constraintWithAttribute(.trailing, .equal, to: superview, constant: edgeInsets.right))
constraints.append(self.constraintWithAttribute(.top, .equal, to: superview, constant: edgeInsets.top))
constraints.append(self.constraintWithAttribute(.bottom, .equal, to: superview, constant: edgeInsets.bottom))
}
return constraints
}
@objc func constraintWithAttribute(_ attribute: NSLayoutConstraint.Attribute, _ relation: NSLayoutConstraint.Relation, to constant: CGFloat, multiplier: CGFloat = 1.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: multiplier, constant: constant)
}
@objc func constraintWithAttribute(_ attribute: NSLayoutConstraint.Attribute, _ relation: NSLayoutConstraint.Relation, to otherAttribute: NSLayoutConstraint.Attribute, of item: AnyObject? = nil, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item ?? self, attribute: otherAttribute, multiplier: multiplier, constant: constant)
}
@objc func constraintWithAttribute(_ attribute: NSLayoutConstraint.Attribute, _ relation: NSLayoutConstraint.Relation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item, attribute: attribute, multiplier: multiplier, constant: constant)
}
func constraintsWithAttributes(_ attributes: [NSLayoutConstraint.Attribute], _ relation: NSLayoutConstraint.Relation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> [NSLayoutConstraint] {
return attributes.map { self.constraintWithAttribute($0, relation, to: item, multiplier: multiplier, constant: constant) }
}
}
| 47.650367 | 274 | 0.677921 |
1e876df4321ac37f64ae51c21df685fab7408876 | 22,532 | // RUN: %target-typecheck-verify-swift
var var_redecl1: Int // expected-note {{previously declared here}}
var_redecl1 = 0
var var_redecl1: UInt // expected-error {{invalid redeclaration of 'var_redecl1'}}
var var_redecl2: Int // expected-note {{previously declared here}}
var_redecl2 = 0
var var_redecl2: Int // expected-error {{invalid redeclaration of 'var_redecl2'}}
var var_redecl3: (Int) -> () { get {} } // expected-note {{previously declared here}}
var var_redecl3: () -> () { get {} } // expected-error {{invalid redeclaration of 'var_redecl3'}}
var var_redecl4: Int // expected-note 2{{previously declared here}}
var var_redecl4: Int // expected-error {{invalid redeclaration of 'var_redecl4'}}
var var_redecl4: Int // expected-error {{invalid redeclaration of 'var_redecl4'}}
let let_redecl1: Int = 0 // expected-note {{previously declared here}}
let let_redecl1: UInt = 0 // expected-error {{invalid redeclaration}}
let let_redecl2: Int = 0 // expected-note {{previously declared here}}
let let_redecl2: Int = 0 // expected-error {{invalid redeclaration}}
class class_redecl1 {} // expected-note {{previously declared here}}
class class_redecl1 {} // expected-error {{invalid redeclaration}}
class class_redecl2<T> {} // expected-note {{previously declared here}}
class class_redecl2 {} // expected-error {{invalid redeclaration}}
class class_redecl3 {} // expected-note {{previously declared here}}
class class_redecl3<T> {} // expected-error {{invalid redeclaration}}
struct struct_redecl1 {} // expected-note {{previously declared here}}
struct struct_redecl1 {} // expected-error {{invalid redeclaration}}
struct struct_redecl2<T> {} // expected-note {{previously declared here}}
struct struct_redecl2 {} // expected-error {{invalid redeclaration}}
struct struct_redecl3 {} // expected-note {{previously declared here}}
struct struct_redecl3<T> {} // expected-error {{invalid redeclaration}}
enum enum_redecl1 {} // expected-note {{previously declared here}}
enum enum_redecl1 {} // expected-error {{invalid redeclaration}}
enum enum_redecl2<T> {} // expected-note {{previously declared here}}
enum enum_redecl2 {} // expected-error {{invalid redeclaration}}
enum enum_redecl3 {} // expected-note {{previously declared here}}
enum enum_redecl3<T> {} // expected-error {{invalid redeclaration}}
protocol protocol_redecl1 {} // expected-note {{previously declared here}}
protocol protocol_redecl1 {} // expected-error {{invalid redeclaration}}
typealias typealias_redecl1 = Int // expected-note {{previously declared here}}
typealias typealias_redecl1 = Int // expected-error {{invalid redeclaration}}
typealias typealias_redecl2 = Int // expected-note {{previously declared here}}
typealias typealias_redecl2 = UInt // expected-error {{invalid redeclaration}}
var mixed_redecl1: Int // expected-note {{previously declared here}}
class mixed_redecl1 {} // expected-error {{invalid redeclaration}}
class mixed_redecl1a : mixed_redecl1 {}
class mixed_redecl2 {} // expected-note {{previously declared here}}
struct mixed_redecl2 {} // expected-error {{invalid redeclaration}}
class mixed_redecl3 {} // expected-note {{previously declared here}}
// expected-note @-1 2{{found this candidate}}
enum mixed_redecl3 {} // expected-error {{invalid redeclaration}}
// expected-note @-1 2{{found this candidate}}
enum mixed_redecl3a : mixed_redecl3 {} // expected-error {{'mixed_redecl3' is ambiguous for type lookup in this context}}
// expected-error@-1 {{an enum with no cases cannot declare a raw type}}
// expected-error@-2 {{raw type}}
class mixed_redecl3b : mixed_redecl3 {} // expected-error {{'mixed_redecl3' is ambiguous for type lookup in this context}}
class mixed_redecl4 {} // expected-note {{previously declared here}}
// expected-note@-1{{found this candidate}}
protocol mixed_redecl4 {} // expected-error {{invalid redeclaration}}
// expected-note@-1{{found this candidate}}
protocol mixed_redecl4a : mixed_redecl4 {} // expected-error {{'mixed_redecl4' is ambiguous for type lookup in this context}}
class mixed_redecl5 {} // expected-note {{previously declared here}}
typealias mixed_redecl5 = Int // expected-error {{invalid redeclaration}}
typealias mixed_redecl5a = mixed_redecl5
func mixed_redecl6() {} // expected-note {{'mixed_redecl6()' previously declared here}}
var mixed_redecl6: Int // expected-error {{invalid redeclaration of 'mixed_redecl6'}}
var mixed_redecl7: Int // expected-note {{'mixed_redecl7' previously declared here}}
func mixed_redecl7() {} // expected-error {{invalid redeclaration of 'mixed_redecl7()'}}
func mixed_redecl8() {} // expected-note {{previously declared here}}
class mixed_redecl8 {} // expected-error {{invalid redeclaration}}
class mixed_redecl8a : mixed_redecl8 {}
class mixed_redecl9 {} // expected-note {{previously declared here}}
func mixed_redecl9() {} // expected-error {{invalid redeclaration}}
func mixed_redecl10() {} // expected-note {{previously declared here}}
typealias mixed_redecl10 = Int // expected-error {{invalid redeclaration}}
typealias mixed_redecl11 = Int // expected-note {{previously declared here}}
func mixed_redecl11() {} // expected-error {{invalid redeclaration}}
var mixed_redecl12: Int // expected-note {{previously declared here}}
let mixed_redecl12: Int = 0 // expected-error {{invalid redeclaration}}
let mixed_redecl13: Int = 0 // expected-note {{previously declared here}}
var mixed_redecl13: Int // expected-error {{invalid redeclaration}}
var mixed_redecl14 : Int
func mixed_redecl14(_ i: Int) {} // okay
func mixed_redecl15(_ i: Int) {}
var mixed_redecl15 : Int // okay
var mixed_redecl16: Int // expected-note {{'mixed_redecl16' previously declared here}}
func mixed_redecl16() -> Int {} // expected-error {{invalid redeclaration of 'mixed_redecl16()'}}
class OverloadStaticFromBase {
class func create() {}
}
class OverloadStaticFromBase_Derived : OverloadStaticFromBase {
class func create(_ x: Int) {}
}
// Overloading of functions based on argument names only.
func ovl_argname1(x: Int, y: Int) { }
func ovl_argname1(y: Int, x: Int) { }
func ovl_argname1(a: Int, b: Int) { }
// Overloading with generics
protocol P1 { }
protocol P2 { }
func ovl_generic1<T: P1 & P2>(t: T) { } // expected-note{{previous}}
func ovl_generic1<U: P1 & P2>(t: U) { } // expected-error{{invalid redeclaration of 'ovl_generic1(t:)'}}
func ovl_generic2<T : P1>(_: T) {} // expected-note{{previously declared here}}
func ovl_generic2<T : P1>(_: T) {} // expected-error{{invalid redeclaration of 'ovl_generic2'}}
func ovl_generic3<T : P1>(_ x: T) {} // OK
func ovl_generic3<T : P2>(_ x: T) {} // OK
// Redeclarations within nominal types
struct X { }
struct Y { }
struct Z {
var a : X, // expected-note{{previously declared here}}
a : Y // expected-error{{invalid redeclaration of 'a'}}
var b: X // expected-note{{previously declared here}}
}
extension Z {
var b: Int { return 0 } // expected-error{{invalid redeclaration of 'b'}}
}
struct X1 {
func f(a : Int) {} // expected-note{{previously declared here}}
func f(a : Int) {} // expected-error{{invalid redeclaration of 'f(a:)'}}
}
struct X2 {
func f(a : Int) {} // expected-note{{previously declared here}}
typealias IntAlias = Int
func f(a : IntAlias) {} // expected-error{{invalid redeclaration of 'f(a:)'}}
}
struct X3 {
func f(a : Int) {} // expected-note{{previously declared here}}
func f(a : IntAlias) {} // expected-error{{invalid redeclaration of 'f(a:)'}}
typealias IntAlias = Int
}
struct X4 {
typealias i = Int
// expected-note@-1 {{previously declared}}
// expected-note@-2 {{previously declared}}
static var i: String { return "" } // expected-error{{invalid redeclaration of 'i'}}
static func i() {} // expected-error{{invalid redeclaration of 'i()'}}
static var j: Int { return 0 } // expected-note{{previously declared here}}
struct j {} // expected-error{{invalid redeclaration of 'j'}}
var i: Int { return 0 }
func i(x: String) {}
}
extension X4 {
static var k: Int { return 0 } // expected-note{{previously declared here}}
struct k {} // expected-error{{invalid redeclaration of 'k'}}
}
// Generic Placeholders
struct X5<t, u, v> {
static var t: Int { return 0 }
static func u() {}
typealias v = String
func foo<t>(_ t: t) {
let t = t
_ = t
}
}
struct X6<T> {
var foo: T // expected-note{{previously declared here}}
func foo() -> T {} // expected-error{{invalid redeclaration of 'foo()'}}
func foo(_ x: T) {}
static var j: Int { return 0 } // expected-note{{previously declared here}}
struct j {} // expected-error{{invalid redeclaration of 'j'}}
}
extension X6 {
var k: Int { return 0 } // expected-note{{previously declared here}}
func k()
// expected-error@-1{{invalid redeclaration of 'k()'}}
// expected-error@-2{{expected '{' in body of function declaration}}
}
// Subscripting
struct Subscript1 {
subscript (a: Int) -> Int {
get { return a }
}
subscript (a: Float) -> Int {
get { return Int(a) }
}
subscript (a: Int) -> Float {
get { return Float(a) }
}
}
struct Subscript2 {
subscript (a: Int) -> Int { // expected-note{{previously declared here}}
get { return a }
}
subscript (a: Int) -> Int { // expected-error{{invalid redeclaration of 'subscript(_:)'}}
get { return a }
}
var `subscript`: Int { return 0 }
}
struct Subscript3 {
typealias `subscript` = Int // expected-note{{previously declared here}}
static func `subscript`(x: Int) -> String { return "" } // expected-error{{invalid redeclaration of 'subscript(x:)'}}
func `subscript`(x: Int) -> String { return "" }
subscript(x x: Int) -> String { return "" }
}
struct Subscript4 {
subscript(f: @escaping (Int) -> Int) -> Int { // expected-note{{previously declared here}}
get { return f(0) }
}
subscript(f: (Int) -> Int) -> Int { // expected-error{{invalid redeclaration of 'subscript(_:)'}}
get { return f(0) }
}
}
struct GenericSubscripts {
subscript<T>(x: T) -> Int { return 0 } // expected-note{{previously declared here}}
}
extension GenericSubscripts {
subscript<U>(x: U) -> Int { return 0 } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
subscript<T, U>(x: T) -> U { fatalError() }
subscript<T>(x: T) -> T { fatalError() }
subscript(x: Int) -> Int { return 0 }
}
struct GenericSubscripts2<T> {
subscript(x: T) -> Int { return 0 } // expected-note{{previously declared here}}
}
extension GenericSubscripts2 {
subscript(x: T) -> Int { return 0 } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
subscript<U>(x: U) -> Int { return 0 }
subscript(x: T) -> T { fatalError() }
subscript<U>(x: T) -> U { fatalError() }
subscript<U, V>(x: U) -> V { fatalError() }
subscript(x: Int) -> Int { return 0 }
}
struct GenericSubscripts3<T> {
subscript<U>(x: T) -> U { fatalError() } // expected-note{{previously declared here}}
}
extension GenericSubscripts3 {
subscript<U>(x: T) -> U { fatalError() } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
subscript<U, V>(x: U) -> V { fatalError() }
subscript<U>(x: U) -> U { fatalError() }
subscript(x: Int) -> Int { return 0 }
}
// Initializers
class Initializers {
init(x: Int) { } // expected-note{{previously declared here}}
convenience init(x: Int) { } // expected-error{{invalid redeclaration of 'init(x:)'}}
static func `init`(x: Int) -> Initializers { fatalError() }
func `init`(x: Int) -> Initializers { fatalError() }
}
// Default arguments
// <rdar://problem/13338746>
func sub(x:Int64, y:Int64) -> Int64 { return x - y } // expected-note 2{{'sub(x:y:)' previously declared here}}
func sub(x:Int64, y:Int64 = 1) -> Int64 { return x - y } // expected-error{{invalid redeclaration of 'sub(x:y:)'}}
func sub(x:Int64 = 0, y:Int64 = 1) -> Int64 { return x - y } // expected-error{{invalid redeclaration of 'sub(x:y:)'}}
// <rdar://problem/13783231>
struct NoneType {
}
func != <T>(lhs : T, rhs : NoneType) -> Bool { // expected-note{{'!=' previously declared here}}
return true
}
func != <T>(lhs : T, rhs : NoneType) -> Bool { // expected-error{{invalid redeclaration of '!=}}
return true
}
// throws
func throwsFunc(code: Int) { } // expected-note{{previously declared}}
func throwsFunc(code: Int) throws { } // expected-error{{invalid redeclaration of 'throwsFunc(code:)'}}
// throws function parameter -- OK
func throwsFuncParam(_ fn: () throws -> ()) { }
func throwsFuncParam(_ fn: () -> ()) { }
// @escaping
func escaping(x: @escaping (Int) -> Int) { } // expected-note{{previously declared}}
func escaping(x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(x:)'}}
func escaping(_ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}}
func escaping(_ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}}
func escaping(a: Int, _ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}}
func escaping(a: Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(a:_:)'}}
func escaping(_ a: (Int) -> Int, _ x: (Int) -> Int) { }
// expected-note@-1{{previously declared}}
// expected-note@-2{{previously declared}}
// expected-note@-3{{previously declared}}
func escaping(_ a: (Int) -> Int, _ x: @escaping (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}}
func escaping(_ a: @escaping (Int) -> Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}}
func escaping(_ a: @escaping (Int) -> Int, _ x: @escaping (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}}
struct Escaping {
func escaping(_ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}}
func escaping(_ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping'}}
func escaping(a: Int, _ x: @escaping (Int) -> Int) { } // expected-note{{previously declared}}
func escaping(a: Int, _ x: (Int) -> Int) { } // expected-error{{invalid redeclaration of 'escaping(a:_:)'}}
}
// @autoclosure
func autoclosure(f: () -> Int) { }
func autoclosure(f: @autoclosure () -> Int) { }
// inout
func inout2(x: Int) { }
func inout2(x: inout Int) { }
// optionals
func optional(x: Int?) { } // expected-note{{previously declared}}
func optional(x: Int!) { } // expected-error{{invalid redeclaration of 'optional(x:)'}}
func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}}
func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)}}
class optionalOverloads {
class func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}}
class func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)'}}
func optionalInOut(x: inout Int?) { } // expected-note{{previously declared}}
func optionalInOut(x: inout Int!) { } // expected-error{{invalid redeclaration of 'optionalInOut(x:)}}
}
func optional_3() -> Int? { } // expected-note{{previously declared}}
func optional_3() -> Int! { } // expected-error{{invalid redeclaration of 'optional_3()'}}
// mutating / nonmutating
protocol ProtocolWithMutating {
mutating func test1() // expected-note {{previously declared}}
func test1() // expected-error{{invalid redeclaration of 'test1()'}}
mutating func test2(_ a: Int?) // expected-note {{previously declared}}
func test2(_ a: Int!) // expected-error{{invalid redeclaration of 'test2'}}
mutating static func classTest1() // expected-error {{static functions must not be declared mutating}} {{3-12=}} expected-note {{previously declared}}
static func classTest1() // expected-error{{invalid redeclaration of 'classTest1()'}}
}
struct StructWithMutating {
mutating func test1() { } // expected-note {{previously declared}}
func test1() { } // expected-error{{invalid redeclaration of 'test1()'}}
mutating func test2(_ a: Int?) { } // expected-note {{previously declared}}
func test2(_ a: Int!) { } // expected-error{{invalid redeclaration of 'test2'}}
}
enum EnumWithMutating {
mutating func test1() { } // expected-note {{previously declared}}
func test1() { } // expected-error{{invalid redeclaration of 'test1()'}}
}
protocol ProtocolWithAssociatedTypes {
associatedtype t
// expected-note@-1 {{previously declared}}
// expected-note@-2 {{previously declared}}
static var t: Int { get } // expected-error{{invalid redeclaration of 't'}}
static func t() // expected-error{{invalid redeclaration of 't()'}}
associatedtype u
associatedtype v
// Instance requirements are fine.
var t: Int { get }
func u()
mutating func v()
associatedtype W
func foo<W>(_ x: W)
}
// <rdar://problem/21783216> Ban members named Type and Protocol without backticks
// https://twitter.com/jadengeller/status/619989059046240256
protocol r21783216a {
// expected-error @+2 {{type member must not be named 'Type', since it would conflict with the 'foo.Type' expression}}
// expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{18-22=`Type`}}
associatedtype Type
// expected-error @+2 {{type member must not be named 'Protocol', since it would conflict with the 'foo.Protocol' expression}}
// expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{18-26=`Protocol`}}
associatedtype Protocol
}
protocol r21783216b {
associatedtype `Type` // ok
associatedtype `Protocol` // ok
}
struct SR7249<T> {
var x: T { fatalError() } // expected-note {{previously declared}}
var y: Int // expected-note {{previously declared}}
var z: Int // expected-note {{previously declared}}
}
extension SR7249 {
var x: Int { fatalError() } // expected-warning{{redeclaration of 'x' is deprecated and will be an error in Swift 5}}
var y: T { fatalError() } // expected-warning{{redeclaration of 'y' is deprecated and will be an error in Swift 5}}
var z: Int { fatalError() } // expected-error{{invalid redeclaration of 'z'}}
}
// A constrained extension is okay.
extension SR7249 where T : P1 {
var x: Int { fatalError() }
var y: T { fatalError() }
var z: Int { fatalError() }
}
protocol P3 {
var i: Int { get }
subscript(i: Int) -> String { get }
}
extension P3 {
var i: Int { return 0 }
subscript(i: Int) -> String { return "" }
}
struct SR7250<T> : P3 {}
extension SR7250 where T : P3 {
var i: Int { return 0 }
subscript(i: Int) -> String { return "" }
}
// SR-10084
struct SR_10084_S {
let name: String
}
enum SR_10084_E {
case foo(SR_10084_S) // expected-note {{'foo' previously declared here}}
static func foo(_ name: String) -> SR_10084_E { // Okay
return .foo(SR_10084_S(name: name))
}
func foo(_ name: Bool) -> SR_10084_E { // Okay
return .foo(SR_10084_S(name: "Test"))
}
static func foo(_ value: SR_10084_S) -> SR_10084_E { // expected-error {{invalid redeclaration of 'foo'}}
return .foo(value)
}
}
enum SR_10084_E_1 {
static func foo(_ name: String) -> SR_10084_E_1 { // Okay
return .foo(SR_10084_S(name: name))
}
static func foo(_ value: SR_10084_S) -> SR_10084_E_1 { // expected-note {{'foo' previously declared here}}
return .foo(value)
}
case foo(SR_10084_S) // expected-error {{invalid redeclaration of 'foo'}}
}
enum SR_10084_E_2 {
case fn(() -> Void) // expected-note {{'fn' previously declared here}}
static func fn(_ x: @escaping () -> Void) -> SR_10084_E_2 { // expected-error {{invalid redeclaration of 'fn'}}
fatalError()
}
static func fn(_ x: @escaping () -> Int) -> SR_10084_E_2 { // Okay
fatalError()
}
static func fn(_ x: @escaping () -> Bool) -> SR_10084_E_2 { // Okay
fatalError()
}
}
// N.B. Redeclaration checks don't see this case because `protocol A` is invalid.
enum SR_10084_E_3 {
protocol A {} //expected-error {{protocol 'A' cannot be nested inside another declaration}}
case A
}
enum SR_10084_E_4 {
class B {} // expected-note {{'B' previously declared here}}
case B // expected-error {{invalid redeclaration of 'B'}}
}
enum SR_10084_E_5 {
struct C {} // expected-note {{'C' previously declared here}}
case C // expected-error {{invalid redeclaration of 'C'}}
}
// N.B. Redeclaration checks don't see this case because `protocol D` is invalid.
enum SR_10084_E_6 {
case D
protocol D {} //expected-error {{protocol 'D' cannot be nested inside another declaration}}
}
enum SR_10084_E_7 {
case E // expected-note {{'E' previously declared here}}
class E {} // expected-error {{invalid redeclaration of 'E'}}
}
enum SR_10084_E_8 {
case F // expected-note {{'F' previously declared here}}
struct F {} // expected-error {{invalid redeclaration of 'F'}}
}
enum SR_10084_E_9 {
case A // expected-note {{found this candidate}} // expected-note {{'A' previously declared here}}
static let A: SR_10084_E_9 = .A // expected-note {{found this candidate}} // expected-error {{invalid redeclaration of 'A'}} // expected-error {{ambiguous use of 'A'}}
}
enum SR_10084_E_10 {
static let A: SR_10084_E_10 = .A // expected-note {{found this candidate}} // expected-note {{'A' previously declared here}} // expected-error {{ambiguous use of 'A'}}
case A // expected-note {{found this candidate}} // expected-error {{invalid redeclaration of 'A'}}
}
enum SR_10084_E_11 {
case A // expected-note {{found this candidate}} // expected-note {{'A' previously declared here}}
static var A: SR_10084_E_11 = .A // expected-note {{found this candidate}} // expected-error {{invalid redeclaration of 'A'}} // expected-error {{ambiguous use of 'A'}}
}
enum SR_10084_E_12 {
static var A: SR_10084_E_12 = .A // expected-note {{found this candidate}} // expected-note {{'A' previously declared here}} // expected-error {{ambiguous use of 'A'}}
case A // expected-note {{found this candidate}} // expected-error {{invalid redeclaration of 'A'}}
}
enum SR_10084_E_13 {
case X // expected-note {{'X' previously declared here}}
struct X<T> {} // expected-error {{invalid redeclaration of 'X'}}
}
enum SR_10084_E_14 {
struct X<T> {} // expected-note {{'X' previously declared here}}
case X // expected-error {{invalid redeclaration of 'X'}}
}
enum SR_10084_E_15 {
case Y // expected-note {{'Y' previously declared here}}
typealias Y = Int // expected-error {{invalid redeclaration of 'Y'}}
}
enum SR_10084_E_16 {
typealias Z = Int // expected-note {{'Z' previously declared here}}
case Z // expected-error {{invalid redeclaration of 'Z'}}
}
| 36.816993 | 170 | 0.681786 |
f80978f7d383a6e9a29cea056ec501e4f7757034 | 3,046 | //
// DataManager.swift
// Images
//
// Created by Infraestructura on 8/2/19.
// Copyright © 2019 Daniel Rosales. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class DataManager:NSObject{
// Implementación Singleton //
static var shared = DataManager()
private override init(){
super.init()
}
/*****************************/
// property de tipo lazy var: Retardar la inicialización, solo cuando sea necesario
lazy var persistentContainer:NSPersistentContainer = {
// Se neesita el nombredel archivo .xcdatamodel
let container = NSPersistentContainer(name: "Images") // name: "nombre del modelo", mismo nombre del sqlite que se va a generar
container.loadPersistentStores(completionHandler: {
(storeDescription, error) in
if error != nil {
//TODO: que hago? cierro la app? exit(666)
print("error al crear la BD en: \(storeDescription). \(error!.localizedDescription)")
}
})
return container
}() //Se ejecuta cuando se inicializa
func saveImage(_ image:UIImage, titulo:String){
// encontrar la ubicación Library
let libraryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
let hoy = Date()
let df = DateFormatter()
df.dateFormat = "yyyyMMdd_HHmmss"
let nombreFoto = df.string(from: hoy) + ".jpg" //Todas las fotos del dispositivo se manejan como .jpg
let urlFoto = libraryURL?.appendingPathComponent(nombreFoto)
print("imagen guardada como: \(urlFoto?.absoluteString)")
let bytes = image.jpegData(compressionQuality: 1.0)
do {
try bytes?.write(to: urlFoto!) //Guardar bytes en un archivo
//guardo en la BD
let imagen = NSEntityDescription.insertNewObject(forEntityName: "Imagen", into: self.persistentContainer.viewContext) as! Imagen //Objeto ManagedObject
imagen.titulo = titulo
//imagen.path = urlFoto!.path
imagen.path = nombreFoto
imagen.guid = UUID().uuidString
//Guardar latitud y longitud de donde se tomó la foto
if GeoManager.shared.lastKnowLocation != nil {
imagen.lat = GeoManager.shared.lastKnowLocation!.latitude
imagen.lon = GeoManager.shared.lastKnowLocation!.longitude
}
try self.persistentContainer.viewContext.save()
}
catch{
print("Ocurrió un error al guardar: \(error.localizedDescription)")
}
}
func selectImages() -> [Imagen]{
var result:[Imagen] = []
let query = NSFetchRequest<Imagen>(entityName: "Imagen")
do{
result = try self.persistentContainer.viewContext.fetch(query)
print("Registros: \(result.count)")
}
catch{
print(error.localizedDescription)
}
return result
}
}
| 36.261905 | 163 | 0.610637 |
dd67e66112d4a42a62fbeab43e403a41e77f1ce5 | 13,759 | //
// Plane.swift
// SurfaceCrib
//
// Created by Paul on 8/11/15.
// Copyright © 2018 Ceran Digital Media. All rights reserved. See LICENSE.md
//
import Foundation
/// Unbounded flat surface.
public struct Plane {
/// A point to locate the plane
internal var location: Point3D
/// A vector perpendicular to the plane
internal var normal: Vector3D
/// Records parameters and checks to see that the normal is a legitimate vector
/// - See: 'testFidelity' under PlaneTests
init(spot: Point3D, arrow: Vector3D) throws {
guard !arrow.isZero() else { throw ZeroVectorError(dir: arrow) }
guard arrow.isUnit() else { throw NonUnitDirectionError(dir: arrow) }
self.location = spot
self.normal = arrow
// TODO: Include tests to verify that the errors get thrown correctly
}
/// Generate a perpendicular vector from differences between the inputs
/// Normal could be the opposite of what you hoped for
/// - Parameters:
/// - alpha: First input point and origin of the fresh plane
/// - beta: Second input point
/// - gamma: Third input point
/// - Returns: Fresh plane
/// - Throws: CoincidentPointsError for duplicate or linear inputs
init(alpha: Point3D, beta: Point3D, gamma: Point3D) throws {
guard Point3D.isThreeUnique(alpha: alpha, beta: beta, gamma: gamma) else { throw CoincidentPointsError(dupePt: alpha) }
// TODO: Come up with a better error type
guard !Point3D.isThreeLinear(alpha: alpha, beta: beta, gamma: gamma) else { throw CoincidentPointsError(dupePt: alpha) }
self.location = alpha
let thisWay = Vector3D.built(from: alpha, towards: beta)
let thatWay = Vector3D.built(from: alpha, towards: gamma)
var perpTo = try! Vector3D.crossProduct(lhs: thisWay, rhs: thatWay)
perpTo.normalize()
self.normal = perpTo
}
/// A getter for the point defining the plane
/// - See: 'testLocationGetter' under PlaneTests
public func getLocation() -> Point3D {
return self.location
}
/// A getter for the vector defining the plane
/// - See: 'testNormalGetter' under PlaneTests
public func getNormal() -> Vector3D {
return self.normal
}
/// This needs to be added back into SketchGen
/// - Parameters:
/// - pip: Point of interest
/// - Returns: Tuple of Vectors
/// - Warning: This will screw up if pip is at the origin of the plane
public func resolveRelativeVec(pip: Point3D) -> (inPlane: Vector3D, perp: Vector3D) {
let bridge = Vector3D.built(from: self.location, towards: pip)
let along = Vector3D.dotProduct(lhs: bridge, rhs: self.normal)
let perp = self.normal * along
let inPlane = bridge - perp
return (inPlane, perp)
}
/// Flip points to the opposite side of the plane
/// - Parameters:
/// - flat: Mirroring plane
/// - pip: Point to be flipped
/// - Returns: New point
public static func mirror(flat: Plane, pip: Point3D) -> Point3D {
let comps = flat.resolveRelativeVec(pip: pip)
let jump = comps.perp * -2.0
let fairest = Point3D.offset(pip: pip, jump: jump)
return fairest
}
/// Flip line segment to the opposite side of the plane
/// - Parameters:
/// - flat: Mirroring plane
/// - wire: LineSeg to be flipped
/// - Returns: New LineSeg
public static func mirror(flat: Plane, wire: LineSeg) -> LineSeg {
var pip: Point3D = wire.getOneEnd()
var comps = flat.resolveRelativeVec(pip: pip)
var jump = comps.perp * -2.0
let fairest1 = Point3D.offset(pip: pip, jump: jump)
pip = wire.getOtherEnd()
comps = flat.resolveRelativeVec(pip: pip)
jump = comps.perp * -2.0
let fairest2 = Point3D.offset(pip: pip, jump: jump)
let rail = try! LineSeg(end1: fairest1, end2: fairest2)
return rail
}
/// Test for points being on opposite sides.
/// This needs to be added back into SketchGen.
/// - Parameters:
/// - pointA: One point of interest
/// - pointB: Other point of interest
/// - Returns: Simple flag
/// - Warning: Probably screws up if either point is on the plane.
public func isOpposite(pointA: Point3D, pointB: Point3D) -> Bool {
let vecA = resolveRelativeVec(pip: pointA)
let senseA = Vector3D.dotProduct(lhs: vecA.perp, rhs: self.getNormal())
let vecB = resolveRelativeVec(pip: pointB)
let senseB = Vector3D.dotProduct(lhs: vecB.perp, rhs: self.getNormal())
let flag = (senseA * senseB) < 0.0
return flag
}
/// Check to see that the line direction is perpendicular to the normal
/// - Parameters:
/// - flat: Plane for testing
/// - enil: Line for testing
public static func isParallel(flat: Plane, enil: Line) -> Bool {
let perp = Vector3D.dotProduct(lhs: enil.getDirection(), rhs: flat.normal)
return abs(perp) < Vector3D.EpsilonV
}
/// Check to see that the line is parallel to the plane, and lies on it
/// - Parameters:
/// - enalp: Plane for testing
/// - enil: Line for testing
public static func isCoincident(enalp: Plane, enil: Line) -> Bool {
return self.isParallel(flat: enalp, enil: enil) && Plane.isCoincident(flat: enalp, pip: enil.getOrigin())
}
/// Does the argument point lie on the plane?
/// - Parameters:
/// - flat: Plane for testing
/// - pip: Point for testing
/// - See: 'testIsCoincident' under PlaneTests
public static func isCoincident(flat: Plane, pip: Point3D) -> Bool {
if pip == flat.getLocation() { return true } // Shortcut!
let bridge = Vector3D.built(from: flat.location, towards: pip)
// This can be positive, negative, or zero
let distanceOffPlane = Vector3D.dotProduct(lhs: bridge, rhs: flat.normal)
return abs(distanceOffPlane) < Point3D.Epsilon
}
/// Are the normals either parallel or opposite?
/// - SeeAlso: isCoincident and ==
public static func isParallel(lhs: Plane, rhs: Plane) -> Bool{
return lhs.normal == rhs.normal || Vector3D.isOpposite(lhs: lhs.normal, rhs: rhs.normal)
}
/// Planes are parallel, and rhs location lies on lhs
/// - SeeAlso: isParallel and ==
public static func isCoincident(lhs: Plane, rhs: Plane) -> Bool {
return Plane.isCoincident(flat: lhs, pip: rhs.location) && Plane.isParallel(lhs: lhs, rhs: rhs)
}
/// Construct a parallel plane offset some distance
/// - Parameters:
/// - base: The reference plane
/// - offset: Desired separation
/// - reverse: Flip the normal, or not
/// - Returns: Fresh plane, with separation
/// - Throws:
/// - ZeroVectorError if base somehow got corrupted
/// - NonUnitDirectionError if base somehow got corrupted
public static func buildParallel(base: Plane, offset: Double, reverse: Bool) throws -> Plane {
let jump = base.normal * offset // offset can be a negative number
let origPoint = base.location
let newLoc = Point3D.offset(pip: origPoint, jump: jump)
var newNorm = base.normal
if reverse {
newNorm = base.normal * -1.0
}
let sparkle = try Plane(spot: newLoc, arrow: newNorm)
return sparkle
}
/// Construct a new plane perpendicular to an existing plane, and through a line on that plane
/// Normal could be the opposite of what you hoped for
/// - Parameters:
/// - enil: Location for a fresh plane
/// - enalp: The reference plane
/// - Returns: Fresh plane
/// - Throws:
/// - ZeroVectorError if enalp somehow got corrupted
/// - NonUnitDirectionError if enalp somehow got corrupted
public static func buildPerpThruLine(enil: Line, enalp: Plane) throws -> Plane {
// TODO: Better error type
guard !Plane.isCoincident(enalp: enalp, enil: enil) else { throw CoincidentLinesError(enil: enil) }
let newDir = try! Vector3D.crossProduct(lhs: enil.getDirection(), rhs: enalp.normal)
let sparkle = try Plane(spot: enil.getOrigin(), arrow: newDir)
return sparkle
}
/// Generate a point by intersecting a line and a plane
/// - Parameters:
/// - enil: Line of interest
/// - enalp: Flat surface to hit
/// - Throws: ParallelError if the input Line is parallel to the plane
public static func intersectLinePlane(enil: Line, enalp: Plane) throws -> Point3D {
// Bail if the line is parallel to the plane
guard !Plane.isParallel(flat: enalp, enil: enil) else { throw ParallelError(enil: enil, enalp: enalp) }
if Plane.isCoincident(flat: enalp, pip: enil.getOrigin()) { return enil.getOrigin() } // Shortcut!
// Resolve the line direction into components normal to the plane and in plane
let lineNormMag = Vector3D.dotProduct(lhs: enil.getDirection(), rhs: enalp.getNormal())
let lineNormComponent = enalp.getNormal() * lineNormMag
let lineInPlaneComponent = enil.getDirection() - lineNormComponent
let projectedLineOrigin = Plane.projectToPlane(pip: enil.getOrigin(), enalp: enalp)
let drop = Vector3D.built(from: enil.getOrigin(), towards: projectedLineOrigin, unit: true)
let closure = Vector3D.dotProduct(lhs: enil.getDirection(), rhs: drop)
let separation = Point3D.dist(pt1: projectedLineOrigin, pt2: enil.getOrigin())
var factor = separation / lineNormComponent.length()
if closure < 0.0 { factor = factor * -1.0 } // Dependent on the line origin's position relative to
// the plane normal
let inPlaneOffset = lineInPlaneComponent * factor
return Point3D.offset(pip: projectedLineOrigin, jump: inPlaneOffset)
}
/// Construct a line by intersecting two planes
/// - Parameters:
/// - flatA: First plane
/// - flatB: Second plane
/// - Throws: ParallelPlanesError if the inputs are parallel
/// - Throws: CoincidentPlanesError if the inputs are coincident
public static func intersectPlanes(flatA: Plane, flatB: Plane) throws -> Line {
guard !Plane.isParallel(lhs: flatA, rhs: flatB) else { throw ParallelPlanesError(enalpA: flatA) }
guard !Plane.isCoincident(lhs: flatA, rhs: flatB) else { throw CoincidentPlanesError(enalpA: flatA) }
/// Direction of the intersection line
var lineDir = try! Vector3D.crossProduct(lhs: flatA.getNormal(), rhs: flatB.getNormal())
lineDir.normalize() // Checks in crossProduct should keep this from being a zero vector
/// Vector on plane B that is perpendicular to the intersection line
var perpInB = try! Vector3D.crossProduct(lhs: lineDir, rhs: flatB.getNormal())
perpInB.normalize() // Checks in crossProduct should keep this from being a zero vector
// The ParallelPlanesError or CoincidentPlanesError should be avoided by the guard statements
let lineFromCenterB = try Line(spot: flatB.getLocation(), arrow: perpInB) // Can be either towards flatA,
// or away from it
let intersectionPoint = try Plane.intersectLinePlane(enil: lineFromCenterB, enalp: flatA)
let common = try Line(spot: intersectionPoint, arrow: lineDir)
return common
}
/// Drop the point in the direction opposite of the normal
/// - Parameters:
/// - pip: Point to be projected
/// - enalp: Flat surface to hit
/// - Returns: Closest point on plane
public static func projectToPlane(pip: Point3D, enalp: Plane) -> Point3D {
if Plane.isCoincident(flat: enalp, pip: pip) {return pip } // Shortcut!
let planeCenter = enalp.getLocation() // Referred to multiple times
let bridge = Vector3D.built(from: planeCenter, towards: pip) // Not normalized
// This can be positive, or negative
let distanceOffPlane = Vector3D.dotProduct(lhs: bridge, rhs: enalp.getNormal())
// Resolve "bridge" into components that are perpendicular to the plane and are parallel to it
let bridgeNormComponent = enalp.getNormal() * distanceOffPlane
let bridgeInPlaneComponent = bridge - bridgeNormComponent
return Point3D.offset(pip: planeCenter, jump: bridgeInPlaneComponent) // Ignore the component normal to the plane
}
}
/// Check for them being identical
/// - SeeAlso: isParallel and isCoincident
/// - See: 'testEquals' under PlaneTests
public func == (lhs: Plane, rhs: Plane) -> Bool {
let flag1 = lhs.normal == rhs.normal // Do they have the same direction?
let flag2 = lhs.location == rhs.location // Do they have identical locations?
return flag1 && flag2
}
| 37.490463 | 130 | 0.609565 |
7251f989a61d2f609e1a30aef4d4db257a3a1913 | 638 | //
// StripeDuration.swift
// Stripe
//
// Created by Andrew Edwards on 5/28/17.
//
//
public enum StripeDuration: String, Codable {
case forever
case once
case repeating
}
// https://stripe.com/docs/api/curl#account_object-payout_schedule-interval
public enum StripePayoutInterval: String, Codable {
case manual
case daily
case weekly
case monthly
}
// https://stripe.com/docs/api/curl#account_object-payout_schedule-weekly_anchor
public enum StripeWeeklyAnchor: String, Codable {
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}
| 19.333333 | 80 | 0.711599 |
8afabf3783f6d578c481f07117bd011d4c076be4 | 1,947 | //
// LogTrackingWebViewController.swift
// TTBaseUIKit
//
// Created by Tuan Truong Quang on 9/11/19.
// Copyright © 2019 Truong Quang Tuan. All rights reserved.
//
import Foundation
class LogTrackingTableViewCell : TTTextSubtextIconTableViewCell {
override var sizeImages: (CGFloat, CGFloat) { return ( 0,0 )}
override var numberOfLineTitle: Int { return 100}
override var numberOfLineSub: Int { return 20 }
override func updateUI() {
super.updateUI()
self.titleLabel.setTextColor(color: TTView.labelBgDef).setFontSize(size: TTFont.SUB_TITLE_H)
self.subLabel.setTextColor(color: TTView.labelBgWar).setFontSize(size: TTFont.SUB_TITLE_H)
}
}
public class LogTrackingWebViewController: TTBaseUIViewController<DarkBaseUIView> {
public override var navType: TTBaseUIViewController<DarkBaseUIView>.NAV_STYLE { return .NO_VIEW}
fileprivate let wkView:TTBaseWKWebView = TTBaseWKWebView()
fileprivate let backButton:TTBaseUIButton = TTBaseUIButton(textString: "BACK", type: .DEFAULT, isSetSize: false)
public override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.wkView)
self.view.addSubview(self.backButton)
self.wkView.translatesAutoresizingMaskIntoConstraints = false
self.wkView.setFullContraints(lead: 0, trail: 0, top: 0, bottom: 0)
if let url = URL(string: "http://jsonviewer.stack.hu/") {
let request = URLRequest(url: url)
wkView.load(request)
}
self.backButton.setWidthAnchor(constant: 200).setHeightAnchor(constant: 40)
.setBottomAnchor(constant: 8, isMarginsGuide: true)
.setCenterXAnchor(constant: 0)
self.backButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return }
strongSelf.dismiss(animated: true, completion: nil)
}
}
}
| 36.735849 | 116 | 0.686697 |
bf89626aab716c260e025463902b9fa89d7c4838 | 417 | //
// LyricFontTests.swift
// MusicXMLTests
//
// Created by James Bean on 10/24/19.
//
import MusicXML
import XCTest
class LyricFontTests: XCTestCase {
func testRoundTrip() throws {
let lyricFont = LyricFont(
Font(family: "Helvetica", style: .italic, size: 42, weight: .bold),
number: 13,
name: "Recitative"
)
try testRoundTrip(lyricFont)
}
}
| 19.857143 | 79 | 0.59952 |
efb27ac7f028c41d7fdd4e5a57898be282e3b3e7 | 1,762 | //
// Utils.swift
// Representor
//
// Created by Kyle Fuller on 18/11/2014.
// Copyright (c) 2014 Apiary. All rights reserved.
//
import Foundation
import Representor
func fixture(_ named:String, forObject:AnyObject) -> Data {
let bundle = Bundle(for:object_getClass(forObject))
let path = bundle.url(forResource: named, withExtension: "json")!
let data = try! Data(contentsOf: path)
return data
}
func JSONFixture(_ named: String, forObject: AnyObject) -> [String: Any] {
let data = fixture(named, forObject: forObject)
let object = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0))
return object as! [String: Any]
}
func PollFixtureAttributes(_ forObject: AnyObject) -> [String: Any] {
return JSONFixture("poll.attributes", forObject: forObject)
}
func PollFixture(_ forObject:AnyObject) -> Representor<HTTPTransition> {
return Representor { builder in
builder.addTransition("self", uri:"/polls/1/")
builder.addTransition("next", uri:"/polls/2/")
builder.addAttribute("question", value: "Favourite programming language?" as AnyObject)
builder.addAttribute("published_at", value: "2014-11-11T08:40:51.620Z" as AnyObject)
builder.addAttribute("choices", value: [
[
"answer": "Swift",
"votes": 2048,
], [
"answer": "Python",
"votes": 1024,
], [
"answer": "Objective-C",
"votes": 512,
], [
"answer": "Ruby",
"votes": 256,
],
] as AnyObject)
builder.addRepresentor("next") { builder in
builder.addTransition("self", uri:"/polls/2/")
builder.addTransition("next", uri:"/polls/3/")
builder.addTransition("previous", uri:"/polls/1/")
}
}
}
| 29.864407 | 116 | 0.654938 |
5b71e08fe11bff96001f23075af0aeb3562cb808 | 2,537 | //
// InjectorRegistration.swift
// ShortcutFoundation
//
// Created by Gabriel Sabadin on 2021-04-26.
// Copyright © 2021 Shortcut Scandinavia Apps AB. All rights reserved.
//
public class InjectorRegistration<T>: InjectorOptions<T> {
public var key: Int
public var cacheKey: String
public init(injector: Injector, key: Int, name: Injector.Name?) {
self.key = key
if let injectionName = name {
self.cacheKey = String(key) + ":" + injectionName.rawValue
} else {
self.cacheKey = String(key)
}
super.init(injector: injector)
}
public func resolve(injector: Injector, args: Any?) -> T? {
fatalError("abstract function")
}
}
public final class InjectorRegistrationOnly<T>: InjectorRegistration<T> {
public var factory: InjectorFactory<T>
public init(injector: Injector, key: Int, name: Injector.Name?, factory: @escaping InjectorFactory<T>) {
self.factory = factory
super.init(injector: injector, key: key, name: name)
}
public final override func resolve(injector: Injector, args: Any?) -> T? {
guard let injection = factory() else {
return nil
}
mutate(injection, injector: injector, args: args)
return injection
}
}
public final class InjectorRegistrationMapping<T>: InjectorRegistration<T> {
public var factory: InjectorFactoryMapping<T>
public init(injector: Injector, key: Int, name: Injector.Name?, factory: @escaping InjectorFactoryMapping<T>) {
self.factory = factory
super.init(injector: injector, key: key, name: name)
}
public final override func resolve(injector: Injector, args: Any?) -> T? {
guard let injection = factory(injector) else {
return nil
}
mutate(injection, injector: injector, args: args)
return injection
}
}
public final class InjectorRegistrationArgumentsN<T>: InjectorRegistration<T> {
public var factory: InjectorFactoryArgumentsN<T>
public init(injector: Injector, key: Int, name: Injector.Name?, factory: @escaping InjectorFactoryArgumentsN<T>) {
self.factory = factory
super.init(injector: injector, key: key, name: name)
}
public final override func resolve(injector: Injector, args: Any?) -> T? {
guard let injection = factory(injector, Injector.Args(args)) else {
return nil
}
mutate(injection, injector: injector, args: args)
return injection
}
}
| 32.113924 | 118 | 0.652739 |
03f187842423bea99b118de2dfce53f383a03ccc | 1,118 | //
// CLKEdgesAnchorGroup.swift
// ConstraintKit
//
// Created by Jed Lewison / Magic App Factory on 1/30/16.
// MIT License All rights reserved.
//
import UIKit
/// An anchor group for constraining to edges. Uses top, bottom, leading, and trailing anchors except with viewController's, where is uses top and bottom layout guides.
public final class CLKEdgesAnchorGroup: CLKAnchorGroup, CLKAnchorGroupSubclassProtocol {
public typealias Constant = UIEdgeInsets
/// Specify insets and/or priority values for the anchor group's constraints. Must be called prior to activation.
public func with(insets: UIEdgeInsets? = nil, priority: UILayoutPriority? = nil) -> Self {
with(insets ?? config.insets, priority: priority ?? config.priority)
return self
}
/// Specify insets and priority values for the anchor group's constraints. Must be called prior to activation.
@objc(withConstant:priority:)
public func with(insets: UIEdgeInsets, priority: UILayoutPriority) -> Self {
config.insets = insets
config.priority = priority
return self
}
} | 37.266667 | 168 | 0.718247 |
72d6fcf91eedb9d1e662a1f1b755a3d1560d2f65 | 4,126 | //
// TabmanBlockTabBar.swift
// Tabman
//
// Created by Merrick Sapsford on 09/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import PureLayout
import Pageboy
/// A button tab bar with a block style indicator behind the selected item.
internal class TabmanBlockTabBar: TabmanStaticButtonBar {
// MARK: Properties
private var buttonContentView: UIView?
private var maskContentView: UIView?
public override var interItemSpacing: CGFloat {
didSet {
let insets = UIEdgeInsets(top: 0.0, left: interItemSpacing / 2, bottom: 0.0, right: interItemSpacing / 2)
self.updateButtonsInView(view: self.buttonContentView) { (button) in
button.titleEdgeInsets = insets
button.imageEdgeInsets = insets
}
self.updateButtonsInView(view: self.maskContentView) { (button) in
button.titleEdgeInsets = insets
button.imageEdgeInsets = insets
}
}
}
override var color: UIColor {
didSet {
guard color != oldValue else {
return
}
self.updateButtonsInView(view: self.buttonContentView, update: { (button) in
button.tintColor = color
button.setTitleColor(color, for: .normal)
})
}
}
override var selectedColor: UIColor {
didSet {
guard selectedColor != oldValue else {
return
}
self.updateButtonsInView(view: self.maskContentView, update: { (button) in
button.tintColor = selectedColor
button.setTitleColor(selectedColor, for: .normal)
})
}
}
override var textFont: UIFont {
didSet {
guard textFont != oldValue else {
return
}
updateButtonsInView(view: self.buttonContentView,
update: { $0.titleLabel?.font = textFont })
updateButtonsInView(view: self.maskContentView,
update: { $0.titleLabel?.font = textFont })
}
}
// MARK: Lifecycle
override public func defaultIndicatorStyle() -> TabmanIndicator.Style {
return .custom(type: TabmanBlockIndicator.self)
}
public override func usePreferredIndicatorStyle() -> Bool {
return false
}
// MARK: TabmanBar Lifecycle
public override func construct(in contentView: UIView,
for items: [TabmanBar.Item]) {
super.construct(in: contentView, for: items)
let buttonContentView = UIView(forAutoLayout: ())
let maskContentView = UIView(forAutoLayout: ())
maskContentView.isUserInteractionEnabled = false
self.contentView.addSubview(buttonContentView)
buttonContentView.autoPinEdgesToSuperviewEdges()
self.contentView.addSubview(maskContentView)
maskContentView.autoPinEdgesToSuperviewEdges()
maskContentView.mask = self.indicatorMaskView
self.addAndLayoutBarButtons(toView: buttonContentView, items: items) { (button, _) in
self.buttons.append(button)
button.addTarget(self, action: #selector(tabButtonPressed(_:)), for: .touchUpInside)
}
self.addAndLayoutBarButtons(toView: maskContentView, items: items) { (button, _) in
button.tintColor = self.selectedColor
button.setTitleColor(self.selectedColor, for: .normal)
}
self.buttonContentView = buttonContentView
self.maskContentView = maskContentView
}
// MARK: Utilities
private func updateButtonsInView(view: UIView?, update: (UIButton) -> Void) {
guard let view = view else {
return
}
for subview in view.subviews {
if let button = subview as? UIButton {
update(button)
}
}
}
}
| 32.234375 | 117 | 0.584828 |
9c468318f70b67a17666bff2212210e71a4fa02d | 13,293 | //
// Issue.swift
//
//
// Created by Nanshi Li on 2022/03/31.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
open class Issue: Codable {
open private(set) var id: Int = -1
open var url: URL?
open var repositoryURL: URL?
@available(*, deprecated)
open var labelsURL: URL?
open var commentsURL: URL?
open var eventsURL: URL?
open var htmlURL: URL?
open var number: Int
open var state: Openness?
open var title: String?
open var body: String?
open var user: GithubUser?
open var assignee: GithubUser?
open var locked: Bool?
open var comments: Int?
open var closedAt: Date?
open var createdAt: Date?
open var updatedAt: Date?
open var closedBy: GithubUser?
enum CodingKeys: String, CodingKey {
case id
case url
case repositoryURL = "repository_url"
case commentsURL = "comments_url"
case eventsURL = "events_url"
case htmlURL = "html_url"
case number
case state
case title
case body
case user
case assignee
case locked
case comments
case closedAt = "closed_at"
case createdAt = "created_at"
case updatedAt = "updated_at"
case closedBy = "closed_by"
}
}
public extension GithubAccount {
/**
Fetches the issues of the authenticated user
- parameter session: GitURLSession, defaults to URLSession.sharedSession()
- parameter state: Issue state. Defaults to open if not specified.
- parameter page: Current page for issue pagination. `1` by default.
- parameter perPage: Number of issues per page. `100` by default.
- parameter completion: Callback for the outcome of the fetch.
*/
@discardableResult
func myIssues(_ session: GitURLSession = URLSession.shared,
state: Openness = .open,
page: String = "1",
perPage: String = "100",
completion: @escaping (
_ response: Result<[Issue], Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.readAuthenticatedIssues(configuration, page, perPage, state)
return router.load(
session,
dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter),
expectedResultType: [Issue].self) { issues, error in
if let error = error {
completion(.failure(error))
} else {
if let issues = issues {
completion(.success(issues))
}
}
}
}
/**
Fetches an issue in a repository
- parameter session: GitURLSession, defaults to URLSession.sharedSession()
- parameter owner: The user or organization that owns the repository.
- parameter repository: The name of the repository.
- parameter number: The number of the issue.
- parameter completion: Callback for the outcome of the fetch.
*/
@discardableResult
func issue(_ session: GitURLSession = URLSession.shared,
owner: String, repository: String,
number: Int,
completion: @escaping (
_ response: Result<Issue, Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.readIssue(configuration, owner, repository, number)
return router.load(
session,
dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter),
expectedResultType: Issue.self) { issue, error in
if let error = error {
completion(.failure(error))
} else {
if let issue = issue {
completion(.success(issue))
}
}
}
}
/**
Fetches all issues in a repository
- parameter session: GitURLSession, defaults to URLSession.sharedSession()
- parameter owner: The user or organization that owns the repository.
- parameter repository: The name of the repository.
- parameter state: Issue state. Defaults to open if not specified.
- parameter page: Current page for issue pagination. `1` by default.
- parameter perPage: Number of issues per page. `100` by default.
- parameter completion: Callback for the outcome of the fetch.
*/
@discardableResult
func issues(_ session: GitURLSession = URLSession.shared,
owner: String,
repository: String,
state: Openness = .open,
page: String = "1",
perPage: String = "100",
completion: @escaping (
_ response: Result<[Issue], Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.readIssues(configuration, owner, repository, page, perPage, state)
return router.load(
session,
dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter),
expectedResultType: [Issue].self) { issues, error in
if let error = error {
completion(.failure(error))
} else {
if let issues = issues {
completion(.success(issues))
}
}
}
}
/**
Creates an issue in a repository.
- parameter session: GitURLSession, defaults to URLSession.sharedSession()
- parameter owner: The user or organization that owns the repository.
- parameter repository: The name of the repository.
- parameter title: The title of the issue.
- parameter body: The body text of the issue in GitHub-flavored Markdown format.
- parameter assignee: The name of the user to assign the issue to.
This parameter is ignored if the user lacks push access to the repository.
- parameter labels: An array of label names to add to the issue. If the labels do not exist,
GitHub will create them automatically.
This parameter is ignored if the user lacks push access to the repository.
- parameter completion: Callback for the issue that is created.
*/
@discardableResult
func postIssue(_ session: GitURLSession = URLSession.shared,
owner: String,
repository: String,
title: String,
body: String? = nil,
assignee: String? = nil,
labels: [String] = [],
completion: @escaping (
_ response: Result<Issue, Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.postIssue(configuration, owner, repository, title, body, assignee, labels)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Time.rfc3339DateFormatter)
return router.post(
session,
decoder: decoder,
expectedResultType: Issue.self) { issue, error in
if let error = error {
completion(.failure(error))
} else {
if let issue = issue {
completion(.success(issue))
}
}
}
}
/**
Edits an issue in a repository.
- parameter session: GitURLSession, defaults to URLSession.sharedSession()
- parameter owner: The user or organization that owns the repository.
- parameter repository: The name of the repository.
- parameter number: The number of the issue.
- parameter title: The title of the issue.
- parameter body: The body text of the issue in GitHub-flavored Markdown format.
- parameter assignee: The name of the user to assign the issue to.
This parameter is ignored if the user lacks push access to the repository.
- parameter state: Whether the issue is open or closed.
- parameter completion: Callback for the issue that is created.
*/
@discardableResult
func patchIssue(_ session: GitURLSession = URLSession.shared,
owner: String,
repository: String,
number: Int,
title: String? = nil,
body: String? = nil,
assignee: String? = nil,
state: Openness? = nil,
completion: @escaping (
_ response: Result<Issue, Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.patchIssue(configuration, owner, repository, number, title, body, assignee, state)
return router.post(
session,
expectedResultType: Issue.self) { issue, error in
if let error = error {
completion(.failure(error))
} else {
if let issue = issue {
completion(.success(issue))
}
}
}
}
/// Posts a comment on an issue using the given body.
/// - Parameters:
/// - session: GitURLSession, defaults to URLSession.sharedSession()
/// - owner: The user or organization that owns the repository.
/// - repository: The name of the repository.
/// - number: The number of the issue.
/// - body: The contents of the comment.
/// - completion: Callback for the comment that is created.
@discardableResult
func commentIssue(_ session: GitURLSession = URLSession.shared,
owner: String,
repository: String,
number: Int,
body: String,
completion: @escaping (
_ response: Result<Comment, Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.commentIssue(configuration, owner, repository, number, body)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Time.rfc3339DateFormatter)
return router.post(
session,
decoder: decoder,
expectedResultType: Comment.self) { issue, error in
if let error = error {
completion(.failure(error))
} else {
if let issue = issue {
completion(.success(issue))
}
}
}
}
/// Fetches all comments for an issue
/// - Parameters:
/// - session: GitURLSession, defaults to URLSession.sharedSession()
/// - owner: The user or organization that owns the repository.
/// - repository: The name of the repository.
/// - number: The number of the issue.
/// - page: Current page for comments pagination. `1` by default.
/// - perPage: Number of comments per page. `100` by default.
/// - completion: Callback for the outcome of the fetch.
@discardableResult
func issueComments(_ session: GitURLSession = URLSession.shared,
owner: String,
repository: String,
number: Int,
page: String = "1",
perPage: String = "100",
completion: @escaping (
_ response: Result<[Comment], Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.readIssueComments(configuration, owner, repository, number, page, perPage)
return router.load(
session,
dateDecodingStrategy: .formatted(Time.rfc3339DateFormatter),
expectedResultType: [Comment].self) { comments, error in
if let error = error {
completion(.failure(error))
} else {
if let comments = comments {
completion(.success(comments))
}
}
}
}
/// Edits a comment on an issue using the given body.
/// - Parameters:
/// - session: GitURLSession, defaults to URLSession.sharedSession()
/// - owner: The user or organization that owns the repository.
/// - repository: The name of the repository.
/// - number: The number of the comment.
/// - body: The contents of the comment.
/// - completion: Callback for the comment that is created.
@discardableResult
func patchIssueComment(
_ session: GitURLSession = URLSession.shared,
owner: String,
repository: String,
number: Int,
body: String,
completion: @escaping (
_ response: Result<Comment, Error>) -> Void) -> URLSessionDataTaskProtocol? {
let router = IssueRouter.patchIssueComment(configuration, owner, repository, number, body)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Time.rfc3339DateFormatter)
return router.post(
session, decoder: decoder,
expectedResultType: Comment.self) { issue, error in
if let error = error {
completion(.failure(error))
} else {
if let issue = issue {
completion(.success(issue))
}
}
}
}
}
| 37.764205 | 115 | 0.578951 |
acd2b19a3b7986bdb69c00e038141c29c524cbaf | 313 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
| 18.411765 | 87 | 0.619808 |
3838cd814fdc27f33c4796d6628452b43beabc6d | 12,047 | //
// CurrencyPicker.swift
// MyMonero
//
// Created by Paul Shapiro on 10/19/17.
// Copyright © 2014-2018 MyMonero. All rights reserved.
//
// 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 nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import UIKit
//
extension UICommonComponents.Form.Amounts
{
struct CurrencyPicker {}
}
//
extension UICommonComponents.Form.Amounts.CurrencyPicker
{
class PickerButton: UIButton
{
//
// Common - Constants
static let disclosureArrow_w: CGFloat = 8
static let disclosureArrow_margin_right: CGFloat = 6
static let disclosureArrow_margin_left: CGFloat = 6
static let selectText_margin_left: CGFloat = 9
static let selectText_w: CGFloat = 28
static let fixedWidth: CGFloat
= selectText_margin_left + selectText_w + disclosureArrow_margin_left + disclosureArrow_w + disclosureArrow_margin_right
//
// Interface - Properties
var selectedCurrency: CcyConversionRates.Currency = SettingsController.shared.displayCurrency
var didUpdateSelection_fn: (() -> Void)?
//
// Internal - Properties
var mask_shapeLayer: CAShapeLayer!
var pickerView: PickerView!
var picker_inputField: UITextField!
//
// Interface - Lifecycle
init()
{
super.init(frame: .zero) // whoever instantiates is responsible for sizing even tho cornerRadius is fixed within self… maybe time to bring size in
self.setup()
}
//
// Internal - Lifecycle
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()
{
self.setup_layerMask()
//
self.titleEdgeInsets = UIEdgeInsets.init(
top: 0,
left: -PickerButton.selectText_w + PickerButton.selectText_margin_left,
bottom: 0,
right: 0//PickerButton.disclosureArrow_margin_left + PickerButton.disclosureArrow_w + PickerButton.disclosureArrow_margin_right
//+ 4 // not sure why this is necessary - basically a difference to JS/HTML
)
self.titleLabel!.textAlignment = .left
self.titleLabel!.font = UIFont.smallSemiboldSansSerif
self.setTitleColor(
UIColor(rgb: 0xDFDEDF), // or 0x989698; TODO: obtain from theme controller / UIColor + listen
for: .normal
)
//
self.setImage(
UIImage(named: "smallSelect_disclosureArrow")!,
for: .normal
)
self.imageEdgeInsets = UIEdgeInsets.init(
top: 0,
left: PickerButton.selectText_margin_left + PickerButton.selectText_w + PickerButton.disclosureArrow_margin_left,
bottom: 0,
right: 0
)
//
self.configureBackgroundColor()
//
do {
let view = PickerView()
view.didSelect_fn =
{ [unowned self] (currency) in
self.set(
selectedCurrency: currency,
skipSettingOnPickerView: true // because we got this from the picker view
)
}
self.pickerView = view
}
do {
let view = UITextField(frame: .zero) // invisible - and possibly wouldn't work if hidden
view.inputView = self.pickerView
self.picker_inputField = view
self.addSubview(view)
}
do {
self.configureTitleWith_selectedCurrency()
self.pickerView.selectWithoutYielding(currencySymbol: self.selectedCurrency.symbol) // must do initial config!
}
do {
self.addTarget(self, action: #selector(tapped), for: .touchUpInside)
}
}
func setup_layerMask()
{
let shapeLayer = CAShapeLayer()
self.mask_shapeLayer = shapeLayer
shapeLayer.frame = self.bounds
shapeLayer.path = self._new_mask_cgPath
self.layer.mask = shapeLayer
}
//
// Overrides - Accessors/Derived Properties
override open var isHighlighted: Bool {
didSet {
self.configureBackgroundColor()
}
}
override open var isEnabled: Bool {
didSet {
self.configureBackgroundColor()
}
}
//
// Internal - Accessors/Constants
let backgroundColor_normal = UICommonComponents.HighlightableCells.Variant.normal.visualEquivalentSemiOpaque_contentBackgroundColor
let backgroundColor_highlighted = UICommonComponents.HighlightableCells.Variant.highlighted.contentBackgroundColor
let backgroundColor_disabled = UICommonComponents.HighlightableCells.Variant.disabled.contentBackgroundColor
//
var _new_mask_cgPath: CGPath {
return UIBezierPath(
roundedRect: self.bounds,
byRoundingCorners: [ .topRight, .bottomRight ],
cornerRadii: CGSize(
width: UICommonComponents.FormInputCells.background_outlineInternal_cornerRadius,
height: UICommonComponents.FormInputCells.background_outlineInternal_cornerRadius
)
).cgPath
}
//
// Overrides - Imperatives
override func layoutSubviews()
{
super.layoutSubviews()
self.mask_shapeLayer.frame = self.bounds // TODO: must this be updated?
self.mask_shapeLayer.path = self._new_mask_cgPath // figure this must be updated since it involves the bounds
}
//
// Internal - Imperatives
func configureBackgroundColor()
{
self.backgroundColor = self.isEnabled ? self.isHighlighted ? self.backgroundColor_highlighted : self.backgroundColor_normal : self.backgroundColor_disabled
}
func configureTitleWith_selectedCurrency()
{
self.setTitle(self.selectedCurrency.symbol.uppercased(), for: .normal)
}
//
// Imperatives - Config
func set(
selectedCurrency currency: CcyConversionRates.Currency,
skipSettingOnPickerView: Bool = false // leave as false if you're setting from anywhere but the PickerView
)
{
self.selectedCurrency = currency
self.configureTitleWith_selectedCurrency()
if skipSettingOnPickerView == false {
self.pickerView.selectWithoutYielding(currencySymbol: currency.symbol)
}
//
if let fn = self.didUpdateSelection_fn {
fn()
}
}
//
// Delegation - Interactions
@objc func tapped()
{
if self.picker_inputField.isFirstResponder {
self.picker_inputField.resignFirstResponder()
// TODO: or just return?
//
} else {
self.picker_inputField.becomeFirstResponder()
}
}
}
//
class PickerView: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource
{
//
// Properties
var didSelect_fn: ((_ value: CcyConversionRates.Currency) -> Void)?
//
// Lifecycle
init()
{
super.init(frame: .zero)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()
{
self.backgroundColor = .customKeyboardBackgroundColor
self.delegate = self
self.dataSource = self
//
self.startObserving()
}
func startObserving()
{
}
//
deinit
{
self.teardown()
}
func teardown()
{
self.stopObserving()
}
func stopObserving()
{
// no changes to list expected
}
//
// Accessors
var selectedCurrency: CcyConversionRates.Currency { // always expecting a selection b/c list is predecided
let selectedIndex = self.selectedRow(inComponent: 0)
if selectedIndex == -1 {
fatalError("CurrencyPicker selectedRow unexpectedly -1")
}
let records = self.rowValues
if records.count <= selectedIndex {
fatalError("CurrencyPicker.PickerView has non -1 selectedIndex but too few records for the selectedIndex to be correct.")
}
let selectedCurrencySymbol = records[selectedIndex] as CcyConversionRates.CurrencySymbol
let selectedCurrency = CcyConversionRates.Currency(rawValue: selectedCurrencySymbol)! // we assume this is always correct b/c we got the symbols straight from the code, not external input
//
return selectedCurrency
}
var rowValues: [CcyConversionRates.CurrencySymbol] {
return CcyConversionRates.Currency.lazy_allCurrencySymbols // b/c using allCurrencies and converting to raw values might be less efficient
}
//
// Imperatives - Interface - Setting wallet externally
func selectWithoutYielding(currencySymbol: CcyConversionRates.CurrencySymbol)
{
let rowIndex = self.rowValues.index(
of: currencySymbol
)!
self.selectRow(
rowIndex,
inComponent: 0,
animated: false
) // not pickWallet(atRow:) b/c that will merely notify
}
//
// Delegation - Yielding
func didPick(rowAtIndex rowIndex: Int)
{
let record = self.rowValues[rowIndex] as CcyConversionRates.CurrencySymbol
if let fn = self.didSelect_fn {
let selectedCurrency = CcyConversionRates.Currency(rawValue: record)!
fn(selectedCurrency)
}
}
//
// Delegation - UIPickerView
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return CcyConversionRates.Currency.lazy_allCurrencies.count
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
{
return PickerCellContentView.h
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
self.didPick(rowAtIndex: row)
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat
{
let safeAreaInsets = pickerView.polyfilled_safeAreaInsets // important…
let w = pickerView.frame.size.width - safeAreaInsets.left - safeAreaInsets.right - 2*CGFloat.form_input_margin_x
//
return w
}
func pickerView(
_ pickerView: UIPickerView,
viewForRow row: Int,
forComponent component: Int,
reusing view: UIView?
) -> UIView {
var mutable_view: UIView? = view
if mutable_view == nil {
mutable_view = PickerCellContentView()
}
let cellView = mutable_view as! PickerCellContentView
let record = self.rowValues[row] as CcyConversionRates.CurrencySymbol
cellView.configure(withObject: record)
//
return cellView
}
}
class PickerCellContentView: UIView
{
//
// Interface - Constants
static let h: CGFloat = 42
//
// Internal - Properties
var label: UILabel!
//
// Interface - Init
init()
{
super.init(frame: .zero)
self.setup()
}
//
// Internal - Init
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()
{
self.backgroundColor = .customKeyboardBackgroundColor
do {
let view = UILabel(frame: .zero)
view.textAlignment = .center
view.font = UIFont.keyboardContentSemiboldSansSerif
view.textColor = UIColor(rgb: 0xF8F7F8) // TODO: obtain from theme controller / UIColor + listen
self.label = view
self.addSubview(view)
}
}
//
// Overrides - Layout
override func layoutSubviews()
{
super.layoutSubviews()
self.label.frame = self.bounds
}
//
// Interface - Imperatives
func configure(withObject object: CcyConversionRates.CurrencySymbol)
{
self.label.text = object
}
}
}
| 31.129199 | 190 | 0.726156 |
c169cad5f441b4443d878ef5826238c0e263c7ba | 2,519 | //
// UIColor-YPExtension.swift
// YPPageView
//
// Created by 赖永鹏 on 2018/11/26.
// Copyright © 2018年 LYP. All rights reserved.
//
import UIKit
extension UIColor{
/*
在extension中扩充构造函数,只能扩充便利构造函数
1 > 在init前添加convenience
2 > 在自定义的构造函数中,必须通过调用self.init()调用其他函数
函数的重载
1 > 函数名相同。但是参数不同
2 > 参数不同的有两层函数:1)参数的类型不同 2)参数的个数不同
*/
convenience init(r : CGFloat,g : CGFloat,b : CGFloat,alpha : CGFloat = 1.0){
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
}
// 类方法
class var randomColor: UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)), alpha: 1.0)
}
convenience init?(hex : String,alpha : CGFloat = 1.0){
// ff0011
// 0xFF0011
// ##ff0022
// 1.判断字符串长度是否大于等于6
guard hex.characters.count >= 6 else {
return nil
}
// 2.将所有的字符串转成大写
var hexString = hex.uppercased()
// 3.判断是否以0x/##
if (hexString.hasPrefix("##") || hexString.hasPrefix("0x")) {
// as 将String类型转成NSString
hexString = (hexString as NSString).substring(from: 2)
}
// 4.判断是否以#开头
if (hexString.hasPrefix("#")) {
// as 将String类型转成NSString
hexString = (hexString as NSString).substring(from: 1)
}
// FF0011
// 结构体是值类型 类是引用类型
// 5.获取RGB的字符串
var range = NSRange(location: 0, length: 2)
let rStr = (hexString as NSString).substring(with: range)
range.location = 2
let gStr = (hexString as NSString).substring(with: range)
range.location = 4
let bStr = (hexString as NSString).substring(with: range)
// 6.转成10进制的值
// UnsafeMutablePointer : 指针/地址
var r : UInt32 = 0
var g : UInt32 = 0
var b : UInt32 = 0
Scanner(string: rStr).scanHexInt32(&r)
Scanner(string: gStr).scanHexInt32(&g)
Scanner(string: bStr).scanHexInt32(&b)
self.init(r : CGFloat(r), g : CGFloat(g), b : CGFloat(b), alpha : alpha)
}
func getRGB() -> (CGFloat,CGFloat,CGFloat) {
var red : CGFloat = 0
var green : CGFloat = 0
var blue : CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: nil)
return (red * 255,green * 255, blue * 255)
}
}
| 28.625 | 145 | 0.547836 |
3371c7c15976b19b59961bec28769c0732313be9 | 1,545 | //
// ViewProducer.swift
// CombineRextensions
//
// Created by Luis Reisewitz on 12.02.20.
// Copyright © 2020 Lautsprecher Teufel GmbH. All rights reserved.
//
import SwiftUI
/// Defines a function mapping some state context to a View.
/// Can be used by ViewModels to map navigation anchor points to their views.
public struct ViewProducer<Context, ProducedView: View> {
/// Runs the function that produces a View from the state context
public let run: (Context) -> ProducedView
/// Init with the function that produces a View from some state context
public init(_ run: @escaping (Context) -> ProducedView) {
self.run = run
}
}
extension ViewProducer {
public func view(_ context: Context) -> ProducedView {
self.run(context)
}
}
extension ViewProducer where Context == Void {
public func view() -> ProducedView {
self.run(())
}
}
extension ViewProducer {
/// Identity case for the ViewProducer, ignoring the state and always rendering the provided view
/// Can be used in ViewModels to map navigation anchor points to their views.
public static func pure(_ view: ProducedView) -> ViewProducer {
.init { _ in view }
}
}
extension ViewProducer where ProducedView == EmptyView {
/// Identity case for the ViewProducer, ignoring the state and always rendering an EmptyView
/// Can be used in ViewModels to map navigation anchor points to their views.
public static func pure() -> ViewProducer {
.init { _ in EmptyView() }
}
}
| 30.9 | 101 | 0.691262 |
6a8ba206be81ea4324f2fffda3c88da1b37136d0 | 563 | //
// CategoryTableViewCell.swift
// DominoPizzaExam
//
// Created by chang sic jung on 26/04/2019.
// Copyright © 2019 Kira. All rights reserved.
//
import UIKit
class CategoryTableViewCell: UITableViewCell {
@IBOutlet weak var categoryImageView: UIImageView!
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
}
}
| 21.653846 | 65 | 0.680284 |
d987a1782fb6da3367633488b9b7f4d305184149 | 2,800 | //
// DiscardTouchViewSpec.swift
// bytes
//
// Created by Cornelius Horstmann on 01.11.16.
// Copyright © 2016 TBO INTERACTIVE GmbH & Co. KG. All rights reserved.
//
import bytes
import Quick
import Nimble
class DiscardTouchViewSpec: QuickSpec {
override func spec() {
describe("discardTouches") {
it("should be true per default") {
let discardTouchView = DiscardTouchView()
expect(discardTouchView.discardsTouches) == true
}
}
describe("hitTest") {
context("with no subviews and discardTouches to true") {
let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
it("should always return nil") {
expect(discardTouchView.hitTest(CGPoint(x: 0, y: 0), with: nil)).to(beNil())
}
}
context("with no subviews and discardTouches to false") {
let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
discardTouchView.discardsTouches = false
it("should always return itself") {
expect(discardTouchView.hitTest(CGPoint(x: 0, y: 0), with: nil)) == discardTouchView
}
}
context("with a subview and discardTouches to true") {
let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
discardTouchView.addSubview(UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5)))
it("should always return nil if the hit test doesn't hit the subview") {
expect(discardTouchView.hitTest(CGPoint(x: 1, y: 6), with: nil)).to(beNil())
}
it("should return the subview that has been hit") {
expect(discardTouchView.hitTest(CGPoint(x: 1, y: 1), with: nil)) == discardTouchView.subviews.first
}
}
context("with a subview and discardTouches to false") {
let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
discardTouchView.addSubview(UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5)))
discardTouchView.discardsTouches = false
it("should always return itself if the hit test doesn't hit the subview") {
expect(discardTouchView.hitTest(CGPoint(x: 1, y: 6), with: nil)) == discardTouchView
}
it("should return the subview that has been hit") {
expect(discardTouchView.hitTest(CGPoint(x: 1, y: 1), with: nil)) == discardTouchView.subviews.first
}
}
}
}
}
| 46.666667 | 119 | 0.567143 |
1c725da678d9b903598e27352897f5e2752f7e21 | 1,852 | /*
* Copyright (C) 2019 ProSiebenSat1.Digital GmbH.
*
* 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 JavaScriptCore
public protocol JavascriptCallbackProtocol: AnyObject {
func onResult(value: JSValue?, error: JSValue?)
}
/**
* Use JavascriptCallback to pass callback functions to
* javascriptInterpreter.evaluate(functionName:parameters:)
* with a signature callback(T, NSError).
*
* We can't pass Swift closures directly, because there's no way
* to make those typed with generics.
* Therefore as a workaround JavascriptCallback<T> has been created.
*/
public class JavascriptCallback<T: Codable> : JavascriptCallbackProtocol {
var callback: ((_: T?, _: JSBridgeError?) -> Void)
public init(callback: @escaping ((_: T?, _: JSBridgeError?) -> Void)) {
self.callback = callback
}
public func onResult(value: JSValue?, error: JSValue?) {
guard let value = value, !value.isUndefined, !value.isNull else {
callback(nil, JSBridgeError.from(jsValue: error))
return
}
let converter = JavascriptConverter<T>(value: value)
if let convertedObject = converter.swiftObject() {
callback(convertedObject, nil)
} else {
callback(nil, JSBridgeError(type: .jsConversionFailed))
}
}
}
| 34.296296 | 75 | 0.696004 |
085f5290aa3658ddcf4634d70a1a3b453d4db01f | 199 | //
// __PRESENTER__.swift
// Kuri
//
// Created by __USERNAME__ on __DATE__.
// Copyright © 2016年 __USERNAME__. All rights reserved.
//
import Foundation
protocol __PRESENTER__: class {
}
| 14.214286 | 56 | 0.693467 |
4a0d21342ccdc5ee3020a7d09b11a498ff66c964 | 2,712 | // Please keep this file in alphabetical order!
// REQUIRES: objc_interop
// RUN: %empty-directory(%t)
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift
// FIXME: END -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -import-objc-header %S/Inputs/newtype.h -emit-module -o %t %s
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -import-objc-header %S/Inputs/newtype.h -parse-as-library %t/newtype.swiftmodule -typecheck -emit-objc-header-path %t/newtype.h
// RUN: %FileCheck %s < %t/newtype.h
// RUN: %check-in-clang %t/newtype.h
// RUN: %check-in-clang -fno-modules -Qunused-arguments %t/newtype.h
import Foundation
// CHECK-LABEL: @interface TestEnumLike : NSObject
class TestEnumLike : NSObject {
// CHECK: - (void)takesNewtype:(EnumLikeStringWrapper _Nonnull)a;
@objc func takesNewtype(_ a: EnumLikeStringWrapper) {}
// CHECK: - (void)takesNewtypeArray:(NSArray<EnumLikeStringWrapper> * _Nonnull)a;
@objc func takesNewtypeArray(_ a: [EnumLikeStringWrapper]) {}
// CHECK: - (void)takesNewtypeDictionary:(NSDictionary<EnumLikeStringWrapper, EnumLikeStringWrapper> * _Nonnull)a;
@objc func takesNewtypeDictionary(_ a: [EnumLikeStringWrapper: EnumLikeStringWrapper]) {}
// CHECK: - (void)takesNewtypeOptional:(EnumLikeStringWrapper _Nullable)a;
@objc func takesNewtypeOptional(_ a: EnumLikeStringWrapper?) {}
}
// CHECK: @end
// CHECK-LABEL: @interface TestStructLike : NSObject
class TestStructLike : NSObject {
// CHECK: - (void)takesNewtype:(StructLikeStringWrapper _Nonnull)a;
@objc func takesNewtype(_ a: StructLikeStringWrapper) {}
// CHECK: - (void)takesNewtypeArray:(NSArray<StructLikeStringWrapper> * _Nonnull)a;
@objc func takesNewtypeArray(_ a: [StructLikeStringWrapper]) {}
// CHECK: - (void)takesNewtypeDictionary:(NSDictionary<StructLikeStringWrapper, StructLikeStringWrapper> * _Nonnull)a;
@objc func takesNewtypeDictionary(_ a: [StructLikeStringWrapper: StructLikeStringWrapper]) {}
// CHECK: - (void)takesNewtypeOptional:(StructLikeStringWrapper _Nullable)a;
@objc func takesNewtypeOptional(_ a: StructLikeStringWrapper?) {}
}
// CHECK: @end
| 55.346939 | 212 | 0.742625 |
b97a7859279eecfa7b911c6fe772359fc54a0004 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct Q<T {
{
}
struct Q<c : f
func f: T {
}
func a<l : a
| 19 | 87 | 0.70614 |
50623a88571396f6c5630f6e614b14754e78db3c | 2,479 | //
// KSMarketTradeCell.swift
// ZeroShare
//
// Created by saeipi on 2019/8/28.
// Copyright © 2019 saeipi. All rights reserved.
//
import UIKit
let KSMarketTradeCellIdentifier = "KSMarketTradeCellIdentifier"
class KSMarketTradeCell: KSBaseTableViewCell {
var labelView: KSDoubleLabelView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class func initialize(tableView:UITableView) -> KSMarketTradeCell {
var cell = tableView.dequeueReusableCell(withIdentifier: KSMarketTradeCellIdentifier)
if cell == nil {
cell = KSMarketTradeCell.init(style: UITableViewCell.CellStyle.value1, reuseIdentifier: KSMarketTradeCellIdentifier)
cell?.selectionStyle = .none
}
return cell as! KSMarketTradeCell
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/// 初始化默认值
override func defaultValue() {
}
/// 创建子控件
override func createChildViews() {
labelView = KSDoubleLabelView.init(textColor: UIColor.ks_rgba(41, 44, 51),
textFont: KS_Const_Font_Normal_14,
alignments: [NSTextAlignment.left,NSTextAlignment.center,NSTextAlignment.right,NSTextAlignment.right],
count: 4,
widthScales: [0.23,0.13,0.32,0.32],
margin: KS_Const_Point16,
padding: KS_Const_Point04)
if let _font = KS_Const_Font_HelveticaNeue_14 {
labelView.update(font: _font)
}
self.addSubview(labelView)
labelView.snp.makeConstraints { (make) in
make.edges.equalTo(0)
}
}
func update(detail: KSTradeDetail) {
labelView.update(attributedTexts: detail.displayTexts)
//labelView.update(texts: detail.displayTexts)
//labelView.update(textColor: detail.textColor, index: 1)
//labelView.update(textColor: detail.textColor, index: 2)
}
}
| 34.430556 | 145 | 0.602662 |
1c22f139a73247743fe5dd15c2a6beddad62a698 | 7,788 | //
// File.swift
//
//
// Created by Olga Lidman on 12.05.2021.
//
import Foundation
import UIKit
public extension SQExtensions where Base: UIDevice {
/// Check if device has narrow screen (like iPhone 5/5c/5s/SE)
static var isNarrowScreen: Bool {
return UIScreen.sq.width == 568.0 || UIScreen.sq.width == 320.0
}
/// Current screen orientation
static var isLandscape: Bool {
return UIDevice.current.orientation.isValidInterfaceOrientation ?
UIDevice.current.orientation.isLandscape : UIApplication.shared.statusBarOrientation.isLandscape
}
/// Status bar height
static var statusBarHeight: CGFloat {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? .zero
} else {
return UIApplication.shared.statusBarFrame.height
}
}
/// Device model identifier
static var modelIdentifier: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
/// Device model name
static var modelName: String {
return self.mapToDevice(identifier: self.modelIdentifier)
}
private static func mapToDevice(identifier: String) -> String {
#if os(iOS)
switch identifier {
// MARK: - iPods
case "iPod5,1": return "iPod touch (5th generation)"
case "iPod7,1": return "iPod touch (6th generation)"
case "iPod9,1": return "iPod touch (7th generation)"
// MARK: - iPhones
case "iPhone3,1": return "iPhone 4"
case "iPhone3,2": return "iPhone 4 GSM Rev A"
case "iPhone3,3": return "iPhone 4 CDMA"
case "iPhone4,1": return "iPhone 4S"
case "iPhone5,1": return "iPhone 5 (GSM)"
case "iPhone5,2": return "iPhone 5 (GSM+CDMA)"
case "iPhone5,3": return "iPhone 5C (GSM)"
case "iPhone5,4": return "iPhone 5C (Global)"
case "iPhone6,1": return "iPhone 5S (GSM)"
case "iPhone6,2": return "iPhone 5S (Global)"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3": return "iPhone X Global"
case "iPhone10,6": return "iPhone X GSM"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4": return "iPhone XS Max"
case "iPhone11,6": return "iPhone XS Max Global"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE (2nd generation)"
case "iPhone13,1": return "iPhone 12 mini"
case "iPhone13,2": return "iPhone 12"
case "iPhone13,3": return "iPhone 12 Pro"
case "iPhone13,4": return "iPhone 12 Pro Max"
case "iPhone14,2": return "iPhone 13 Pro"
case "iPhone14,3": return "iPhone 13 Pro Max"
case "iPhone14,4": return "iPhone 13 Mini"
case "iPhone14,5": return "iPhone 13"
// MARK: - iPads
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)"
case "iPad6,11", "iPad6,12": return "iPad (5th generation)"
case "iPad7,5", "iPad7,6": return "iPad (6th generation)"
case "iPad7,11", "iPad7,12": return "iPad (7th generation)"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad11,4", "iPad11,5": return "iPad Air (3rd generation)"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3"
case "iPad5,1", "iPad5,2": return "iPad mini 4"
case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)"
case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)"
case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)"
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return "iPad Pro (11-inch)"
case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)"
case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)"
case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)"
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return "iPad Pro (12.9-inch) (3rd generation)"
case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
case "i386", "x86_64", "arm64": return "Simulator \(self.mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))"
default: return identifier
}
#elseif os(tvOS)
switch identifier {
case "AppleTV5,3": return "Apple TV 4"
case "AppleTV6,2": return "Apple TV 4K"
case "i386", "x86_64", "arm64": return "Simulator \(self.mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))"
default: return identifier
}
#endif
}
}
| 57.688889 | 173 | 0.476888 |
ac264bd25fb46cb1e5312334d8b55ce55ca6bc51 | 465 | //
// ViewController.swift
// Modular_MacOS
//
// Created by Ondrej Rafaj on 03/12/2017.
// Copyright © 2017 manGoweb UK. All rights reserved.
//
import Cocoa
import Modular
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let canvas1 = NSBox()
canvas1.title = "Modular test!"
canvas1.place.on(view).with.top().bottom().and.sides()
canvas1.debug.constraints()
}
}
| 17.884615 | 62 | 0.645161 |
64b0229e19020f9d5aeab08ebbdc38588f4a39dd | 11,844 | /*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import EchoImplementation
import EchoModel
import SwiftGRPC
import HelloWorldModel
import NIOCore
import NIOHPACK
import NIOPosix
import SwiftProtobuf
import XCTest
class InterceptorsTests: GRPCTestCase {
private var group: EventLoopGroup!
private var server: Server!
private var connection: ClientConnection!
private var echo: Echo_EchoClient!
override func setUp() {
super.setUp()
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.server = try! Server.insecure(group: self.group)
.withServiceProviders([
EchoProvider(),
HelloWorldProvider(interceptors: HelloWorldServerInterceptorFactory()),
])
.withLogger(self.serverLogger)
.bind(host: "localhost", port: 0)
.wait()
self.connection = ClientConnection.insecure(group: self.group)
.withBackgroundActivityLogger(self.clientLogger)
.connect(host: "localhost", port: self.server.channel.localAddress!.port!)
self.echo = Echo_EchoClient(
channel: self.connection,
defaultCallOptions: CallOptions(logger: self.clientLogger),
interceptors: ReversingInterceptors()
)
}
override func tearDown() {
super.tearDown()
XCTAssertNoThrow(try self.connection.close().wait())
XCTAssertNoThrow(try self.server.close().wait())
XCTAssertNoThrow(try self.group.syncShutdownGracefully())
}
func testEcho() {
let get = self.echo.get(.with { $0.text = "hello" })
assertThat(try get.response.wait(), .is(.with { $0.text = "hello :teg ohce tfiwS" }))
assertThat(try get.status.wait(), .hasCode(.ok))
}
func testCollect() {
let collect = self.echo.collect()
collect.sendMessage(.with { $0.text = "1 2" }, promise: nil)
collect.sendMessage(.with { $0.text = "3 4" }, promise: nil)
collect.sendEnd(promise: nil)
assertThat(try collect.response.wait(), .is(.with { $0.text = "3 4 1 2 :tcelloc ohce tfiwS" }))
assertThat(try collect.status.wait(), .hasCode(.ok))
}
func testExpand() {
let expand = self.echo.expand(.with { $0.text = "hello" }) { response in
// Expand splits on spaces, so we only expect one response.
assertThat(response, .is(.with { $0.text = "hello :)0( dnapxe ohce tfiwS" }))
}
assertThat(try expand.status.wait(), .hasCode(.ok))
}
func testUpdate() {
let update = self.echo.update { response in
// We'll just send the one message, so only expect one response.
assertThat(response, .is(.with { $0.text = "hello :)0( etadpu ohce tfiwS" }))
}
update.sendMessage(.with { $0.text = "hello" }, promise: nil)
update.sendEnd(promise: nil)
assertThat(try update.status.wait(), .hasCode(.ok))
}
func testSayHello() {
let greeter = Helloworld_GreeterClient(
channel: self.connection,
defaultCallOptions: CallOptions(logger: self.clientLogger)
)
// Make a call without interceptors.
let notAuthed = greeter.sayHello(.with { $0.name = "World" })
assertThat(try notAuthed.response.wait(), .throws())
assertThat(
try notAuthed.trailingMetadata.wait(),
.contains("www-authenticate", ["Magic"])
)
assertThat(try notAuthed.status.wait(), .hasCode(.unauthenticated))
// Add an interceptor factory.
greeter.interceptors = HelloWorldClientInterceptorFactory(client: greeter)
// Make sure we break the reference cycle.
defer {
greeter.interceptors = nil
}
// Try again with the not-really-auth interceptor:
let hello = greeter.sayHello(.with { $0.name = "PanCakes" })
assertThat(
try hello.response.map { $0.message }.wait(),
.is(.equalTo("Hello, PanCakes, you're authorized!"))
)
assertThat(try hello.status.wait(), .hasCode(.ok))
}
}
// MARK: - Helpers
class HelloWorldProvider: Helloworld_GreeterProvider {
var interceptors: Helloworld_GreeterServerInterceptorFactoryProtocol?
init(interceptors: Helloworld_GreeterServerInterceptorFactoryProtocol? = nil) {
self.interceptors = interceptors
}
func sayHello(
request: Helloworld_HelloRequest,
context: StatusOnlyCallContext
) -> EventLoopFuture<Helloworld_HelloReply> {
// Since we're auth'd, the 'userInfo' should have some magic set.
assertThat(context.userInfo.magic, .is("Magic"))
let response = Helloworld_HelloReply.with {
$0.message = "Hello, \(request.name), you're authorized!"
}
return context.eventLoop.makeSucceededFuture(response)
}
}
private class HelloWorldClientInterceptorFactory:
Helloworld_GreeterClientInterceptorFactoryProtocol {
var client: Helloworld_GreeterClient
init(client: Helloworld_GreeterClient) {
self.client = client
}
func makeSayHelloInterceptors(
) -> [ClientInterceptor<Helloworld_HelloRequest, Helloworld_HelloReply>] {
return [NotReallyAuthClientInterceptor(client: self.client)]
}
}
class RemoteAddressExistsInterceptor<Request, Response>: ServerInterceptor<Request, Response> {
override func receive(
_ part: GRPCServerRequestPart<Request>,
context: ServerInterceptorContext<Request, Response>
) {
XCTAssertNotNil(context.remoteAddress)
super.receive(part, context: context)
}
}
class NotReallyAuthServerInterceptor<Request: Message, Response: Message>:
ServerInterceptor<Request, Response> {
override func receive(
_ part: GRPCServerRequestPart<Request>,
context: ServerInterceptorContext<Request, Response>
) {
switch part {
case let .metadata(headers):
if let auth = headers.first(name: "authorization"), auth == "Magic" {
context.userInfo.magic = auth
context.receive(part)
} else {
// Not auth'd. Fail the RPC.
let status = GRPCStatus(code: .unauthenticated, message: "You need some magic auth!")
let trailers = HPACKHeaders([("www-authenticate", "Magic")])
context.send(.end(status, trailers), promise: nil)
}
case .message, .end:
context.receive(part)
}
}
}
class HelloWorldServerInterceptorFactory: Helloworld_GreeterServerInterceptorFactoryProtocol {
func makeSayHelloInterceptors(
) -> [ServerInterceptor<Helloworld_HelloRequest, Helloworld_HelloReply>] {
return [RemoteAddressExistsInterceptor(), NotReallyAuthServerInterceptor()]
}
}
class NotReallyAuthClientInterceptor<Request: Message, Response: Message>:
ClientInterceptor<Request, Response> {
private let client: Helloworld_GreeterClient
private enum State {
// We're trying the call, these are the parts we've sent so far.
case trying([GRPCClientRequestPart<Request>])
// We're retrying using this call.
case retrying(Call<Request, Response>)
}
private var state: State = .trying([])
init(client: Helloworld_GreeterClient) {
self.client = client
}
override func cancel(
promise: EventLoopPromise<Void>?,
context: ClientInterceptorContext<Request, Response>
) {
switch self.state {
case .trying:
context.cancel(promise: promise)
case let .retrying(call):
call.cancel(promise: promise)
context.cancel(promise: nil)
}
}
override func send(
_ part: GRPCClientRequestPart<Request>,
promise: EventLoopPromise<Void>?,
context: ClientInterceptorContext<Request, Response>
) {
switch self.state {
case var .trying(parts):
// Record the part, incase we need to retry.
parts.append(part)
self.state = .trying(parts)
// Forward the request part.
context.send(part, promise: promise)
case let .retrying(call):
// We're retrying, send the part to the retry call.
call.send(part, promise: promise)
}
}
override func receive(
_ part: GRPCClientResponsePart<Response>,
context: ClientInterceptorContext<Request, Response>
) {
switch self.state {
case var .trying(parts):
switch part {
// If 'authentication' fails this is the only part we expect, we can forward everything else.
case let .end(status, trailers) where status.code == .unauthenticated:
// We only know how to deal with magic.
guard trailers.first(name: "www-authenticate") == "Magic" else {
// We can't handle this, fail.
context.receive(part)
return
}
// We know how to handle this: make a new call.
let call: Call<Request, Response> = self.client.channel.makeCall(
path: context.path,
type: context.type,
callOptions: context.options,
// We could grab interceptors from the client, but we don't need to.
interceptors: []
)
// We're retying the call now.
self.state = .retrying(call)
// Invoke the call and redirect responses here.
call.invoke(onError: context.errorCaught(_:), onResponsePart: context.receive(_:))
// Parts must contain the metadata as the first item if we got that first response.
if case var .some(.metadata(metadata)) = parts.first {
metadata.replaceOrAdd(name: "authorization", value: "Magic")
parts[0] = .metadata(metadata)
}
// Now replay any requests on the retry call.
for part in parts {
call.send(part, promise: nil)
}
default:
context.receive(part)
}
case .retrying:
// Ignore anything we receive on the original call.
()
}
}
}
class EchoReverseInterceptor: ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> {
override func send(
_ part: GRPCClientRequestPart<Echo_EchoRequest>,
promise: EventLoopPromise<Void>?,
context: ClientInterceptorContext<Echo_EchoRequest, Echo_EchoResponse>
) {
switch part {
case .message(var request, let metadata):
request.text = String(request.text.reversed())
context.send(.message(request, metadata), promise: promise)
default:
context.send(part, promise: promise)
}
}
override func receive(
_ part: GRPCClientResponsePart<Echo_EchoResponse>,
context: ClientInterceptorContext<Echo_EchoRequest, Echo_EchoResponse>
) {
switch part {
case var .message(response):
response.text = String(response.text.reversed())
context.receive(.message(response))
default:
context.receive(part)
}
}
}
private class ReversingInterceptors: Echo_EchoClientInterceptorFactoryProtocol {
// This interceptor is stateless, let's just share it.
private let interceptors = [EchoReverseInterceptor()]
func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return self.interceptors
}
func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return self.interceptors
}
func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return self.interceptors
}
func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return self.interceptors
}
}
private enum MagicKey: UserInfo.Key {
typealias Value = String
}
extension UserInfo {
fileprivate var magic: MagicKey.Value? {
get {
return self[MagicKey.self]
}
set {
self[MagicKey.self] = newValue
}
}
}
| 31.753351 | 99 | 0.689294 |
ed34c5ff3bac6b5aee710cb973ec324b01201c88 | 617 | //
// AppDelegate.swift
// Dominos11_Starter
//
// Created by Lee on 2020/05/26.
// Copyright © 2020 Kira. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .systemBackground
window?.rootViewController = MainTabBarController()
window?.makeKeyAndVisible()
return true
}
}
| 22.851852 | 143 | 0.730956 |
6a56825a448db58cd72f6bd02fafcc4a7434422a | 2,443 | //
// LPMainViewController.swift
// Example
//
// Created by lipeng on 2017/11/17.
// Copyright © 2017年 lipeng. All rights reserved.
//
import UIKit
class LPMainViewController: UITableViewController {
deinit {
#if DEBUG
print("LPMainViewController -> relese memory.")
#endif
}
var models: [LPModel] = []
override func viewDidLoad() {
super.viewDidLoad()
models += LPModel.list
}
override func numberOfSections(in tableView: UITableView) -> Int {
return models.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models[section].data.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return models[section].title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LPMainCell", for: indexPath)
let data = models[indexPath.section].data[indexPath.row]
cell.textLabel?.text = data.title
cell.textLabel?.textColor = data.ok ? #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1) : #colorLiteral(red: 1, green: 0.1490196078, blue: 0, alpha: 1)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
func push(_ vc: UIViewController) {
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
}
let data = models[indexPath.section].data[indexPath.row]
switch data.id {
case .indicator: push(LPIndicatorViewController(data: data))
case .bar: push(LPPageBarViewController(data: data))
case .cover: push(LPCoverViewController(data: data))
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
}
| 33.465753 | 166 | 0.652476 |
e646d811391104e86806d1944396c75ce7ef353f | 653 | //
// Copyright © 2021 Dropbox, Inc. All rights reserved.
//
import Foundation
import Utilities
public struct BuckMoveInput: Codable, ReflectedStringConvertible, Equatable {
public struct Path: Codable, Equatable, ReflectedStringConvertible {
public let source: String
public let destination: String
public init(source: String, destination: String) {
self.source = source
self.destination = destination
}
}
public let paths: [Path]
public let ignoreFolders: [String]?
public init(
paths: [Path],
ignoreFolders: [String]? = nil
) {
self.paths = paths
self.ignoreFolders = ignoreFolders
}
}
| 21.766667 | 77 | 0.696784 |
bfaf0d784aeda34fac347ca820b1f09a3b2a48e0 | 7,619 | //
// KissParametersViewController.swift
// Mobilinkd TNC Config
//
// Created by Rob Riggs on 12/29/18.
// Copyright © 2018 Mobilinkd LLC. All rights reserved.
//
import UIKit
class KissParametersViewController: UIViewController {
@IBOutlet weak var txDelayTextField: UITextField!
@IBOutlet weak var txDelayStepper: UIStepper!
@IBOutlet weak var persistenceTextField: UITextField!
@IBOutlet weak var persistenceStepper: UIStepper!
@IBOutlet weak var timeSlotTextField: UITextField!
@IBOutlet weak var timeSlotStepper: UIStepper!
@IBOutlet weak var duplexSwitch: UISwitch!
@IBAction func txDelayEdited(_ sender: UITextField) {
let value = UInt8(sender.text!)
if value != nil {
txDelay = value!
self.txDelayStepper.value = Double(value!)
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetTxDelay(value: value!))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
} else {
sender.text = self.txDelayStepper.value.description
}
}
@IBAction func txDelayChanged(_ sender: UIStepper) {
self.txDelayTextField.text = Int(sender.value).description
}
@IBAction func txDelayChangeComplete(_ sender: UIStepper) {
txDelay = UInt8(sender.value)
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetTxDelay(value: UInt8(sender.value)))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
}
@IBAction func persistenceEdited(_ sender: UITextField) {
let value = UInt8(sender.text!)
if value != nil {
persistence = value!
self.persistenceStepper.value = Double(value!)
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetPersistence(value: value!))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
} else {
sender.text = self.persistenceStepper.value.description
}
}
@IBAction func persistenceChanged(_ sender: UIStepper) {
self.persistenceTextField.text = Int(sender.value).description
}
@IBAction func persistenceChangeComplete(_ sender: UIStepper) {
persistence = UInt8(sender.value)
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetPersistence(value: UInt8(sender.value)))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
}
@IBAction func timeSlotEdited(_ sender: UITextField) {
let value = UInt8(sender.text!)
if value != nil {
timeSlot = value!
self.timeSlotStepper.value = Double(value!)
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetTxDelay(value: value!))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
} else {
sender.text = self.timeSlotStepper.value.description
}
}
@IBAction func timeSlotChanged(_ sender: UIStepper) {
self.timeSlotTextField.text = Int(sender.value).description
}
@IBAction func timeSlotChangeComplete(_ sender: UIStepper) {
timeSlot = UInt8(sender.value)
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetSlotTime(value: UInt8(sender.value)))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
}
@IBAction func duplexChanged(_ sender: UISwitch) {
duplex = sender.isOn
NotificationCenter.default.post(
name: BLECentralViewController.bleDataSendNotification,
object: KissPacketEncoder.SetDuplex(value: sender.isOn))
NotificationCenter.default.post(
name: TncConfigMenuViewController.tncModifiedNotification,
object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
if txDelay != nil {
txDelayTextField.text = txDelay!.description
txDelayStepper.value = Double(txDelay!)
}
if persistence != nil {
persistenceTextField.text = persistence!.description
persistenceStepper.value = Double(persistence!)
}
if timeSlot != nil {
timeSlotTextField.text = timeSlot!.description
timeSlotStepper.value = Double(timeSlot!)
}
if duplex != nil {
duplexSwitch.isOn = duplex!
}
txDelayTextField.clearsOnBeginEditing = true
persistenceTextField.clearsOnBeginEditing = true
timeSlotTextField.clearsOnBeginEditing = true
}
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(
self,
selector: #selector(self.didLoseConnection),
name: BLECentralViewController.bleDisconnectNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.willResignActive),
name: UIApplication.willResignActiveNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.didBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(
self,
name: UIApplication.willResignActiveNotification,
object: nil)
NotificationCenter.default.removeObserver(
self,
name: UIApplication.didBecomeActiveNotification,
object: nil)
NotificationCenter.default.removeObserver(
self,
name: BLECentralViewController.bleDisconnectNotification,
object: nil)
}
@objc func willResignActive(notification: NSNotification)
{
print("KissParametersViewController.willResignActive")
disconnectBle()
}
@objc func didBecomeActive(notification: NSNotification)
{
if blePeripheral == nil {
self.navigationController?.popToRootViewController(animated: false)
}
}
@objc func didLoseConnection(notification: NSNotification)
{
let alert = UIAlertController(
title: "LostBLETitle".localized,
message: "LostBLEMessage".localized,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.navigationController?.popToRootViewController(animated: false)
}))
self.present(alert, animated: true)
}
}
| 36.629808 | 88 | 0.641948 |
dbcfe29c67b9603475b6c7efde5f7dccad8eb991 | 13,311 | //
// REST.swift
// D&D Tavern Aid
//
// Created by Rafael on 11/05/19.
// Copyright © 2019 Rafael Plinio. All rights reserved.
//
import Foundation
enum ApiError {
case url
case taskError(error: Error)
case noResponse
case noData
case responseStatusCode(code: Int)
case invalidJSON
}
enum RESTOperation {
case save
case update
case delete
}
class REST {
private static let configuration: URLSessionConfiguration = {
let config = URLSessionConfiguration.default
config.allowsCellularAccess = false
config.httpAdditionalHeaders = ["Content-Type": "application/json"]
config.timeoutIntervalForRequest = 30.0
config.httpMaximumConnectionsPerHost = 5
return config
}()
private static let session = URLSession(configuration: configuration) //URLSession.shared
class func loadRumorData(url: String, onComplete: @escaping ([Rumor]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Rumor].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//-------
class func loadBartenderData(url: String, onComplete: @escaping ([Bartender]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Bartender].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//-------
class func loadNameData(url: String, onComplete: @escaping ([Name]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Name].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//-------
class func loadRaceData(url: String, onComplete: @escaping ([Race]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Race].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//------
class func loadDrinkData(url: String, onComplete: @escaping ([Drink]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Drink].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//===========
class func loadTavernNameData(url: String, onComplete: @escaping ([TavernName]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([TavernName].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//=============
class func loadClienteleData(url: String, onComplete: @escaping ([Clientele]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Clientele].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//=========
class func loadAccommodationData(url: String, onComplete: @escaping ([Accommodations]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Accommodations].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
//==========
class func loadGenderData(url: String, onComplete: @escaping ([Gender]) -> Void, onError: @escaping (ApiError) -> Void) {
guard let url = URL(string: url) else {
onError(.url)
return
}
let dataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
guard let response = response as? HTTPURLResponse else {
onError(.noResponse)
return
}
if response.statusCode == 200 {
guard let data = data else {return}
do {
let result = try JSONDecoder().decode([Gender].self, from: data)
onComplete(result)
} catch {
print(error.localizedDescription)
onError(.invalidJSON)
}
} else {
print("Algum status invalido pelo servidor!!")
onError(.responseStatusCode(code: response.statusCode))
}
} else {
print(error!)
onError(.taskError(error: error!))
}
}
dataTask.resume()
}
}
| 34.754569 | 140 | 0.445045 |
56db6a226717657ec3f3384380d629bc3c3cd75f | 2,307 | // Copyright (c) 2016 NoodleNation <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct LocalizedStrings {
public static let byte = "%d byte"
public static let file = "%d file"
public static let item = "%d item"
public static let match = "%d match"
public static let all = "all".capitalizedLocalizedString
public static let apply = "apply".capitalizedLocalizedString
public static let cancel = "cancel".capitalizedLocalizedString
public static let compress = "compress".capitalizedLocalizedString
public static let copy = "copy".capitalizedLocalizedString
public static let delete = "delete".capitalizedLocalizedString
public static let done = "done".capitalizedLocalizedString
public static let edit = "edit".capitalizedLocalizedString
public static let move = "move".capitalizedLocalizedString
public static let moveToTrash = "move to trash".capitalizedLocalizedString
public static let openWith = "open with".capitalizedLocalizedString
public static let rename = "rename".capitalizedLocalizedString
public static let renamePrompt = "rename prompt".properLocalizedString
}
| 53.651163 | 80 | 0.73342 |
8994c214a6d29a8bc79a7c3796b67426d22c1ada | 2,925 | //
// Profile.swift
// Ride Report
//
// Created by William Henderson on 4/30/15.
// Copyright (c) 2015 Knock Softwae, Inc. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
import HealthKit
import CocoaLumberjack
public class Profile: NSManagedObject {
public var weightKilograms: Double? {
get {
willAccessValue(forKey: "weightKilograms")
defer { didAccessValue(forKey: "weightKilograms") }
return (self.primitiveValue(forKey: "weightKilograms") as? NSNumber)?.doubleValue
}
set {
willChangeValue(forKey: "weightKilograms")
defer { didChangeValue(forKey: "weightKilograms") }
self.setPrimitiveValue(newValue.map({NSNumber(value: $0)}), forKey: "weightKilograms")
}
}
public var gender: HKBiologicalSex {
get {
willAccessValue(forKey: "gender")
defer { didAccessValue(forKey: "gender") }
guard let genderRawValue = self.primitiveValue(forKey: "gender") as? Int else {
return HKBiologicalSex.notSet
}
return HKBiologicalSex(rawValue: genderRawValue) ?? HKBiologicalSex.notSet
}
set {
willChangeValue(forKey: "gender")
defer { didChangeValue(forKey: "gender") }
self.setPrimitiveValue(newValue.rawValue, forKey: "gender")
}
}
struct Static {
static var onceToken : Int = 0
static var profile : Profile!
}
class func resetPagitionState() {
if let _ = Static.profile {
CoreDataManager.shared.saveContext()
}
}
class func resetProfile() {
Static.profile = nil
}
private var featureFlagObservation: NSKeyValueObservation?
class func profile() -> Profile {
if (Static.profile == nil) {
let context = CoreDataManager.shared.currentManagedObjectContext()
let fetchedRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Profile")
fetchedRequest.fetchLimit = 1
let results: [AnyObject]?
do {
results = try context.fetch(fetchedRequest)
} catch let error {
DDLogWarn(String(format: "Error finding profile: %@", error as NSError))
results = nil
}
if let results = results, let profileResult = results.first as? Profile {
Static.profile = profileResult
} else {
let context = CoreDataManager.shared.currentManagedObjectContext()
Static.profile = Profile(entity: NSEntityDescription.entity(forEntityName: "Profile", in: context)!, insertInto:context)
CoreDataManager.shared.saveContext()
}
}
return Static.profile
}
}
| 32.142857 | 136 | 0.592821 |
14069df92dae106125ae5ff93b58c084bac425d7 | 3,165 | //
// PageViewController.swift
// LandmarksSwiftUI
//
// Created by Steve Wall on 6/6/21.
//
import SwiftUI
import UIKit
struct PageViewController<Page: View>: UIViewControllerRepresentable {
var pages: [Page]
@Binding var currentPage: Int
/*
SwiftUI calls this makeCoordinator() method before makeUIViewController(context:),
so that you have access to the coordinator object when configuring your view controller.
Tip:
You can use this coordinator to implement common Cocoa patterns, such as delegates,
data sources, and responding to user events via target-action.
*/
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIPageViewController {
let pageViewController = UIPageViewController(
transitionStyle: .scroll,
navigationOrientation: .horizontal
)
pageViewController.dataSource = context.coordinator
pageViewController.delegate = context.coordinator
return pageViewController
}
func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
pageViewController.setViewControllers(
[context.coordinator.controllers[currentPage]], direction: .forward, animated: true
)
}
//MARK: - Coordinator to handle UIViewRepresentable
class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var parent: PageViewController
var controllers = [UIViewController]()
init(_ pageViewController: PageViewController) {
parent = pageViewController
controllers = parent.pages.map { UIHostingController(rootView: $0) }
}
// MARK: - Data Source
// These Data source methods allow the pages to loop infinitely
/// Returns the previous Page Controller from the current.
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController?
{
guard let index = controllers.firstIndex(of: viewController) else {
return nil
}
if index == 0 {
return controllers.last
}
return controllers[index - 1]
}
/// Returns the next Page Controller from the current.
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController?
{
guard let index = controllers.firstIndex(of: viewController) else {
return nil
}
if index + 1 == controllers.count {
return controllers.first
}
return controllers[index + 1]
}
// MARK: - Delegate
// Persisting the current page index
func pageViewController(
_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
if completed,
let visibleViewController = pageViewController.viewControllers?.first,
let index = controllers.firstIndex(of: visibleViewController) {
parent.currentPage = index
}
}
}
}
| 32.628866 | 93 | 0.709637 |
1ea26ede84d6dae15c0c3c6abf1273838b19f2e3 | 3,431 | //
// TarballReader.swift
// https://github.com/kolyvan/tarballkit
//
// Created by Konstantin Bukreev on 24.01.17.
//
/*
Copyright (c) 2017 Konstantin Bukreev All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
public struct TarballReader {
public let filePath: String
public init(filePath: String) {
precondition(!filePath.isEmpty)
self.filePath = filePath
}
public func items() throws -> [TarballItem] {
let raw = try RawArchive.openRead(filePath)
return try raw.items().map{ item in
return TarballItem(item, filter: raw.filter)
}
}
public func item(path: String) throws -> TarballItem? {
let raw = try RawArchive.openRead(filePath)
guard let item = raw.item(withPath: path) else { return nil}
return TarballItem(item, filter: raw.filter)
}
public func read(path: String) throws -> Data {
let raw = try RawArchive.openRead(filePath)
return try raw.readData(path)
}
public func read(item: TarballItem) throws -> Data {
if item.compressed {
return try read(path: item.path)
} else {
return try read(range: item.range)
}
}
private func read(range: Range<Int64>) throws -> Data {
precondition(range.lowerBound >= 0)
let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: filePath))
defer { handle.closeFile() }
handle.seek(toFileOffset: UInt64(range.lowerBound))
return handle.readData(ofLength: Int(range.upperBound - range.lowerBound))
}
}
public final class TarballReaderIterator: IteratorProtocol {
private var raw: RawArchive?
init(_ raw: RawArchive?) {
self.raw = raw
}
public func next() -> TarballEntry? {
guard let raw = raw else { return nil }
if let entry = try? raw.readNext() {
return TarballEntry(entry)
}
self.raw = nil
return nil
}
}
extension TarballReader: Sequence {
public func makeIterator() -> TarballReaderIterator {
let raw = try? RawArchive.openRead(filePath)
return TarballReaderIterator(raw)
}
}
| 32.67619 | 83 | 0.693675 |
5d817110740df8b067c7ffd1cc18e3dddfb036b4 | 1,606 | //
// PreferencesWindow.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 7/19/17.
// Copyright © 2017 Ian Ynda-Hummel. All rights reserved.
//
import AppKit
class PreferencesWindowController: NSWindowController {
override func awakeFromNib() {
super.awakeFromNib()
window?.title = ""
guard let firstItem = window?.toolbar?.items.first else {
return
}
window?.toolbar?.selectedItemIdentifier = firstItem.itemIdentifier
selectPane(firstItem)
}
@IBAction func selectPane(_ sender: NSToolbarItem) {
switch sender.itemIdentifier.rawValue {
case "general":
contentViewController = GeneralPreferencesViewController()
case "shortcuts":
contentViewController = ShortcutsPreferencesViewController()
case "floating":
contentViewController = FloatingPreferencesViewController()
case "debug":
contentViewController = DebugPreferencesViewController()
default:
break
}
}
}
final class PreferencesWindow: NSWindow {
@IBOutlet var closeMenuItem: NSMenuItem?
override func keyDown(with event: NSEvent) {
super.keyDown(with: event)
guard let closeMenuItem = closeMenuItem else {
return
}
let eventModifierMask = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
guard closeMenuItem.keyEquivalentModifierMask == eventModifierMask && closeMenuItem.keyEquivalent == event.characters else {
return
}
close()
}
}
| 26.766667 | 132 | 0.653798 |
6abcaed80c727cde9a51e3586b1fee0980e493f2 | 3,787 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test, objc_interop
import Foundation
import StdlibUnittest
let StringForPrintObjectTests = TestSuite("StringForPrintObject")
// Wrap stringForPrintObject for convenience. Note that the debugger uses
// something slightly different to pretty-print (see: debugVal()).
func printObj<T>(_ x: T) -> String {
return _DebuggerSupport.stringForPrintObject(x)
}
// Check if @x has a reference type.
func hasReferenceType<T>(_ x: T) -> Bool {
return _canBeClass(T.self) == 1
}
// The debugger uses unsafeBitCast to take an arbitrary address and cast it to
// AnyObject. Mimic that operation here.
func debugVal<T>(_ x: inout T) -> String {
if !hasReferenceType(x) {
return printObj(x)
}
return withUnsafePointer(to: &x) {
return _DebuggerSupport.stringForPrintObject(Swift.unsafeBitCast($0.pointee, to: AnyObject.self))
}
}
// Check if @x uses the small-string or Cocoa representations.
func hasSmallStringOrCocoaVariant(_ x: String) -> Bool {
return x._guts._isCocoa || x._guts._isSmall
}
StringForPrintObjectTests.test("Basic") {
var a = "Hello World" as NSString
let a_printed = printObj(a)
let a_debug = debugVal(&a)
expectEqual("Hello World", String(reflecting: a))
expectEqual("Hello World\n", a_printed)
expectEqual(a_printed, a_debug)
}
StringForPrintObjectTests.test("NSStringFromStringLiteral") {
var a = Foundation.NSString(stringLiteral: "Hello World")
let a_printed = printObj(a)
let a_debug = debugVal(&a)
expectEqual("Hello World", String(reflecting: a))
expectEqual("Hello World\n", a_printed)
expectEqual(a_printed, a_debug)
}
StringForPrintObjectTests.test("NSStringFromUnsafeBuffer") {
let buf = UnsafeMutablePointer<Int8>.allocate(capacity: 8)
buf[0] = 65
buf[1] = 0
var a = Foundation.NSString(utf8String: buf)!
let a_printed = printObj(a)
let a_debug = debugVal(&a)
expectEqual("A", String(reflecting: a))
expectEqual("A\n", a_printed)
expectEqual(a_printed, a_debug)
buf.deallocate()
}
StringForPrintObjectTests.test("NSStringUTF8") {
let nsUTF16 = NSString(utf8String: "🏂☃❅❆❄︎⛄️❄️")!
expectTrue(CFStringGetCharactersPtr(unsafeBitCast(nsUTF16, to: CFString.self)) != nil)
var newNSUTF16 = nsUTF16 as String
expectTrue(hasSmallStringOrCocoaVariant(newNSUTF16))
let printed = printObj(newNSUTF16)
let debug = debugVal(&newNSUTF16)
expectEqual("🏂☃❅❆❄︎⛄️❄️", String(reflecting: nsUTF16))
expectEqual("\"🏂☃❅❆❄︎⛄️❄️\"", String(reflecting: newNSUTF16))
expectEqual("\"🏂☃❅❆❄︎⛄️❄️\"\n", printed)
expectEqual(printed, debug)
}
StringForPrintObjectTests.test("ArrayOfStrings") {
var a = ["Hello World" as NSString]
let a_printed = printObj(a)
let a_debug = debugVal(&a)
expectEqual("[Hello World]", String(reflecting: a))
expectEqual("▿ 1 element\n - 0 : Hello World\n", a_printed)
expectEqual(a_printed, a_debug)
}
struct StructWithOneMember {
var a = "Hello World" as NSString
}
StringForPrintObjectTests.test("StructWithOneMember") {
var a = StructWithOneMember()
let a_printed = printObj(StructWithOneMember())
let a_debug = debugVal(&a)
expectEqual("main.StructWithOneMember(a: Hello World)", String(reflecting: a))
expectEqual("▿ StructWithOneMember\n - a : Hello World\n", a_printed)
expectEqual(a_printed, a_debug)
}
struct StructWithTwoMembers {
var a = 1
var b = "Hello World" as NSString
}
StringForPrintObjectTests.test("StructWithTwoMembers") {
var a = StructWithTwoMembers()
let a_printed = printObj(StructWithTwoMembers())
let a_debug = debugVal(&a)
expectEqual("main.StructWithTwoMembers(a: 1, b: Hello World)", String(reflecting: a))
expectEqual("▿ StructWithTwoMembers\n - a : 1\n - b : Hello World\n", a_printed)
expectEqual(a_printed, a_debug)
}
runAllTests()
| 32.367521 | 101 | 0.728809 |
4a6988a635052998cc1052662bbf629ec241fc73 | 216 | //
// Product.swift
// Examples
//
// Created by Vladislav Fitc on 04/11/2021.
//
import Foundation
struct Product: Codable {
let name: String
let description: String
let brand: String?
let image: URL
}
| 13.5 | 44 | 0.675926 |
0e22298fd61ba829057c3e8b8954ff33f13f1484 | 2,268 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
An extension on the Recipe struct to load recipe definitions from a plist file in the application bundle.
*/
import Foundation
extension Recipe {
/// Loads the recipes specified in the `Cookbook.plist` file.
static func loadRecipes() -> [Recipe] {
let bundle = NSBundle.mainBundle()
guard let cookbookURL = bundle.URLForResource("Cookbook", withExtension: "plist") else { fatalError("Unable to determine URL for cookbook plist.") }
guard let fileContents = NSArray(contentsOfURL: cookbookURL) as? [[String: String]] else { fatalError("Unable to load cookbook plist.") }
let recipies: [Recipe] = fileContents.flatMap { recipeData in
// Fetch the recipe information.
guard let title = recipeData["Title"],
descriptionFileName = recipeData["Document"],
identifierString = recipeData["Identifier"] else {
assertionFailure("Unable to fetch recipe information.")
return nil
}
// Convert the identifier string to an `Identifier` type.
guard let identifier = CookbookStoryboardIdentifier(rawValue: identifierString) else {
assertionFailure("Invalid recipe identifier: \(identifierString).")
return nil
}
// Read the recipe description from the associated file.
var description: String
do {
guard let descriptionURL = bundle.URLForResource(descriptionFileName, withExtension: nil) else {
fatalError("Unable to determine recipe description URL from fileName: \(descriptionFileName).")
}
try description = NSString(contentsOfURL: descriptionURL, encoding: NSUTF8StringEncoding) as String
}
catch {
fatalError("Unable to read recipe description from file")
}
return Recipe(title: title, identifier: identifier, description: description)
}
return recipies
}
} | 43.615385 | 156 | 0.611552 |
ccb1412613d4bc7e7a2fc4c3b1b257e056966bca | 646 | //
// JSON.swift
// SuperLachaiseRealmLoader
//
// Created by Maxime Le Moine on 21/05/2017.
//
//
import Foundation
import SwiftyJSON
extension JSON {
init(fileURL: URL) throws {
var error: NSError?
self.init(data: try Data(contentsOf: fileURL), error: &error)
if let error = error {
throw error
}
}
func assertType(type: Type) throws {
guard self.type == type else {
assertionFailure()
throw JSONError.invalidType(json: self, expected: type)
}
}
}
enum JSONError: Error {
case invalidType(json: JSON, expected: Type)
}
| 19 | 69 | 0.586687 |
7549b0531fad7e4849ede4db926c06f7c4bc0f6b | 1,349 | // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Created by Sam Deane on 08/03/22.
// All code (c) 2022 - present day, Elegant Chaos Limited.
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import Foundation
public enum ComparisonOperator: String, CaseIterable {
case equals = "=="
case notEquals = "!="
case greaterThan = ">"
case greaterThanOrEqual = ">="
case lessThan = "<"
case lessThanOrEqual = "<="
var keyword: String {
switch self {
case .equals:
return "=="
case .notEquals:
return "!="
case .greaterThan:
return ">"
case .greaterThanOrEqual:
return ">="
case .lessThan:
return "<"
case .lessThanOrEqual:
return "<="
}
}
init(flags: UInt8) {
self = Self.allCases[Int(flags >> 5)]
}
init?(keyword: String) {
for c in Self.allCases {
if c.keyword == keyword {
self = c
return
}
}
return nil
}
var flags: UInt8 {
guard let index = Self.allCases.firstIndex(of: self) else { return 0 }
return UInt8(index) << 5
}
}
| 25.45283 | 78 | 0.418829 |
18573ae79bafd347fe4ccc655f94869a84a2a73c | 1,482 | //
// StringExtensionTests.swift
// FoundationExtensionsTests
//
// Created by 张鹏 on 2019/8/12.
// Copyright © 2019 [email protected] All rights reserved.
//
import XCTest
class StringExtensionTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testRandom() {
let randomString = String.random(length: 32)
XCTAssertEqual(randomString.count, 32)
print(randomString)
let randomString2 = String.random(length: 16)
XCTAssertEqual(randomString2.count, 16)
print(randomString2)
let randomString3 = String.random(length: 128)
XCTAssertEqual(randomString3.count, 128)
print(randomString3)
}
func testRandomWithinLetter() {
let randomString = String.random(length: 32, isLetter: true)
XCTAssertEqual(randomString.count, 32)
print(randomString)
let randomString2 = String.random(length: 16, isLetter: true)
XCTAssertEqual(randomString2.count, 16)
print(randomString2)
let randomString3 = String.random(length: 128, isLetter: true)
XCTAssertEqual(randomString3.count, 128)
print(randomString3)
}
}
| 29.058824 | 111 | 0.652497 |
cccdaa342893686c79ca8be1fbebb0c69aca1913 | 8,246 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import Network
/// Network connection details.
public struct NetworkConnectionInfo: Equatable {
/// Tells if network is reachable.
public enum Reachability: String, Codable, CaseIterable {
/// The network is reachable.
case yes
/// The network might be reachable after trying.
case maybe
/// The network is not reachable.
case no
}
/// Network connection interfaces.
public enum Interface: String, Codable, CaseIterable {
case wifi
case wiredEthernet
case cellular
case loopback
case other
}
/// Network reachability status.
public let reachability: Reachability
/// Available network interfaces.
public let availableInterfaces: [Interface]?
/// A Boolean indicating whether the connection supports IPv4 traffic.
public let supportsIPv4: Bool?
/// A Boolean indicating whether the connection supports IPv6 traffic.
public let supportsIPv6: Bool?
/// A Boolean indicating if the connection uses an interface that is considered expensive, such as Cellular or a Personal Hotspot.
public let isExpensive: Bool?
/// A Boolean indicating if the connection uses an interface in Low Data Mode.
public let isConstrained: Bool?
}
/// An observer for `NetworkConnectionInfo` value.
internal typealias NetworkConnectionInfoObserver = ValueObserver
/// Provides the current `NetworkConnectionInfo`.
internal protocol NetworkConnectionInfoProviderType {
/// Current `NetworkConnectionInfo`. It might return `nil` for the first attempt(s),
/// shortly after provider's initialization, until underlying monitor does not warm up.
var current: NetworkConnectionInfo? { get }
/// Subscribes for `NetworkConnectionInfo` updates.
func subscribe<Observer: NetworkConnectionInfoObserver>(_ subscriber: Observer) where Observer.ObservedValue == NetworkConnectionInfo?
}
/// An interface for the iOS-version specific network info provider.
internal protocol WrappedNetworkConnectionInfoProvider {
var current: NetworkConnectionInfo? { get }
}
internal class NetworkConnectionInfoProvider: NetworkConnectionInfoProviderType {
/// The `NetworkConnectionInfo` provider for the current iOS version.
private let wrappedProvider: WrappedNetworkConnectionInfoProvider
/// Publisher for notifying observers on `NetworkConnectionInfo` change.
private let publisher: ValuePublisher<NetworkConnectionInfo?>
convenience init() {
if #available(iOS 12, *) {
self.init(wrappedProvider: NWPathNetworkConnectionInfoProvider())
} else {
self.init(wrappedProvider: iOS11NetworkConnectionInfoProvider())
}
}
init(wrappedProvider: WrappedNetworkConnectionInfoProvider) {
self.wrappedProvider = wrappedProvider
self.publisher = ValuePublisher(initialValue: nil)
}
var current: NetworkConnectionInfo? {
let nextValue = wrappedProvider.current
// `NetworkConnectionInfo` subscribers are notified as a side-effect of retrieving the
// current `NetworkConnectionInfo` value.
publisher.publishAsync(nextValue)
return nextValue
}
// MARK: - Managing Subscribers
func subscribe<Observer: NetworkConnectionInfoObserver>(_ subscriber: Observer) where Observer.ObservedValue == NetworkConnectionInfo? {
publisher.subscribe(subscriber)
}
}
// MARK: - iOS 12+
/// Thread-safe wrapper for `NWPathMonitor`.
///
/// The `NWPathMonitor` provides two models of getting the `NWPath` info:
/// * pulling the value with `monitor.currentPath`,
/// * pushing the value with `monitor.pathUpdateHandler = { path in ... }`.
///
/// We found the pulling model to not be thread-safe: accessing `currentPath` properties lead to occasional crashes.
/// The `ThreadSafeNWPathMonitor` listens to path updates and synchonizes the values on `.current` property.
/// This adds the necessary thread-safety and keeps the convenience of pulling.
@available(iOS 12, *)
internal class NWPathNetworkConnectionInfoProvider: WrappedNetworkConnectionInfoProvider {
/// Queue synchronizing the reads and updates to `NWPath`.
private let queue = DispatchQueue(
label: "com.datadoghq.thread-safe-nw-path-monitor",
target: .global(qos: .utility)
)
private let monitor: NWPathMonitor
init(monitor: NWPathMonitor = NWPathMonitor()) {
self.monitor = monitor
monitor.pathUpdateHandler = { [weak self] path in
self?.unsafeCurrentNetworkConnectionInfo = NetworkConnectionInfo(
reachability: NetworkConnectionInfo.Reachability(from: path.status),
availableInterfaces: Array(fromInterfaceTypes: path.availableInterfaces.map { $0.type }),
supportsIPv4: path.supportsIPv4,
supportsIPv6: path.supportsIPv6,
isExpensive: path.isExpensive,
isConstrained: {
if #available(iOS 13.0, *) {
return path.isConstrained
} else {
return nil
}
}()
)
}
monitor.start(queue: queue)
}
deinit {
monitor.cancel()
}
/// Unsynchronized `NetworkConnectionInfo`. Use `self.current` setter & getter.
private var unsafeCurrentNetworkConnectionInfo: NetworkConnectionInfo?
var current: NetworkConnectionInfo? {
get { queue.sync { unsafeCurrentNetworkConnectionInfo } }
set { queue.async { self.unsafeCurrentNetworkConnectionInfo = newValue } }
}
}
// MARK: - iOS 11
import SystemConfiguration
internal class iOS11NetworkConnectionInfoProvider: WrappedNetworkConnectionInfoProvider {
private let reachability: SCNetworkReachability = {
var zero = sockaddr()
zero.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zero.sa_family = sa_family_t(AF_INET)
return SCNetworkReachabilityCreateWithAddress(nil, &zero)! // swiftlint:disable:this force_unwrapping
}()
var current: NetworkConnectionInfo? {
var retrieval = SCNetworkReachabilityFlags()
let flags = (SCNetworkReachabilityGetFlags(reachability, &retrieval)) ? retrieval : nil
return NetworkConnectionInfo(
reachability: NetworkConnectionInfo.Reachability(from: flags),
availableInterfaces: Array(fromReachabilityFlags: flags),
supportsIPv4: nil,
supportsIPv6: nil,
isExpensive: nil,
isConstrained: nil
)
}
}
// MARK: Conversion helpers
extension NetworkConnectionInfo.Reachability {
@available(iOS 12, *)
init(from status: NWPath.Status) {
switch status {
case .satisfied: self = .yes
case .requiresConnection: self = .maybe
case .unsatisfied: self = .no
@unknown default: self = .maybe
}
}
init(from flags: SCNetworkReachabilityFlags?) {
switch flags?.contains(.reachable) {
case .none: self = .maybe
case .some(true): self = .yes
case .some(false): self = .no
}
}
}
extension Array where Element == NetworkConnectionInfo.Interface {
@available(iOS 12, *)
init(fromInterfaceTypes interfaceTypes: [NWInterface.InterfaceType]) {
self = interfaceTypes.map { interface in
switch interface {
case .wifi: return .wifi
case .wiredEthernet: return .wiredEthernet
case .cellular: return .cellular
case .loopback: return .loopback
case .other: return .other
@unknown default: return .other
}
}
}
@available(iOS 2.0, macCatalyst 13.0, *)
init?(fromReachabilityFlags flags: SCNetworkReachabilityFlags?) {
if let flags = flags,
flags.contains(.isWWAN) {
self = [.cellular]
} else {
return nil
}
}
}
| 37.144144 | 140 | 0.676085 |
fc0e0e042a5ed5d320c04b7c34e962a6b1a300c6 | 1,730 | //
// Helpers.swift
// PokeMaster
//
// Created by Wang Wei on 2019/08/20.
// Copyright © 2019 OneV's Den. All rights reserved.
//
import Foundation
import SwiftUI
extension Color {
init(hex: Int, alpha: Double = 1) {
let components = (
R: Double((hex >> 16) & 0xff) / 255,
G: Double((hex >> 08) & 0xff) / 255,
B: Double((hex >> 00) & 0xff) / 255
)
self.init(
.sRGB,
red: components.R,
green: components.G,
blue: components.B,
opacity: alpha
)
}
}
extension URL {
var extractedID: Int? {
Int(lastPathComponent)
}
}
extension String {
var newlineRemoved: String {
return split(separator: "\n").joined(separator: " ")
}
var isValidEmailAddress: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: self)
}
}
let appDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
let appEncoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}()
import Combine
extension Array where Element: Publisher {
var zipAll: AnyPublisher<[Element.Output], Element.Failure> {
let initial = Just([Element.Output]())
.setFailureType(to: Element.Failure.self)
.eraseToAnyPublisher()
return reduce(initial) { result, publisher in
result.zip(publisher) { $0 + [$1] }.eraseToAnyPublisher()
}
}
}
| 23.066667 | 76 | 0.583815 |
1855a807c8dd6a75f8d8bca8a9ecf4066fca2ca9 | 2,465 | //
// IssueCardTestDoubles.swift
// AptoSDK
//
// Created by Takeichi Kanzaki on 29/06/2018.
//
//
import AptoSDK
@testable import AptoUISDK
final class CardAdditionalFieldsSpy: CardAdditionalFieldsProtocol {
public private(set) var setCalled = false
func set(_: AdditionalFields) {
setCalled = true
}
public private(set) var getCalled = false
func get() -> AdditionalFields? {
getCalled = true
return nil
}
}
class IssueCardPresenterSpy: IssueCardPresenterProtocol {
let viewModel = IssueCardViewModel(state: .loading, errorAsset: nil)
var analyticsManager: AnalyticsServiceProtocol?
private(set) var viewLoadedCalled = false
func viewLoaded() {
viewLoadedCalled = true
}
private(set) var requestCardTappedCalled = false
func requestCardTapped() {
requestCardTappedCalled = true
}
private(set) var retryTappedCalled = false
func retryTapped() {
retryTappedCalled = true
}
private(set) var closeTappedCalled = false
func closeTapped() {
closeTappedCalled = true
}
private(set) var showURLCalled = false
private(set) var lastURLToShow: TappedURL?
func show(url: TappedURL) {
showURLCalled = true
lastURLToShow = url
}
}
class IssueCardInteractorSpy: IssueCardInteractorProtocol {
private(set) var issueCardCalled = false
private(set) var lastIssueCardCompletion: Result<Card, NSError>.Callback?
func issueCard(completion: @escaping Result<Card, NSError>.Callback) {
issueCardCalled = true
lastIssueCardCompletion = completion
}
}
class IssueCardInteractorFake: IssueCardInteractorSpy {
var nextIssueCardResult: Result<Card, NSError>?
override func issueCard(completion: @escaping Result<Card, NSError>.Callback) {
super.issueCard(completion: completion)
if let result = nextIssueCardResult {
completion(result)
}
}
}
class IssueCardModuleSpy: UIModuleSpy, IssueCardModuleProtocol {
private(set) var cardIssuedCalled = false
private(set) var lastCardIssued: Card?
func cardIssued(_ card: Card) {
cardIssuedCalled = true
lastCardIssued = card
}
private(set) var closeTappedCalled = false
func closeTapped() {
closeTappedCalled = true
}
private(set) var showURLCalled = false
func show(url _: TappedURL) {
showURLCalled = true
}
}
| 25.947368 | 83 | 0.686004 |
fbe1058b86f571eeeb3fe64309e3230eb351188a | 8,534 | //
// SharingEntry+CoreDataClass.swift
// SyncServer
//
// Created by Christopher G Prince on 9/4/18.
//
//
import Foundation
import CoreData
import SMCoreLib
import SyncServer_Shared
// These represent an index of all sharing groups to which the user belongs.
@objc(SharingEntry)
public class SharingEntry: NSManagedObject, CoreDataModel, AllOperations {
typealias COREDATAOBJECT = SharingEntry
public static let UUID_KEY = "sharingGroupUUID"
public class func entityName() -> String {
return "SharingEntry"
}
// This will be nil for owning users. And for sharing users where their owning user was removed.
var cloudStorageType: CloudStorageType? {
get {
if let cloudStorageTypeInternal = cloudStorageTypeInternal {
return CloudStorageType(rawValue: cloudStorageTypeInternal)
}
else {
return nil
}
}
set {
cloudStorageTypeInternal = newValue?.rawValue
}
}
var permission: Permission! {
get {
if let permissionInternal = permissionInternal {
return Permission(rawValue: permissionInternal)
}
else {
return nil
}
}
set {
if newValue == nil {
permissionInternal = nil
}
else {
permissionInternal = newValue.rawValue
}
}
}
public class func newObject() -> NSManagedObject {
let se = CoreData.sessionNamed(Constants.coreDataName).newObject(withEntityName: self.entityName()) as! SharingEntry
// Has the current user been removed from this group?
se.removedFromGroup = false
// If we are creating the object because the local user created the sharing group, sync with the server is not needed.
se.syncNeeded = false
se.masterVersion = 0
se.permission = .read
return se
}
func toSharingGroup() -> SyncServer.SharingGroup {
return SyncServer.SharingGroup(sharingGroupUUID: sharingGroupUUID!, sharingGroupName: sharingGroupName, permission: permission, syncNeeded: syncNeeded)
}
class func fetchObjectWithUUID(uuid:String) -> SharingEntry? {
let managedObject = CoreData.fetchObjectWithUUID(uuid, usingUUIDKey: UUID_KEY, fromEntityName: self.entityName(), coreDataSession: CoreData.sessionNamed(Constants.coreDataName))
return managedObject as? SharingEntry
}
class func masterVersionForUUID(_ uuid: String) -> MasterVersionInt? {
if let result = fetchObjectWithUUID(uuid: uuid) {
return result.masterVersion
}
else {
return nil
}
}
// Determine which, if any, sharing groups (a) have been deleted, or (b) have had name changes.
struct Updates {
let deletedOnServer:[SyncServer.SharingGroup]
let newSharingGroups:[SyncServer.SharingGroup]
let updatedSharingGroups:[SyncServer.SharingGroup]
}
// We're being passed the list of sharing groups in which the user is still a member. (Notably, if a sharing group has been removed from a group, it will not be in this list, so we haven't handle this specially).
class func update(serverSharingGroups: [SharingGroup], desiredEvents:EventDesired, delegate:SyncServerDelegate?) throws -> Updates? {
var deletedOnServer = [SharingGroup]()
var newSharingGroups = [SharingGroup]()
var updatedSharingGroups = [SharingGroup]()
for sharingGroup in serverSharingGroups {
if let sharingGroupUUID = sharingGroup.sharingGroupUUID {
if let found = fetchObjectWithUUID(uuid: sharingGroupUUID) {
if found.sharingGroupName != sharingGroup.sharingGroupName {
found.sharingGroupName = sharingGroup.sharingGroupName
updatedSharingGroups += [sharingGroup]
}
if found.masterVersion != sharingGroup.masterVersion {
found.masterVersion = sharingGroup.masterVersion!
// The master version on the server changed from what we know about. Need to sync with server to get updates.
found.syncNeeded = true
}
if sharingGroup.cloudStorageType == nil {
// If a sharing user's owning user gets removed, we need to reset the sharing group's cloud storage type.
if found.cloudStorageType != nil {
found.cloudStorageType = nil
EventDesired.reportEvent(.sharingGroupOwningUserRemoved(sharingGroup: SyncServer.SharingGroup.from(sharingGroup: sharingGroup)), mask: desiredEvents, delegate: delegate)
}
}
else {
// Migration to having cloudStorageType's for sharing users. We only have a cloudStorageType in a SharingEntry for sharing users (not for owning users), and then only when their owning user has not been removed.
if found.cloudStorageType == nil {
if let cloudStorageType = CloudStorageType(rawValue: sharingGroup.cloudStorageType!) {
found.cloudStorageType = cloudStorageType
}
}
}
}
else {
let sharingEntry = SharingEntry.newObject() as! SharingEntry
sharingEntry.sharingGroupUUID = sharingGroupUUID
sharingEntry.sharingGroupName = sharingGroup.sharingGroupName
sharingEntry.masterVersion = sharingGroup.masterVersion!
sharingEntry.permission = sharingGroup.permission
// sharingGroup.cloudStorageType will be nil for owning users. And for sharing users where their owning user has been removed.
if let cloudStorageTypeRaw = sharingGroup.cloudStorageType,
let cloudStorageType = CloudStorageType(rawValue: cloudStorageTypeRaw) {
sharingEntry.cloudStorageType = cloudStorageType
}
// This is a sharing group we (the client) didn't know about previously: Need to sync with the server to get files etc. for the sharing group.
sharingEntry.syncNeeded = true
newSharingGroups += [sharingGroup]
}
}
}
// Now, do the opposite and figure out which sharing groups have been removed or we've been removed from.
let localSharingGroups = SharingEntry.fetchAll().filter {!$0.removedFromGroup}
localSharingGroups.forEach { localSharingGroup in
let filtered = serverSharingGroups.filter {$0.sharingGroupUUID == localSharingGroup.sharingGroupUUID}
if filtered.count == 0 {
// We're no longer a member of this sharing group.
localSharingGroup.removedFromGroup = true
// Not going to mark localSharingGroup as `syncNeeded`. We're not a member of it now-- we'd get an error if we tried to sync with this sharing group.
let deletedSharingGroup = SharingGroup()
deletedSharingGroup.sharingGroupUUID = localSharingGroup.sharingGroupUUID
deletedSharingGroup.sharingGroupName = localSharingGroup.sharingGroupName
deletedSharingGroup.permission = localSharingGroup.permission
deletedOnServer += [deletedSharingGroup]
}
}
if deletedOnServer.count == 0 && newSharingGroups.count == 0 && updatedSharingGroups.count == 0 {
return nil
}
else {
return Updates(
deletedOnServer: SyncServer.SharingGroup.from(sharingGroups: deletedOnServer),
newSharingGroups: SyncServer.SharingGroup.from(sharingGroups: newSharingGroups),
updatedSharingGroups: SyncServer.SharingGroup.from(sharingGroups: updatedSharingGroups))
}
}
}
| 44.915789 | 235 | 0.602765 |
1c9a2970c528504ef806a95f8c7e676b6c90209a | 1,612 | //===----------------------------------------------------------------------===//
//
// This source file is part of the RediStack open source project
//
// Copyright (c) 2019 RediStack project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of RediStack project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
/// Handles incoming byte messages from Redis
/// and decodes them according to the Redis Serialization Protocol (RESP).
///
/// See `NIO.ByteToMessageDecoder`, `RESPTranslator` and [https://redis.io/topics/protocol](https://redis.io/topics/protocol)
public final class RedisByteDecoder: ByteToMessageDecoder {
/// `ByteToMessageDecoder.InboundOut`
public typealias InboundOut = RESPValue
private let parser: RESPTranslator
public init() {
self.parser = RESPTranslator()
}
/// See `ByteToMessageDecoder.decode(context:buffer:)`
public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
guard let value = try self.parser.parseBytes(from: &buffer) else { return .needMoreData }
context.fireChannelRead(wrapInboundOut(value))
return .continue
}
/// See `ByteToMessageDecoder.decodeLast(context:buffer:seenEOF)`
public func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState { return .needMoreData }
}
| 35.043478 | 125 | 0.638958 |
11bab67050ed7d38d7862c8baf6aab7a54b08a89 | 3,056 | //
// CommentAuthor.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// 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
extension Storefront {
/// The author of a comment.
open class CommentAuthorQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CommentAuthor
/// The author's email.
@discardableResult
open func email(alias: String? = nil) -> CommentAuthorQuery {
addField(field: "email", aliasSuffix: alias)
return self
}
/// The author’s name.
@discardableResult
open func name(alias: String? = nil) -> CommentAuthorQuery {
addField(field: "name", aliasSuffix: alias)
return self
}
}
/// The author of a comment.
open class CommentAuthor: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CommentAuthorQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "email":
guard let value = value as? String else {
throw SchemaViolationError(type: CommentAuthor.self, field: fieldName, value: fieldValue)
}
return value
case "name":
guard let value = value as? String else {
throw SchemaViolationError(type: CommentAuthor.self, field: fieldName, value: fieldValue)
}
return value
default:
throw SchemaViolationError(type: CommentAuthor.self, field: fieldName, value: fieldValue)
}
}
/// The author's email.
open var email: String {
return internalGetEmail()
}
func internalGetEmail(alias: String? = nil) -> String {
return field(field: "email", aliasSuffix: alias) as! String
}
/// The author’s name.
open var name: String {
return internalGetName()
}
func internalGetName(alias: String? = nil) -> String {
return field(field: "name", aliasSuffix: alias) as! String
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| 31.833333 | 94 | 0.714987 |
fb777d1cce79b4e2d1045e216355fb246dcccd5c | 13,935 | //
// LRParser.swift
// SwiParse
//
// Created by Yassir Ramdani on 08/10/2020.
// Copyright © 2020 Yassir Ramdani. All rights reserved.
//
import Foundation
import SwiLex
extension SwiParse {
/// Prints the the parser's table for debugging.
///
/// Activated by setting `verbose` to true.
func parserTableLogs(parserTable: ActionTable) {
if !verbose { return }
parserTable
.sorted { $0.key.id < $1.key.id }
.forEach { (key: State, value: [Word: Action]) in
print(key.id, terminator: " ")
value.forEach { (key: Word, value: Action) in
print("\(key)->\(value)", terminator: " ")
}
print("")
}
}
/// Prints the the parser's automaton for debugging.
///
/// Activated by setting `verbose` to true.
func parserStatesLogs(statesList: [State]) {
if !verbose { return }
statesList.forEach { print($0) }
}
/// Checks if the grammar satisfies all the **SwiParse** requirements.
func checkRules(rules: [Rule]) throws -> [Rule] {
if !rules.allSatisfy({ $0.right.count > 0 }) { throw ParseError.emptyRuleDefined }
return rules
}
/// Builds parser's table from the grammar's rules.
func buildRules() throws -> (State, ActionTable) {
let startingRules = rules.filter { $0.left == .start }
if startingRules.count > 1 { throw ParseError.multipleStartingRulesDefined }
guard let startingRule = startingRules.first else { throw ParseError.noStartingRuleDefined }
let initialState = State(id: 0, items: closure(items: [Item(rule: startingRule, index: 0, follow: Terminal.eof)]))
let statesList = computeStates(initState: initialState)
parserStatesLogs(statesList: statesList)
let parserTable = try table(from: statesList)
parserTableLogs(parserTable: parserTable)
return (initialState, parserTable)
}
/// Builds the first table.
func buildFirstTable() -> FirstTable {
var firstList = [DefinedWord: Set<Terminal>]()
// init first list for every token.
firstList[Word(.none)] = [.none]
for word in DefinedWord.all {
switch word {
case let .terminal(terminal):
firstList[word] = [terminal]
case .nonTerminal:
firstList[word] = []
}
}
// fill the first lists using rules.
var changed = true
while changed {
changed = false
for rule in rules {
let productionResult = DefinedWord(rule.left)
for word in rule.right {
if firstList[word]!.contains(.none) { break }
let before = firstList[productionResult]!
firstList[productionResult]!.formUnion(firstList[word]!.subtracting([Terminal.none]))
if before != firstList[productionResult]! {changed = true}
}
if let lastWord = rule.right.last,
firstList[lastWord]!.contains(.none) {
let before = firstList[productionResult]!
firstList[productionResult]!.formUnion([Terminal.none])
if before != firstList[productionResult]! {changed = true}
}
}
}
return firstList
}
/// Returns the first list for a given word.
func getFirst(of word: DefinedWord) -> Set<Terminal> {
firstTable[word]!
}
/// Builds a set of equivalent items from a given item.
func closure(items: Set<Item>) -> Set<Item> {
var itemsFinal = items
var changed = true
while changed {
changed = false
for item in itemsFinal {
if item.next() == Word(.none) {
let nexItem = Item(rule: item.rule, index: item.index + 1, follow: item.follow)
if itemsFinal.insert(nexItem).inserted { changed = true }
}
// [A → β•Bδ, a]
guard let next = item.next(),
case let Word.nonTerminal(B) = next else { continue }
for rule in rules {
// [B → τ, b]
if rule.left == B {
var firstOfSigmaA = Set<Terminal>()
if let sigma = item.next(1) {
firstOfSigmaA = getFirst(of: sigma)
if firstOfSigmaA.contains(.none) {
let firstOfSigma = getFirst(of: Word(item.follow))
firstOfSigmaA.formUnion(firstOfSigma)
}
} else {
firstOfSigmaA = getFirst(of: Word(item.follow))
}
for b in firstOfSigmaA {
// [B → •τ, b]
let newItem = Item(rule: rule, index: 0, follow: b)
if itemsFinal.insert(newItem).inserted { changed = true }
}
}
}
}
}
return itemsFinal
}
/// Returns all possible items from `state` when `word` is read.
func go(from state: State, using word: DefinedWord) -> Set<Item> {
var nextStateItems = Set<Item>()
for item in state.items {
if item.next() == word {
let nexItem = Item(rule: item.rule, index: item.index + 1, follow: item.follow)
nextStateItems.insert(nexItem)
}
}
return closure(items: nextStateItems)
}
/// Computs all the automaton nodes and transition from a given starting state.
func computeStates(initState: State) -> [State] {
var result = [initState]
var changed = true
var stateId = 1
while changed {
changed = false
for i in 0 ..< result.count {
let currentState = result[i]
for word in DefinedWord.all {
let items = go(from: currentState, using: word)
if items.isEmpty { continue }
let newState = State(id: stateId, items: items)
// add a goTo transition from curentState using word
if let found = result.first(where: { $0.items == items }) {
currentState.goTo[word] = found
} else {
currentState.goTo[word] = newState
}
// add the new state to the list
if !result.contains(newState) {
result.append(newState)
changed = true
stateId += 1
}
}
}
}
return result
}
/// Solves the reduce conflicts.
func solveReduceConflict(actionTable: inout ActionTable, state: State, word: DefinedWord, action: Action) throws {
// We already have a reduce action for word
if case Action.accept = action {
// always accept if possible!
actionTable[state]![word] = action
return
}
if case let Action.reduce(rule) = actionTable[state]![word]! {
// avoid reducing .none
if rule.right.contains(DefinedWord(.none)) {
actionTable[state]![word] = action
}
return
}
print(state)
throw ParseError.AmbiguousGrammar(actionTable[state]![word]!.description, action.description)
}
/// Solves the shift conflicts.
func solveShiftConflict(actionTable: inout ActionTable, state: State, word: DefinedWord, action: Action) throws {
// We already have a shift action for word
guard case let Action.reduce(reduceRule) = action else {
if case Action.accept = action {
// always accept if possible !
actionTable[state]![word] = action
return
}
print(state)
throw ParseError.AmbiguousGrammar(actionTable[state]![word]!.description, action.description)
}
// Shift / Reduce conflict
if verbose { print("Shift/Reduce conflict:", reduceRule, "shift[\(word)]", terminator:"") }
// associativity
for priority in priorities {
switch priority {
// Left associative => Reduce
case let .left(terminal):
if Word(terminal) == word {
if reduceRule.lastTerminal == word {
// replace the current action with the reduce
if verbose { print(" resolved by REDUCE") }
actionTable[state]![word] = action
return
}
}
// Right associative => Shift
case let .right(terminal):
if Word(terminal) == word {
if reduceRule.lastTerminal == word {
if verbose { print(" resolved by SHIFT") }
// keep the current action (shift)
return
}
}
}
}
// precedence
let precedence = priorities.filter { Word($0.token) == word || Word($0.token) == reduceRule.lastTerminal }.map { $0.token }
// if no precendence is defined then Shift/Reduce Conflict
guard precedence.count == 2 else { throw ParseError.shiftReduceConflict(word, action.description) }
if Word(precedence[1]) == reduceRule.lastTerminal {
// reduce has higher precedence (precedence is declared from low to high)
// replace the current action with the reduce
actionTable[state]![word] = action
if verbose { print(" resolved by REDUCE") }
return
}
if verbose { print(" resolved by SHIFT") }
// keep the current action (shift)
return
}
/// Adds an action to the parsing table.
func addTo(actionTable: inout ActionTable, state: State, word: DefinedWord, action: Action) throws {
guard let stateActionTable = actionTable[state] else {
// new action for word
actionTable[state] = [word: action]
return
}
guard stateActionTable[word] != nil else {
// new action for word
actionTable[state]![word] = action
return
}
switch stateActionTable[word]! {
case .accept:
// always accept if possible !
return
case .shift:
try solveShiftConflict(actionTable: &actionTable, state: state, word: word, action: action)
case .reduce:
try solveReduceConflict(actionTable: &actionTable, state: state, word: word, action: action)
case .goTo:
throw ParseError.AmbiguousGrammar(stateActionTable[word]!.description, action.description)
}
}
/// Turns the automaton into a parsing table.
func table(from states: [State]) throws -> ActionTable {
var actionTable = ActionTable()
for state in states {
for (key, val) in state.goTo {
if case Word.terminal = key {
try addTo(actionTable: &actionTable, state: state, word: key, action: .shift(val))
} else if case Word.nonTerminal = key {
try addTo(actionTable: &actionTable, state: state, word: key, action: .goTo(val))
}
}
for item in state.items {
if item.index == item.rule.right.count {
if item.rule.left == NonTerminal.start, item.follow == Terminal.eof {
try addTo(actionTable: &actionTable, state: state, word: .terminal(item.follow), action: .accept)
} else {
try addTo(actionTable: &actionTable, state: state, word: .terminal(item.follow), action: .reduce(item.rule))
}
}
}
}
return actionTable
}
/// Applies a reduction rule.
func apply(rule: Rule, to parsingStack: Stack<DefinedWord>, data: Stack<Any>, stateStack: Stack<State>) {
if rule.right.contains(DefinedWord(.none)) {
let dataResult = rule.action([])
data.push(item: dataResult)
let new = DefinedWord(rule.left)
parsingStack.push(item: new)
return
}
parsingStack.pop(rule.right.count)
stateStack.pop(rule.right.count)
let datainput = data.pop(rule.right.count)!
let dataResult = rule.action(datainput)
data.push(item: dataResult)
let new = DefinedWord(rule.left)
parsingStack.push(item: new)
}
/// Applies the next parsing action..
func actionExec(action: Action, tokenStack: Stack<Token<Terminal>>, parsingStack: Stack<DefinedWord>, dataStack: Stack<Any>, stateStack: Stack<State>) {
switch action {
case .accept:
tokenStack.pop()
case let .shift(state):
let currentShift = tokenStack.pop()!
parsingStack.push(item: DefinedWord(currentShift.type))
dataStack.push(item: currentShift.value)
stateStack.push(item: state)
case let .reduce(rule):
apply(rule: rule, to: parsingStack, data: dataStack, stateStack: stateStack)
if case let .goTo(newState) = parserTable[stateStack.look!]![parsingStack.look!]! {
stateStack.push(item: newState)
}
case let .goTo(state):
stateStack.push(item: state)
}
}
}
| 40.043103 | 156 | 0.534194 |
22cf78ace973cc7c119ef2e4459e5af1d3f6c336 | 3,199 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private class Reader : Record {
var id: Int64?
let name: String
let age: Int?
init(id: Int64?, name: String, age: Int?) {
self.id = id
self.name = name
self.age = age
super.init()
}
required init(_ row: Row){
self.id = row.value(named: "id")
self.name = row.value(named: "name")
self.age = row.value(named: "age")
super.init(row)
}
override static func databaseTableName() -> String {
return "readers"
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["id": id, "name": name, "age": age]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
id = rowID
}
}
class RecordQueryInterfaceRequestTests: GRDBTestCase {
override func setUpDatabase(dbWriter: DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try migrator.migrate(dbWriter)
}
// MARK: - Fetch Record
func testFetch() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let arthur = Reader(id: nil, name: "Arthur", age: 42)
try arthur.insert(db)
let barbara = Reader(id: nil, name: "Barbara", age: 36)
try barbara.insert(db)
let request = Reader.all()
do {
let readers = request.fetchAll(db)
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(readers.count, 2)
XCTAssertEqual(readers[0].id!, arthur.id!)
XCTAssertEqual(readers[0].name, arthur.name)
XCTAssertEqual(readers[0].age, arthur.age)
XCTAssertEqual(readers[1].id!, barbara.id!)
XCTAssertEqual(readers[1].name, barbara.name)
XCTAssertEqual(readers[1].age, barbara.age)
}
do {
let reader = request.fetchOne(db)!
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(reader.id!, arthur.id!)
XCTAssertEqual(reader.name, arthur.name)
XCTAssertEqual(reader.age, arthur.age)
}
do {
let names = request.fetch(db).map { $0.name }
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
}
}
}
}
| 31.673267 | 82 | 0.508596 |
5bd29adf1d31f3d94b2e5dd13f022fee61a32e17 | 994 | //
// ExtensionDelegate.swift
// app_iwatch3 WatchKit Extension
//
// Created by CICE on 27/10/16.
// Copyright © 2016 CICE. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
}
| 36.814815 | 285 | 0.735412 |
e89e56def1b76ff8513b1b106ba277bd558dfd57 | 311 | //
// AndesButtonStyle.swift
// AndesUI
//
// Created by LEANDRO FURYK on 17/12/2019.
//
import Foundation
internal protocol AndesButtonHierarchyProtocol {
var idleColor: UIColor { get }
var pressedColor: UIColor { get }
var disableColor: UIColor { get }
var fontColor: UIColor { get }
}
| 17.277778 | 48 | 0.684887 |
2f99a348a4b0011c0bb111f8fb47beb48694cab3 | 1,960 | //
// AlbumTableViewCell.swift
// JSONPhotos
//
// Created by Merle Anthony on 23/02/2022.
//
import UIKit
import RxSwift
class AlbumTableViewCell: UITableViewCell {
weak var collectionView: UICollectionView!
var viewModel: AlbumCellViewModelType? {
didSet {
if let viewModel = viewModel {
update(with: viewModel)
}
}
}
let adapter = AlbumCollectionViewDatapter()
private var disposeBag = DisposeBag()
override init(
style: UITableViewCell.CellStyle,
reuseIdentifier: String?
) {
super.init(
style: style,
reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
private func setupView() {
selectionStyle = .none
let collectionView = createCollectionView()
contentView.encapsulate(collectionView)
self.collectionView = collectionView
adapter.bind(to: collectionView)
}
private func createCollectionView() -> UICollectionView {
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: .defaultAlbumPhotosLayout(
scrollDirection: .horizontal
))
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
return collectionView
}
private func update(
with viewModel: AlbumCellViewModelType
) {
viewModel
.photos
.bind(to: adapter.photos)
.disposed(by: disposeBag)
collectionView
.rx
.modelSelected(Photo.self)
.bind(to: viewModel.photoSelected)
.disposed(by: disposeBag)
}
}
| 22.272727 | 61 | 0.605612 |
efb49fad5af43897dc131db394395f698e9b959a | 2,769 | //
// ArchiveFetcher.swift
// r2-shared-swift
//
// Created by Mickaël Menu on 11/05/2020.
//
// Copyright 2020 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
/** Provides access to entries of a ZIP archive. */
public final class ArchiveFetcher: Fetcher, Loggable {
private let archive: Archive
public init(archive: Archive) {
self.archive = archive
}
public lazy var links: [Link] =
archive.entries.map { entry in
Link(
href: entry.path.addingPrefix("/"),
type: MediaType.of(fileExtension: URL(fileURLWithPath: entry.path).pathExtension)?.string,
properties: .init([
"compressedLength": entry.compressedLength as Any
])
)
}
public func get(_ link: Link) -> Resource {
return ArchiveResource(link: link, archive: archive)
}
public func close() {}
private final class ArchiveResource: Resource {
lazy var link: Link = {
var link = originalLink
if let compressedLength = entry?.compressedLength {
link = link.addingProperties(["compressedLength": Int(compressedLength)])
}
return link
}()
var file: URL? { archive.file(at: href) }
private let originalLink: Link
private let href: String
private let archive: Archive
private lazy var entry: ArchiveEntry? = try? archive.entry(at: href)
init(link: Link, archive: Archive) {
self.originalLink = link
self.href = link.href.removingPrefix("/")
self.archive = archive
}
var length: Result<UInt64, ResourceError> {
guard let length = entry?.length else {
return .failure(.notFound)
}
return .success(length)
}
func read(range: Range<UInt64>?) -> Result<Data, ResourceError> {
guard entry != nil else {
return .failure(.notFound)
}
let data: Data? = {
if let range = range {
return archive.read(at: href, range: range)
} else {
return archive.read(at: href)
}
}()
if let data = data {
return .success(data)
} else {
return .failure(.unavailable)
}
}
func close() {}
}
}
| 29.147368 | 106 | 0.5316 |
11e9bcf71bea92597cadf45061be31c8e866680e | 5,997 | //
// HttpResponse.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
public enum SerializationError: ErrorType {
case InvalidObject
case NotSupported
}
public protocol HttpResponseBodyWriter {
func write(file: File)
func write(data: [UInt8])
func write(data: ArraySlice<UInt8>)
}
public enum HttpResponseBody {
case Json(AnyObject)
case Html(String)
case Text(String)
case Custom(Any, (Any) throws -> String)
func content() -> (Int, (HttpResponseBodyWriter throws -> Void)?) {
do {
switch self {
case .Json(let object):
#if os(Linux)
let data = [UInt8]("Not ready for Linux.".utf8)
return (data.count, {
$0.write(data)
})
#else
guard NSJSONSerialization.isValidJSONObject(object) else {
throw SerializationError.InvalidObject
}
let json = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted)
let data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
return (data.count, {
$0.write(data)
})
#endif
case .Text(let body):
let data = [UInt8](body.utf8)
return (data.count, {
$0.write(data)
})
case .Html(let body):
let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
let data = [UInt8](serialised.utf8)
return (data.count, {
$0.write(data)
})
case .Custom(let object, let closure):
let serialised = try closure(object)
let data = [UInt8](serialised.utf8)
return (data.count, {
$0.write(data)
})
}
} catch {
let data = [UInt8]("Serialisation error: \(error)".utf8)
return (data.count, {
$0.write(data)
})
}
}
}
public enum HttpResponse {
case SwitchProtocols([String: String], Socket -> Void)
case OK(HttpResponseBody), Created, Accepted
case MovedPermanently(String)
case BadRequest(HttpResponseBody?), Unauthorized, Forbidden, NotFound
case InternalServerError
case RAW(Int, String, [String:String]?, (HttpResponseBodyWriter -> Void)? )
func statusCode() -> Int {
switch self {
case .SwitchProtocols(_, _) : return 101
case .OK(_) : return 200
case .Created : return 201
case .Accepted : return 202
case .MovedPermanently : return 301
case .BadRequest(_) : return 400
case .Unauthorized : return 401
case .Forbidden : return 403
case .NotFound : return 404
case .InternalServerError : return 500
case .RAW(let code, _ , _, _) : return code
}
}
func reasonPhrase() -> String {
switch self {
case .SwitchProtocols(_, _) : return "Switching Protocols"
case .OK(_) : return "OK"
case .Created : return "Created"
case .Accepted : return "Accepted"
case .MovedPermanently : return "Moved Permanently"
case .BadRequest(_) : return "Bad Request"
case .Unauthorized : return "Unauthorized"
case .Forbidden : return "Forbidden"
case .NotFound : return "Not Found"
case .InternalServerError : return "Internal Server Error"
case .RAW(_, let phrase, _, _) : return phrase
}
}
func headers() -> [String: String] {
var headers = ["Server" : "Swifter \(HttpServer.VERSION)"]
switch self {
case .SwitchProtocols(let switchHeaders, _):
for (key, value) in switchHeaders {
headers[key] = value
}
case .OK(let body):
switch body {
case .Json(_) : headers["Content-Type"] = "application/json"
case .Html(_) : headers["Content-Type"] = "text/html"
default:break
}
case .MovedPermanently(let location):
headers["Location"] = location
case .RAW(_, _, let rawHeaders, _):
if let rawHeaders = rawHeaders {
for (k, v) in rawHeaders {
headers.updateValue(v, forKey: k)
}
}
default:break
}
return headers
}
func content() -> (length: Int, write: (HttpResponseBodyWriter throws -> Void)?) {
switch self {
case .OK(let body) : return body.content()
case .BadRequest(let body) : return body?.content() ?? (-1, nil)
case .RAW(_, _, _, let writer) : return (-1, writer)
default : return (-1, nil)
}
}
func socketSession() -> (Socket -> Void)? {
switch self {
case SwitchProtocols(_, let handler) : return handler
default: return nil
}
}
}
/**
Makes it possible to compare handler responses with '==', but
ignores any associated values. This should generally be what
you want. E.g.:
let resp = handler(updatedRequest)
if resp == .NotFound {
print("Client requested not found: \(request.url)")
}
*/
func ==(inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
return inLeft.statusCode() == inRight.statusCode()
}
| 33.881356 | 126 | 0.516592 |
8f30df7bf5026d34738a3fd1cdb1a57854672b2f | 1,373 | //
// AppDelegate.swift
// virtual-tourist
//
// Created by Fabrício Silva Carvalhal on 04/07/21.
//
import UIKit
import CoreData
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
CoreDataManager.shared.configure()
CoreDataManager.shared.load()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func applicationWillTerminate(_ application: UIApplication) {
saveViewContext()
}
func applicationDidEnterBackground(_ application: UIApplication) {
saveViewContext()
}
// MARK: - Core Data Saving support
func saveViewContext() {
let context = CoreDataManager.shared.viewContext
if context.hasChanges {
try? context.save()
}
}
}
| 29.212766 | 179 | 0.694829 |
e47ed97446cb6a0b037e10fc0adee1ad772a5477 | 1,441 | //
// DevicesViewModel.swift
// Bagel
//
// Created by Yagiz Gurgul on 1.10.2018.
// Copyright © 2018 Yagiz Lab. All rights reserved.
//
import Cocoa
class DevicesViewModel: BaseListViewModel<BagelDeviceController> {
func register() {
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshItems), name: BagelNotifications.didGetPacket, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshItems), name: BagelNotifications.didSelectProject, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshItems), name: BagelNotifications.didSelectDevice, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshItems), name: BagelNotifications.didUpdatePacket, object: nil)
}
var selectedItem: BagelDeviceController? {
return BagelController.shared.selectedProjectController?.selectedDeviceController
}
var selectedItemIndex: Int? {
if let selectedItem = self.selectedItem {
return self.items.firstIndex { $0 === selectedItem }
}
return nil
}
@objc func refreshItems() {
self.set(items: BagelController.shared.selectedProjectController?.deviceControllers ?? [])
// self.onChange?()
}
}
| 31.326087 | 148 | 0.671062 |
87fb76935857fcaf5f09671e333f33e7bb5a3971 | 299 | import Foundation
/// Response obtained via a called to `getCardProviders`
struct CardProviderResponse: Codable {
/// type of the object response: 'list'
let object: String
/// number of card providers
let count: Int
/// list of card providers
let data: [CardProvider]
}
| 19.933333 | 56 | 0.685619 |
d951e427a6c2e9785772d8c89b888c10289c1503 | 620 | //
// DetailsView.swift
// ScootersApp
//
// Created by Isabela Louli on 19.03.22.
//
import UIKit
import MapKit
final class DetailsView: UIViewController {
//MARK - Properties
@IBOutlet weak var scooterNameLabel: UILabel!
@IBOutlet weak var bateryLevelLabel: UILabel!
@IBOutlet weak var plateLabel: UILabel!
var scooter: Scooter?
//MARK - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
scooterNameLabel.text = scooter?.name
bateryLevelLabel.text = scooter?.battery
plateLabel.text = scooter?.plate
}
}
| 20 | 49 | 0.641935 |
6a5e1b9b9efeeb3d73584ab3381b436d2ea51896 | 559 | //
// ViewController.swift
// LOTAnimationView_IB_Example
//
// Created by Taylor Wright-Sanson on 2/22/19.
// Copyright © 2019 Taylor Wright-Sanson. All rights reserved.
//
import UIKit
import Lottie
class ViewController: UIViewController {
@IBOutlet weak var lottieView: LOTAnimationView!
override func viewDidLoad() {
super.viewDidLoad()
let lottieFileName = "159-servishero-loading"
lottieView.setAnimation(named: lottieFileName)
lottieView.loopAnimation = true
lottieView.play()
}
}
| 21.5 | 63 | 0.68873 |
e4eca494e4813e88c2adcf91d94c0942e2601d0d | 628 | //
// AVPlayerViewExtension.swift
// Aerial
//
// Created by Guillaume Louel on 16/10/2018.
// Copyright © 2018 John Coates. All rights reserved.
//
import Foundation
import Cocoa
import AVKit
extension AVPlayerView {
override open func scrollWheel(with event: NSEvent) {
// Disable scrolling that can cause accidental video playback control (seek)
return
}
override open func keyDown(with event: NSEvent) {
// Disable space key (do not pause video playback)
let spaceBarKeyCode = UInt16(49)
if event.keyCode == spaceBarKeyCode {
return
}
}
}
| 21.655172 | 84 | 0.657643 |
e4cb36311898c7013d4e1c1900964fd59e5f6d34 | 904 | //
// ContentView.swift
// DashboardUI
//
// Created by user208584 on 12/23/21.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
HStack{
Button(action: {}) {
Image("menu")
.renderingMode(.template)
.foregroundColor(.white)
}
Spacer()
Button(action: {}) {
Image("bell")
.renderingMode(.template)
.foregroundColor(.white)
}
}
.padding()
Spacer(minLength: 0)
}
.background(Color.accentColor.ignoresSafeArea(.all, edges: .all))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 22.6 | 73 | 0.439159 |
4846e4dd1cdc3acc2bc251feb1834d55acd19047 | 4,710 | //
// TweetCell.swift
// twitter_alamofire_demo
//
// Created by Chengjiu Hong on 9/29/18.
// Copyright © 2018 Charles Hieger. All rights reserved.
//
import UIKit
import AlamofireImage
class TweetCell: UITableViewCell {
@IBOutlet weak var heartBtn: UIButton!
@IBOutlet weak var retweetBtn: UIButton!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var screenName: UILabel!
@IBOutlet weak var tweetMessage: UILabel!
@IBOutlet weak var favoriteCount: UILabel!
@IBOutlet weak var retweetCount: UILabel!
var tweet: Tweet!{
didSet{
tweetMessage.text = tweet.text
username.text = tweet.user?.name
screenName.text = "@\(tweet.user!.screenName) - \(tweet.createdAtString!)"
if let cnt = tweet.favoriteCount{
favoriteCount.text = String(cnt)
}
else{
favoriteCount.text = String(0)
}
if let cnt = tweet.retweetCount{
retweetCount.text = String(cnt)
}
else{
retweetCount.text = String(0)
}
profileImageView.af_setImage(withURL: (tweet.user?.profileURLPath)!)
}
}
@IBAction func tapLove(_ sender: Any) {
if(!(tweet.favorited!)){
let image = UIImage(named: "favor-icon-red")
heartBtn.setImage(image, for: UIControlState.normal)
tweet.favorited = true
APIManager.shared.favorite(tweet) { (ntweet: Tweet?, error: Error?) in
if let error = error {
print("Error favoriting tweet: \(error.localizedDescription)")
} else if let ntweet = ntweet {
print("Successfully favorited the following Tweet")
let count = ntweet.favoriteCount!
self.favoriteCount.text = String(count)
}
}
}else {
let image = UIImage(named: "favor-icon")
heartBtn.setImage(image, for: UIControlState.normal)
tweet.favorited = false
APIManager.shared.unfavorite(tweet) { (ntweet: Tweet?, error: Error?) in
if let error = error {
print("Error unfavoriting tweet: \(error.localizedDescription)")
} else if let ntweet = ntweet {
print("Successfully unfavorited the following Tweet")
let count = ntweet.favoriteCount!
self.favoriteCount.text = String(count)
}
}
}
}
@IBAction func tapRetweet(_ sender: Any) {
if(!(tweet.retweeted!)){
let image = UIImage(named: "retweet-icon-green")
retweetBtn.setImage(image, for: UIControlState.normal)
tweet.retweeted = true
APIManager.shared.retweet(tweet) { (ntweet: Tweet?, error: Error?) in
if let error = error {
print("Error retweet tweet: \(error.localizedDescription)")
} else if let ntweet = ntweet {
print("Successfully retweet the following Tweet")
let count = ntweet.retweetCount!
self.retweetCount.text = String(count)
}
}
}else {
let image = UIImage(named: "retweet-icon")
retweetBtn.setImage(image, for: UIControlState.normal)
tweet.retweeted = false
APIManager.shared.unretweet(tweet) { (ntweet: Tweet?, error: Error?) in
if let error = error {
print("Error unretweet tweet: \(error.localizedDescription)")
} else if let ntweet = ntweet {
print("Successfully unretweet the following Tweet")
let count = ntweet.retweetCount!
self.retweetCount.text = String(count)
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
profileImageView.layer.cornerRadius = 3
profileImageView.clipsToBounds = true
tweetMessage.preferredMaxLayoutWidth = tweetMessage.frame.size.width
}
override func layoutSubviews() {
super.layoutSubviews()
tweetMessage.preferredMaxLayoutWidth = tweetMessage.frame.size.width
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 36.796875 | 86 | 0.558174 |
e463f759befd607c6f5fe44dc46e699dd3354153 | 268 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol g { func i(a
func a
func a<H : AnyObject
}
protocol a {
typealias b: e
typealias e
func l
| 20.615385 | 87 | 0.75 |
7ae3c387d09d52f753b51178fa9b1a765f1e9261 | 522 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import Foundation
class HandleChangesMulticast: Publisher {
static let shared = HandleChangesMulticast()
private let multicast = MulticastDelegate<Subscriber>()
func notify(_ hint: Hint) {
multicast.invoke { $0.update(hint) }
}
func subscribe(_ subscriber: Subscriber) {
multicast.add(subscriber)
}
}
| 23.727273 | 91 | 0.681992 |
21dba5df4cfb684e709b06cd407553169a226e38 | 474 | import SwiftCrossUI
class CounterState: AppState {
@Observed var count = 0
}
@main
struct CounterApp: App {
let identifier = "dev.stackotter.CounterApp"
let state = CounterState()
let windowProperties = WindowProperties(title: "CounterApp")
var body: some ViewContent {
HStack {
Button("-") { state.count -= 1 }
Text("Count: \(state.count)")
Button("+") { state.count += 1 }
}
}
}
| 20.608696 | 64 | 0.56962 |
d6ffbd6c540bf3bc714c3b3c2792ea59bfd69aac | 1,591 | //
// MargotUIScreen.swift
// Margot
//
// Created by CatHarly on 2018/11/30.
//
import Foundation
/*
640 × 1136 16:9 iPhone5s Default-568h@2x
750 × 1334 16:9 iPhone6 7 8 Default-667h@2x
1242 × 2208 16:9 iPhone8 Plus Default-736h@3x
1125 × 2436 18:9 iPhoneX, XS Default-812h@3x
828 x 1792 19.5:9 iPhoneXR Default-828h@2x
1242 x 2688 18:9 iPhoneX Max Default-1242h@3x
*/
public struct Screen {
/// Screen width
public var width: CGFloat {
return UIScreen.main.bounds.width
}
/// Screen height
public var height: CGFloat {
return UIScreen.main.bounds.height
}
/// is iphoneX
public var isIphoneX: Bool {
return UIScreen.main.bounds.height >= 812
}
/// NavigationBar height
public var iphoneXNavBarHeight: CGFloat {
return isIphoneX ? 88.0:64.0
}
/// StatusBar height
public var iphoneXStatusBarHeight: CGFloat {
return isIphoneX ? 44.0:20.0
}
/// Top safe area
public var iphoneXStatusBarMargin: CGFloat {
return isIphoneX ? 24.0:0.0
}
/// Bottom safe area
public var iphoneXBottomMargin: CGFloat {
return isIphoneX ? 34.0:0.0
}
public var scaleW: CGFloat {
return width/375.0
}
public var scaleH: CGFloat {
return height/667.0
}
public var scaleWH: CGFloat {
return width/height
}
/// Common scale
public var scale: CGFloat {
return UIScreen.main.scale
}
}
| 20.397436 | 55 | 0.585795 |
91d74231437b11dc13dbda0e4a890c2b60c11c4c | 3,355 | //
// GameScene.swift
// Forces
//
// Created by Jon Manning on 16/02/2015.
// Copyright (c) 2015 Secret Lab. All rights reserved.
//
import SpriteKit
class PhysicsScene: SKScene {
override init(size: CGSize) {
super.init(size:size)
self.backgroundColor = SKColor(red:0.15, green:0.15, blue:0.3, alpha:1.0)
// Add 50 small boxes
for i in 0...50 {
let node = SKSpriteNode(color:SKColor.whiteColor(), size:CGSize(width: 20, height: 20))
node.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
node.physicsBody = SKPhysicsBody(rectangleOfSize:node.size)
node.physicsBody?.density = 0.01
self.addChild(node)
}
// Add the walls
let walls = SKNode()
walls.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame)
self.addChild(walls)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in touches as! Set<UITouch> {
let point = touch.locationInNode(self)
// BEGIN create_explosion
// 'point' is a CGPoint in world space
self.applyExplosionAtPoint(point, radius:150, power:10)
// END create_explosion
}
}
// BEGIN apply_explosion
func applyExplosionAtPoint(point: CGPoint,
radius:CGFloat, power:CGFloat) {
// Work out which bodies are in range of the explosion
// by creating a rectangle
let explosionRect = CGRect(x: point.x - radius,
y: point.y - radius,
width: radius*2, height: radius*2)
// For each body, apply an explosion force
self.physicsWorld.enumerateBodiesInRect(explosionRect,
usingBlock:{ (body, stop) in
// Work out if the body has a node that we can use
if let bodyPosition = body.node?.position {
// Work out the direction that we should apply
// the force in for this body
// BEGIN explosion_offset
let explosionOffset =
CGVector(dx: bodyPosition.x - point.x,
dy: bodyPosition.y - point.y)
// END explosion_offset
// Work out the distance from the explosion point
// BEGIN explosion_distance
let explosionDistance =
sqrt(explosionOffset.dx * explosionOffset.dx +
explosionOffset.dy * explosionOffset.dy)
// END explosion_distance
// BEGIN create_force
// Normalize the explosion force
var explosionForce = explosionOffset
explosionForce.dx /= explosionDistance
explosionForce.dy /= explosionDistance
// Multiply by explosion power
explosionForce.dx *= power
explosionForce.dy *= power
// END create_force
// Finally, apply the force
// BEGIN apply_force
body.applyForce(explosionForce)
// END apply_force
}
})
}
// END apply_explosion
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 31.650943 | 99 | 0.566021 |
0a37795338d1dac2b7643283fae909739c685657 | 6,029 | //
// UIFontExtensions.swift
// Device
//
// Created by German on 3/28/19.
//
import UIKit
@available(iOS 8.2, *)
public extension UIFont {
convenience init(familyName: String,
weight: UIFont.Weight,
size: PointSize) {
let traits: [UIFontDescriptor.TraitKey: Any] = [.weight: weight]
let attributes: [UIFontDescriptor.AttributeName: Any] = [.family: familyName,
.size: size.value,
.traits: traits]
let descriptor = Font.bestDescriptor(matchingAttributes: attributes, weight: weight)
self.init(descriptor: descriptor, size: size.value)
}
func weight(_ weight: UIFont.Weight) -> UIFont {
var attributes = currentAttributes
if var traits = attributes[.traits] as? [UIFontDescriptor.TraitKey: Any] {
traits[.weight] = weight
attributes[.traits] = traits
}
let descriptor = Font.bestDescriptor(matchingAttributes: attributes,
weight: weight)
return UIFont(descriptor: descriptor, size: pointSize)
}
func sized(_ size: PointSize) -> UIFont {
return withSize(size.value)
}
private var currentAttributes: [UIFontDescriptor.AttributeName: Any] {
var attributes = fontDescriptor.fontAttributes
let traits = (fontDescriptor.object(forKey: .traits) ?? attributes[.traits]) as? [UIFontDescriptor.TraitKey: Any] ?? [:]
attributes[.traits] = traits
if attributes[.family] == nil { attributes[.family] = familyName }
attributes[.name] = nil
return attributes
}
// MARK: Weight Functions
var ultraLight: UIFont { return weight(.ultraLight) }
var extraLight: UIFont { return weight(.extraLight) }
var thin: UIFont { return weight(.thin) }
var book: UIFont { return weight(.book) }
var demi: UIFont { return weight(.demi) }
var normal: UIFont { return weight(.normal) }
var light: UIFont { return weight(.light) }
var regular: UIFont { return weight(.regular) }
var medium: UIFont { return weight(.medium) }
var demibold: UIFont { return weight(.demibold) }
var semibold: UIFont { return weight(.semibold) }
var bold: UIFont { return weight(.bold) }
var extraBold: UIFont { return weight(.extraBold) }
var heavy: UIFont { return weight(.heavy) }
var black: UIFont { return weight(.black) }
var extraBlack: UIFont { return weight(.extraBlack) }
var ultraBlack: UIFont { return weight(.ultraBlack) }
var fat: UIFont { return weight(.fat) }
var poster: UIFont { return weight(.poster) }
// MARK: Size Functions
var tiny: UIFont { return sized(.tiny) }
var small: UIFont { return sized(.small) }
var normalSize: UIFont { return sized(.normal) }
var mediumSize: UIFont { return sized(.medium) }
var big: UIFont { return sized(.big) }
var huge: UIFont { return sized(.huge) }
var enormous: UIFont { return sized(.enormous) }
func fixed(_ points: CGFloat) -> UIFont { return sized(.fixed(points: points)) }
func specific(values: SizeSpecification) -> UIFont { return sized(.specific(with: values)) }
func proportional(to base: BaseSize) -> UIFont { return sized(.proportional(to: base)) }
}
@available(iOS 11.0, *)
public extension UIFont {
func dinamicallySized(forStyle style: UIFont.TextStyle) -> UIFont {
let metrics = UIFontMetrics(forTextStyle: style)
return metrics.scaledFont(for: self)
}
@available(iOS 11.0, *)
func dinamicallySized(forSize pointSize: PointSize) -> UIFont {
return dinamicallySized(forStyle: pointSize.fontStyle)
}
var body: UIFont { return dinamicallySized(forStyle: .body) }
var largeTitle: UIFont { return dinamicallySized(forStyle: .largeTitle) }
var title1: UIFont { return dinamicallySized(forStyle: .title1) }
var title2: UIFont { return dinamicallySized(forStyle: .title2) }
var title3: UIFont { return dinamicallySized(forStyle: .title3) }
var headline: UIFont { return dinamicallySized(forStyle: .headline) }
var subheadline: UIFont { return dinamicallySized(forStyle: .subheadline) }
var callout: UIFont { return dinamicallySized(forStyle: .callout) }
var footnote: UIFont { return dinamicallySized(forStyle: .footnote) }
var caption1: UIFont { return dinamicallySized(forStyle: .caption1) }
var caption2: UIFont { return dinamicallySized(forStyle: .caption2) }
}
public extension UIFont.Weight {
private static let equatableDiff: CGFloat = 0.0001
static let extraLight = UIFont.Weight(rawValue: UIFont.Weight.ultraLight.rawValue + equatableDiff)
static let book = UIFont.Weight(rawValue: -0.5)
static let demi = UIFont.Weight(rawValue: -0.5 + equatableDiff)
static let normal = UIFont.Weight(rawValue: 0 + equatableDiff)
static let demibold = UIFont.Weight(rawValue: UIFont.Weight.semibold.rawValue + equatableDiff)
static let extraBold = UIFont.Weight(rawValue: UIFont.Weight.black.rawValue + equatableDiff)
static let extraBlack = UIFont.Weight(rawValue: 0.8)
static let ultraBlack = UIFont.Weight(rawValue: UIFont.Weight.extraBlack.rawValue + equatableDiff)
static let fat = UIFont.Weight(rawValue: UIFont.Weight.ultraBlack.rawValue + equatableDiff)
static let poster = UIFont.Weight(rawValue: UIFont.Weight.fat.rawValue + equatableDiff)
var faceName: String {
switch self {
case .ultraLight: return "UltraLight"
case .extraLight: return "ExtraLight"
case .thin: return "Thin"
case .book: return "Book"
case .demi: return "Demi"
case .normal: return "Normal"
case .light: return "Light"
case .medium: return "Medium"
case .demibold: return "DemiBold"
case .semibold: return "SemiBold"
case .bold: return "Bold"
case .extraBold: return "ExtraBold"
case .heavy: return "Heavy"
case .black: return "Black"
case .extraBlack: return "ExtraBlack"
case .ultraBlack: return "UltraBlack"
case .fat: return "Fat"
case .poster: return "Poster"
default: return "Regular"
}
}
}
| 41.57931 | 124 | 0.688008 |
18ec3807ac6ba12265a778113dd09e190dc93a5d | 1,724 | //
// CircleView.swift
// chiff
//
// Copyright: see LICENSE.md
//
import UIKit
class RadioButton: UIView {
var enabled = false {
didSet {
innerCircle.isHidden = !enabled
}
}
var innerCircle: CAShapeLayer!
var outerCircle: CAShapeLayer!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
drawOuterCircle()
drawInnerCircle()
}
override init(frame: CGRect) {
super.init(frame: frame)
drawOuterCircle()
drawInnerCircle()
}
func drawInnerCircle() {
let radius = (bounds.width / 2) * (4/9)
let circleCenter = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let path = UIBezierPath(arcCenter: circleCenter, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
innerCircle = CAShapeLayer()
innerCircle.path = path.cgPath
innerCircle.fillColor = UIColor.primary.cgColor
innerCircle.isHidden = true
layer.addSublayer(innerCircle)
}
func drawOuterCircle() {
let radius = bounds.width / 2
let circleCenter = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let path = UIBezierPath(arcCenter: circleCenter, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
outerCircle = CAShapeLayer()
outerCircle.path = path.cgPath
outerCircle.fillColor = UIColor.clear.cgColor
outerCircle.strokeColor = UIColor.primaryHalfOpacity.cgColor
outerCircle.strokeStart = 0.0
outerCircle.strokeEnd = 1.0
outerCircle.lineWidth = 1.0
layer.addSublayer(outerCircle)
}
}
| 29.220339 | 147 | 0.636891 |
5d4728f64678e6034d4be06531b14d09a53b01ff | 56,047 | //
// SignalProducerLiftingSpec.swift
// ReactiveSwift
//
// Created by Neil Pankey on 6/14/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import Dispatch
import Foundation
import Result
@testable import Nimble
import Quick
@testable import ReactiveSwift
class SignalProducerLiftingSpec: QuickSpec {
override func spec() {
describe("map") {
it("should transform the values of the signal") {
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
let mappedProducer = producer.map { String($0 + 1) }
var lastValue: String?
mappedProducer.startWithValues {
lastValue = $0
return
}
expect(lastValue).to(beNil())
observer.send(value: 0)
expect(lastValue) == "1"
observer.send(value: 1)
expect(lastValue) == "2"
}
}
describe("mapError") {
it("should transform the errors of the signal") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 100, userInfo: nil)
var error: NSError?
producer
.mapError { _ in producerError }
.startWithFailed { error = $0 }
expect(error).to(beNil())
observer.send(error: TestError.default)
expect(error) == producerError
}
}
describe("lazyMap") {
describe("with a scheduled binding") {
var token: Lifetime.Token!
var lifetime: Lifetime!
var destination: [String] = []
var tupleProducer: SignalProducer<(character: String, other: Int), NoError>!
var tupleObserver: Signal<(character: String, other: Int), NoError>.Observer!
var theLens: SignalProducer<String, NoError>!
var getterCounter: Int = 0
var lensScheduler: TestScheduler!
var targetScheduler: TestScheduler!
var target: BindingTarget<String>!
beforeEach {
destination = []
token = Lifetime.Token()
lifetime = Lifetime(token)
let (producer, observer) = SignalProducer<(character: String, other: Int), NoError>.pipe()
tupleProducer = producer
tupleObserver = observer
lensScheduler = TestScheduler()
targetScheduler = TestScheduler()
getterCounter = 0
theLens = tupleProducer.lazyMap(on: lensScheduler) { (tuple: (character: String, other: Int)) -> String in
getterCounter += 1
return tuple.character
}
target = BindingTarget<String>(on: targetScheduler, lifetime: lifetime) {
destination.append($0)
}
target <~ theLens
}
it("should not propagate values until scheduled") {
// Send a value along
tupleObserver.send(value: (character: "🎃", other: 42))
// The destination should not change value, and the getter
// should not have evaluated yet, as neither has been scheduled
expect(destination) == []
expect(getterCounter) == 0
// Advance both schedulers
lensScheduler.advance()
targetScheduler.advance()
// The destination receives the previously-sent value, and the
// getter obviously evaluated
expect(destination) == ["🎃"]
expect(getterCounter) == 1
}
it("should evaluate the getter only when scheduled") {
// Send a value along
tupleObserver.send(value: (character: "🎃", other: 42))
// The destination should not change value, and the getter
// should not have evaluated yet, as neither has been scheduled
expect(destination) == []
expect(getterCounter) == 0
// When the getter's scheduler advances, the getter should
// be evaluated, but the destination still shouldn't accept
// the new value
lensScheduler.advance()
expect(getterCounter) == 1
expect(destination) == []
// Sending other values along shouldn't evaluate the getter
tupleObserver.send(value: (character: "😾", other: 42))
tupleObserver.send(value: (character: "🍬", other: 13))
tupleObserver.send(value: (character: "👻", other: 17))
expect(getterCounter) == 1
expect(destination) == []
// Push the scheduler along for the lens, and the getter
// should evaluate
lensScheduler.advance()
expect(getterCounter) == 2
// ...but the destination still won't receive the value
expect(destination) == []
// Finally, pushing the target scheduler along will
// propagate only the first and last values
targetScheduler.advance()
expect(getterCounter) == 2
expect(destination) == ["🎃", "👻"]
}
}
it("should return the result of the getter on each value change") {
let initialValue = (character: "🎃", other: 42)
let nextValue = (character: "😾", other: 74)
let scheduler = TestScheduler()
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe()
let theLens: SignalProducer<String, NoError> = tupleProducer.lazyMap(on: scheduler) { $0.character }
var output: [String] = []
theLens.startWithValues { value in
output.append(value)
}
tupleObserver.send(value: initialValue)
scheduler.advance()
expect(output) == ["🎃"]
tupleObserver.send(value: nextValue)
scheduler.advance()
expect(output) == ["🎃", "😾"]
}
it("should evaluate its getter lazily") {
let initialValue = (character: "🎃", other: 42)
let nextValue = (character: "😾", other: 74)
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe()
let scheduler = TestScheduler()
var output: [String] = []
var getterEvaluated = false
let theLens: SignalProducer<String, NoError> = tupleProducer.lazyMap(on: scheduler) { (tuple: (character: String, other: Int)) -> String in
getterEvaluated = true
return tuple.character
}
// No surprise here, but the getter should not be evaluated
// since the underlying producer has yet to be started.
expect(getterEvaluated).to(beFalse())
// Similarly, sending values won't cause anything to happen.
tupleObserver.send(value: initialValue)
expect(output).to(beEmpty())
expect(getterEvaluated).to(beFalse())
// Start the signal, appending future values to the output array
theLens.startWithValues { value in output.append(value) }
// Even when the producer has yet to start, there should be no
// evaluation of the getter
expect(getterEvaluated).to(beFalse())
// Now we send a value through the producer
tupleObserver.send(value: initialValue)
// The getter should still not be evaluated, as it has not yet
// been scheduled
expect(getterEvaluated).to(beFalse())
// Now advance the scheduler to allow things to proceed
scheduler.advance()
// Now the getter gets evaluated, and the output is what we'd
// expect
expect(getterEvaluated).to(beTrue())
expect(output) == ["🎃"]
// And now subsequent values continue to come through
tupleObserver.send(value: nextValue)
scheduler.advance()
expect(output) == ["🎃", "😾"]
}
it("should evaluate its getter lazily on a different scheduler") {
let initialValue = (character: "🎃", other: 42)
let nextValue = (character: "😾", other: 74)
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe()
let scheduler = TestScheduler()
var output: [String] = []
var getterEvaluated = false
let theLens: SignalProducer<String, NoError> = tupleProducer.lazyMap(on: scheduler) { (tuple: (character: String, other: Int)) -> String in
getterEvaluated = true
return tuple.character
}
// No surprise here, but the getter should not be evaluated
// since the underlying producer has yet to be started.
expect(getterEvaluated).to(beFalse())
// Similarly, sending values won't cause anything to happen.
tupleObserver.send(value: initialValue)
expect(output).to(beEmpty())
expect(getterEvaluated).to(beFalse())
// Start the signal, appending future values to the output array
theLens.startWithValues { value in output.append(value) }
// Even when the producer has yet to start, there should be no
// evaluation of the getter
expect(getterEvaluated).to(beFalse())
tupleObserver.send(value: initialValue)
// The getter should still not get evaluated, as it was not yet
// scheduled
expect(getterEvaluated).to(beFalse())
expect(output).to(beEmpty())
scheduler.run()
// Now that the scheduler's run, things can continue to move forward
expect(getterEvaluated).to(beTrue())
expect(output) == ["🎃"]
tupleObserver.send(value: nextValue)
// Subsequent values should still be held up by the scheduler
// not getting run
expect(output) == ["🎃"]
scheduler.run()
expect(output) == ["🎃", "😾"]
}
it("should evaluate its getter lazily on the scheduler we specify") {
let initialValue = (character: "🎃", other: 42)
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe()
let labelKey = DispatchSpecificKey<String>()
let testQueue = DispatchQueue(label: "test queue", target: .main)
testQueue.setSpecific(key: labelKey, value: "test queue")
testQueue.suspend()
let testScheduler = QueueScheduler(internalQueue: testQueue)
var output: [String] = []
var isOnTestQueue = false
let theLens = tupleProducer.lazyMap(on: testScheduler) { (tuple: (character: String, other: Int)) -> String in
isOnTestQueue = DispatchQueue.getSpecific(key: labelKey) == "test queue"
return tuple.character
}
// Start the signal, appending future values to the output array
theLens.startWithValues { value in output.append(value) }
testQueue.resume()
expect(isOnTestQueue).to(beFalse())
expect(output).to(beEmpty())
tupleObserver.send(value: initialValue)
expect(isOnTestQueue).toEventually(beTrue())
expect(output).toEventually(equal(["🎃"]))
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "lazyMap") { $0.lazyMap(on: $1) { $0 } }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "lazyMap") { $0.lazyMap(on: $1) { $0 } }
}
}
describe("filter") {
it("should omit values from the producer") {
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
let mappedProducer = producer.filter { $0 % 2 == 0 }
var lastValue: Int?
mappedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 0)
expect(lastValue) == 0
observer.send(value: 1)
expect(lastValue) == 0
observer.send(value: 2)
expect(lastValue) == 2
}
}
describe("skipNil") {
it("should forward only non-nil values") {
let (producer, observer) = SignalProducer<Int?, NoError>.pipe()
let mappedProducer = producer.skipNil()
var lastValue: Int?
mappedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: nil)
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: nil)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
}
}
describe("scan(_:_:)") {
it("should incrementally accumulate a value") {
let (baseProducer, observer) = SignalProducer<String, NoError>.pipe()
let producer = baseProducer.scan("", +)
var lastValue: String?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: "a")
expect(lastValue) == "a"
observer.send(value: "bb")
expect(lastValue) == "abb"
}
}
describe("scan(into:_:)") {
it("should incrementally accumulate a value") {
let (baseProducer, observer) = SignalProducer<String, NoError>.pipe()
let producer = baseProducer.scan(into: "") { $0 += $1 }
var lastValue: String?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: "a")
expect(lastValue) == "a"
observer.send(value: "bb")
expect(lastValue) == "abb"
}
}
describe("reduce(_:_:)") {
it("should accumulate one value") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.reduce(1, +)
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(completed) == true
expect(lastValue) == 4
}
it("should send the initial value if none are received") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.reduce(1, +)
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(lastValue) == 1
expect(completed) == true
}
}
describe("reduce(into:_:)") {
it("should accumulate one value") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.reduce(into: 1) { $0 += $1 }
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(completed) == true
expect(lastValue) == 4
}
it("should send the initial value if none are received") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.reduce(into: 1) { $0 += $1 }
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(lastValue) == 1
expect(completed) == true
}
}
describe("skip") {
it("should skip initial values") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.skip(first: 1)
var lastValue: Int?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue) == 2
}
it("should not skip any values when 0") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.skip(first: 0)
var lastValue: Int?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
}
}
describe("skipRepeats") {
it("should skip duplicate Equatable values") {
let (baseProducer, observer) = SignalProducer<Bool, NoError>.pipe()
let producer = baseProducer.skipRepeats()
var values: [Bool] = []
producer.startWithValues { values.append($0) }
expect(values) == []
observer.send(value: true)
expect(values) == [ true ]
observer.send(value: true)
expect(values) == [ true ]
observer.send(value: false)
expect(values) == [ true, false ]
observer.send(value: true)
expect(values) == [ true, false, true ]
}
it("should skip values according to a predicate") {
let (baseProducer, observer) = SignalProducer<String, NoError>.pipe()
let producer = baseProducer.skipRepeats { $0.characters.count == $1.characters.count }
var values: [String] = []
producer.startWithValues { values.append($0) }
expect(values) == []
observer.send(value: "a")
expect(values) == [ "a" ]
observer.send(value: "b")
expect(values) == [ "a" ]
observer.send(value: "cc")
expect(values) == [ "a", "cc" ]
observer.send(value: "d")
expect(values) == [ "a", "cc", "d" ]
}
}
describe("skipWhile") {
var producer: SignalProducer<Int, NoError>!
var observer: Signal<Int, NoError>.Observer!
var lastValue: Int?
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
producer = baseProducer.skip { $0 < 2 }
observer = incomingObserver
lastValue = nil
producer.startWithValues { lastValue = $0 }
}
it("should skip while the predicate is true") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 0)
expect(lastValue) == 0
}
it("should not skip any values when the predicate starts false") {
expect(lastValue).to(beNil())
observer.send(value: 3)
expect(lastValue) == 3
observer.send(value: 1)
expect(lastValue) == 1
}
}
describe("skipUntil") {
var producer: SignalProducer<Int, NoError>!
var observer: Signal<Int, NoError>.Observer!
var triggerObserver: Signal<(), NoError>.Observer!
var lastValue: Int? = nil
beforeEach {
let (baseProducer, baseIncomingObserver) = SignalProducer<Int, NoError>.pipe()
let (triggerProducer, incomingTriggerObserver) = SignalProducer<(), NoError>.pipe()
producer = baseProducer.skip(until: triggerProducer)
observer = baseIncomingObserver
triggerObserver = incomingTriggerObserver
lastValue = nil
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .failed, .completed, .interrupted:
break
}
}
}
it("should skip values until the trigger fires") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
triggerObserver.send(value: ())
observer.send(value: 0)
expect(lastValue) == 0
}
it("should skip values until the trigger completes") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
triggerObserver.sendCompleted()
observer.send(value: 0)
expect(lastValue) == 0
}
}
describe("take") {
it("should take initial values") {
let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe()
let producer = baseProducer.take(first: 2)
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
expect(completed) == false
observer.send(value: 1)
expect(lastValue) == 1
expect(completed) == false
observer.send(value: 2)
expect(lastValue) == 2
expect(completed) == true
}
it("should complete immediately after taking given number of values") {
let numbers = [ 1, 2, 4, 4, 5 ]
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, NoError> = SignalProducer { observer, _ in
// workaround `Class declaration cannot close over value 'observer' defined in outer scope`
let observer = observer
testScheduler.schedule {
for number in numbers {
observer.send(value: number)
}
}
}
var completed = false
producer
.take(first: numbers.count)
.startWithCompleted { completed = true }
expect(completed) == false
testScheduler.run()
expect(completed) == true
}
it("should interrupt when 0") {
let numbers = [ 1, 2, 4, 4, 5 ]
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, NoError> = SignalProducer { observer, _ in
// workaround `Class declaration cannot close over value 'observer' defined in outer scope`
let observer = observer
testScheduler.schedule {
for number in numbers {
observer.send(value: number)
}
}
}
var result: [Int] = []
var interrupted = false
producer
.take(first: 0)
.start { event in
switch event {
case let .value(number):
result.append(number)
case .interrupted:
interrupted = true
case .failed, .completed:
break
}
}
expect(interrupted) == true
testScheduler.run()
expect(result).to(beEmpty())
}
}
describe("collect") {
it("should collect all values") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
let producer = original.collect()
let expectedResult = [ 1, 2, 3 ]
var result: [Int]?
producer.startWithValues { value in
expect(result).to(beNil())
result = value
}
for number in expectedResult {
observer.send(value: number)
}
expect(result).to(beNil())
observer.sendCompleted()
expect(result) == expectedResult
}
it("should complete with an empty array if there are no values") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
let producer = original.collect()
var result: [Int]?
producer.startWithValues { result = $0 }
expect(result).to(beNil())
observer.sendCompleted()
expect(result) == []
}
it("should forward errors") {
let (original, observer) = SignalProducer<Int, TestError>.pipe()
let producer = original.collect()
var error: TestError?
producer.startWithFailed { error = $0 }
expect(error).to(beNil())
observer.send(error: .default)
expect(error) == TestError.default
}
it("should collect an exact count of values") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
let producer = original.collect(count: 3)
var observedValues: [[Int]] = []
producer.startWithValues { value in
observedValues.append(value)
}
var expectation: [[Int]] = []
for i in 1...7 {
observer.send(value: i)
if i % 3 == 0 {
expectation.append([Int]((i - 2)...i))
expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC()
} else {
expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC()
}
}
observer.sendCompleted()
expectation.append([7])
expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC()
}
it("should collect values until it matches a certain value") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
let producer = original.collect { _, value in value != 5 }
var expectedValues = [
[5, 5],
[42, 5],
]
producer.startWithValues { value in
expect(value) == expectedValues.removeFirst()
}
producer.startWithCompleted {
expect(expectedValues._bridgeToObjectiveC()) == []._bridgeToObjectiveC()
}
expectedValues
.flatMap { $0 }
.forEach(observer.send(value:))
observer.sendCompleted()
}
it("should collect values until it matches a certain condition on values") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
let producer = original.collect { values in values.reduce(0, +) == 10 }
var expectedValues = [
[1, 2, 3, 4],
[5, 6, 7, 8, 9],
]
producer.startWithValues { value in
expect(value) == expectedValues.removeFirst()
}
producer.startWithCompleted {
expect(expectedValues._bridgeToObjectiveC()) == []._bridgeToObjectiveC()
}
expectedValues
.flatMap { $0 }
.forEach(observer.send(value:))
observer.sendCompleted()
}
}
describe("takeUntil") {
var producer: SignalProducer<Int, NoError>!
var observer: Signal<Int, NoError>.Observer!
var triggerObserver: Signal<(), NoError>.Observer!
var lastValue: Int? = nil
var completed: Bool = false
beforeEach {
let (baseProducer, baseIncomingObserver) = SignalProducer<Int, NoError>.pipe()
let (triggerProducer, incomingTriggerObserver) = SignalProducer<(), NoError>.pipe()
producer = baseProducer.take(until: triggerProducer)
observer = baseIncomingObserver
triggerObserver = incomingTriggerObserver
lastValue = nil
completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
}
it("should take values until the trigger fires") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
expect(completed) == false
triggerObserver.send(value: ())
expect(completed) == true
}
it("should take values until the trigger completes") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
expect(completed) == false
triggerObserver.sendCompleted()
expect(completed) == true
}
it("should complete if the trigger fires immediately") {
expect(lastValue).to(beNil())
expect(completed) == false
triggerObserver.send(value: ())
expect(completed) == true
expect(lastValue).to(beNil())
}
}
describe("takeUntilReplacement") {
var producer: SignalProducer<Int, NoError>!
var observer: Signal<Int, NoError>.Observer!
var replacementObserver: Signal<Int, NoError>.Observer!
var lastValue: Int? = nil
var completed: Bool = false
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
let (replacementProducer, incomingReplacementObserver) = SignalProducer<Int, NoError>.pipe()
producer = baseProducer.take(untilReplacement: replacementProducer)
observer = incomingObserver
replacementObserver = incomingReplacementObserver
lastValue = nil
completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
}
it("should take values from the original then the replacement") {
expect(lastValue).to(beNil())
expect(completed) == false
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
replacementObserver.send(value: 3)
expect(lastValue) == 3
expect(completed) == false
observer.send(value: 4)
expect(lastValue) == 3
expect(completed) == false
replacementObserver.send(value: 5)
expect(lastValue) == 5
expect(completed) == false
replacementObserver.sendCompleted()
expect(completed) == true
}
}
describe("takeWhile") {
var producer: SignalProducer<Int, NoError>!
var observer: Signal<Int, NoError>.Observer!
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
producer = baseProducer.take { $0 <= 4 }
observer = incomingObserver
}
it("should take while the predicate is true") {
var latestValue: Int!
var completed = false
producer.start { event in
switch event {
case let .value(value):
latestValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
for value in -1...4 {
observer.send(value: value)
expect(latestValue) == value
expect(completed) == false
}
observer.send(value: 5)
expect(latestValue) == 4
expect(completed) == true
}
it("should complete if the predicate starts false") {
var latestValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
latestValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
observer.send(value: 5)
expect(latestValue).to(beNil())
expect(completed) == true
}
}
describe("observeOn") {
it("should send events on the given scheduler") {
let testScheduler = TestScheduler()
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
var result: [Int] = []
producer
.observe(on: testScheduler)
.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
expect(result).to(beEmpty())
testScheduler.run()
expect(result) == [ 1, 2 ]
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "observe(on:)") { $0.observe(on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "observe(on:)") { $0.observe(on: $1) }
}
}
describe("delay") {
it("should send events on the given scheduler after the interval") {
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, NoError> = SignalProducer { observer, _ in
testScheduler.schedule {
observer.send(value: 1)
}
testScheduler.schedule(after: .seconds(5)) {
observer.send(value: 2)
observer.sendCompleted()
}
}
var result: [Int] = []
var completed = false
producer
.delay(10, on: testScheduler)
.start { event in
switch event {
case let .value(number):
result.append(number)
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
testScheduler.advance(by: .seconds(4)) // send initial value
expect(result).to(beEmpty())
testScheduler.advance(by: .seconds(10)) // send second value and receive first
expect(result) == [ 1 ]
expect(completed) == false
testScheduler.advance(by: .seconds(10)) // send second value and receive first
expect(result) == [ 1, 2 ]
expect(completed) == true
}
it("should schedule errors immediately") {
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, TestError> = SignalProducer { observer, _ in
// workaround `Class declaration cannot close over value 'observer' defined in outer scope`
let observer = observer
testScheduler.schedule {
observer.send(error: TestError.default)
}
}
var errored = false
producer
.delay(10, on: testScheduler)
.startWithFailed { _ in errored = true }
testScheduler.advance()
expect(errored) == true
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "delay") { $0.delay(10.0, on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "delay") { $0.delay(10.0, on: $1) }
}
}
describe("throttle") {
var scheduler: TestScheduler!
var observer: Signal<Int, NoError>.Observer!
var producer: SignalProducer<Int, NoError>!
beforeEach {
scheduler = TestScheduler()
let (baseProducer, baseObserver) = SignalProducer<Int, NoError>.pipe()
observer = baseObserver
producer = baseProducer.throttle(1, on: scheduler)
}
it("should send values on the given scheduler at no less than the interval") {
var values: [Int] = []
producer.startWithValues { value in
values.append(value)
}
expect(values) == []
observer.send(value: 0)
expect(values) == []
scheduler.advance()
expect(values) == [ 0 ]
observer.send(value: 1)
observer.send(value: 2)
expect(values) == [ 0 ]
scheduler.advance(by: .milliseconds(1500))
expect(values) == [ 0, 2 ]
scheduler.advance(by: .seconds(3))
expect(values) == [ 0, 2 ]
observer.send(value: 3)
expect(values) == [ 0, 2 ]
scheduler.advance()
expect(values) == [ 0, 2, 3 ]
observer.send(value: 4)
observer.send(value: 5)
scheduler.advance()
expect(values) == [ 0, 2, 3 ]
scheduler.rewind(by: .seconds(2))
expect(values) == [ 0, 2, 3 ]
observer.send(value: 6)
scheduler.advance()
expect(values) == [ 0, 2, 3, 6 ]
observer.send(value: 7)
observer.send(value: 8)
scheduler.advance()
expect(values) == [ 0, 2, 3, 6 ]
scheduler.run()
expect(values) == [ 0, 2, 3, 6, 8 ]
}
it("should schedule completion immediately") {
var values: [Int] = []
var completed = false
producer.start { event in
switch event {
case let .value(value):
values.append(value)
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
observer.send(value: 0)
scheduler.advance()
expect(values) == [ 0 ]
observer.send(value: 1)
observer.sendCompleted()
expect(completed) == false
scheduler.run()
expect(values) == [ 0 ]
expect(completed) == true
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "throttle") { $0.throttle(10.0, on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "throttle") { $0.throttle(10.0, on: $1) }
}
}
describe("debounce") {
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "debounce") { $0.debounce(10.0, on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "debounce") { $0.debounce(10.0, on: $1) }
}
}
describe("sampleWith") {
var sampledProducer: SignalProducer<(Int, String), NoError>!
var observer: Signal<Int, NoError>.Observer!
var samplerObserver: Signal<String, NoError>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
let (sampler, incomingSamplerObserver) = SignalProducer<String, NoError>.pipe()
sampledProducer = producer.sample(with: sampler)
observer = incomingObserver
samplerObserver = incomingSamplerObserver
}
it("should forward the latest value when the sampler fires") {
var result: [String] = []
sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
observer.send(value: 2)
samplerObserver.send(value: "a")
expect(result) == [ "2a" ]
}
it("should do nothing if sampler fires before signal receives value") {
var result: [String] = []
sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") }
samplerObserver.send(value: "a")
expect(result).to(beEmpty())
}
it("should send lates value multiple times when sampler fires multiple times") {
var result: [String] = []
sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
samplerObserver.send(value: "a")
samplerObserver.send(value: "b")
expect(result) == [ "1a", "1b" ]
}
it("should complete when both inputs have completed") {
var completed = false
sampledProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == false
samplerObserver.sendCompleted()
expect(completed) == true
}
it("should emit an initial value if the sampler is a synchronous SignalProducer") {
let producer = SignalProducer<Int, NoError>([1])
let sampler = SignalProducer<String, NoError>(value: "a")
let result = producer.sample(with: sampler)
var valueReceived: String?
result.startWithValues { valueReceived = "\($0.0)\($0.1)" }
expect(valueReceived) == "1a"
}
}
describe("sampleOn") {
var sampledProducer: SignalProducer<Int, NoError>!
var observer: Signal<Int, NoError>.Observer!
var samplerObserver: Signal<(), NoError>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
let (sampler, incomingSamplerObserver) = SignalProducer<(), NoError>.pipe()
sampledProducer = producer.sample(on: sampler)
observer = incomingObserver
samplerObserver = incomingSamplerObserver
}
it("should forward the latest value when the sampler fires") {
var result: [Int] = []
sampledProducer.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
samplerObserver.send(value: ())
expect(result) == [ 2 ]
}
it("should do nothing if sampler fires before signal receives value") {
var result: [Int] = []
sampledProducer.startWithValues { result.append($0) }
samplerObserver.send(value: ())
expect(result).to(beEmpty())
}
it("should send lates value multiple times when sampler fires multiple times") {
var result: [Int] = []
sampledProducer.startWithValues { result.append($0) }
observer.send(value: 1)
samplerObserver.send(value: ())
samplerObserver.send(value: ())
expect(result) == [ 1, 1 ]
}
it("should complete when both inputs have completed") {
var completed = false
sampledProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == false
samplerObserver.sendCompleted()
expect(completed) == true
}
it("should emit an initial value if the sampler is a synchronous SignalProducer") {
let producer = SignalProducer<Int, NoError>([1])
let sampler = SignalProducer<(), NoError>(value: ())
let result = producer.sample(on: sampler)
var valueReceived: Int?
result.startWithValues { valueReceived = $0 }
expect(valueReceived) == 1
}
describe("memory") {
class Payload {
let action: () -> Void
init(onDeinit action: @escaping () -> Void) {
self.action = action
}
deinit {
action()
}
}
var sampledProducer: SignalProducer<Payload, NoError>!
var samplerObserver: Signal<(), NoError>.Observer!
var observer: Signal<Payload, NoError>.Observer!
// Mitigate the "was written to, but never read" warning.
_ = samplerObserver
beforeEach {
let (producer, incomingObserver) = SignalProducer<Payload, NoError>.pipe()
let (sampler, _samplerObserver) = Signal<(), NoError>.pipe()
sampledProducer = producer.sample(on: sampler)
samplerObserver = _samplerObserver
observer = incomingObserver
}
it("should free payload when interrupted after complete of incoming producer") {
var payloadFreed = false
let disposable = sampledProducer.start()
observer.send(value: Payload { payloadFreed = true })
observer.sendCompleted()
expect(payloadFreed) == false
disposable.dispose()
expect(payloadFreed) == true
}
}
}
describe("withLatest(from: signal)") {
var withLatestProducer: SignalProducer<(Int, String), NoError>!
var observer: Signal<Int, NoError>.Observer!
var sampleeObserver: Signal<String, NoError>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
let (samplee, incomingSampleeObserver) = Signal<String, NoError>.pipe()
withLatestProducer = producer.withLatest(from: samplee)
observer = incomingObserver
sampleeObserver = incomingSampleeObserver
}
it("should forward the latest value when the receiver fires") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
sampleeObserver.send(value: "b")
observer.send(value: 1)
expect(result) == [ "1b" ]
}
it("should do nothing if receiver fires before samplee sends value") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
expect(result).to(beEmpty())
}
it("should send latest value with samplee value multiple times when receiver fires multiple times") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
observer.send(value: 1)
observer.send(value: 2)
expect(result) == [ "1a", "2a" ]
}
it("should complete when receiver has completed") {
var completed = false
withLatestProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == true
}
it("should not affect when samplee has completed") {
var event: Signal<(Int, String), NoError>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendCompleted()
expect(event).to(beNil())
}
it("should not affect when samplee has interrupted") {
var event: Signal<(Int, String), NoError>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendInterrupted()
expect(event).to(beNil())
}
}
describe("withLatest(from: producer)") {
var withLatestProducer: SignalProducer<(Int, String), NoError>!
var observer: Signal<Int, NoError>.Observer!
var sampleeObserver: Signal<String, NoError>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
let (samplee, incomingSampleeObserver) = SignalProducer<String, NoError>.pipe()
withLatestProducer = producer.withLatest(from: samplee)
observer = incomingObserver
sampleeObserver = incomingSampleeObserver
}
it("should forward the latest value when the receiver fires") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
sampleeObserver.send(value: "b")
observer.send(value: 1)
expect(result) == [ "1b" ]
}
it("should do nothing if receiver fires before samplee sends value") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
expect(result).to(beEmpty())
}
it("should send latest value with samplee value multiple times when receiver fires multiple times") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
observer.send(value: 1)
observer.send(value: 2)
expect(result) == [ "1a", "2a" ]
}
it("should complete when receiver has completed") {
var completed = false
withLatestProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == true
}
it("should not affect when samplee has completed") {
var event: Signal<(Int, String), NoError>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendCompleted()
expect(event).to(beNil())
}
it("should not affect when samplee has interrupted") {
var event: Signal<(Int, String), NoError>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendInterrupted()
expect(event).to(beNil())
}
}
describe("combineLatestWith") {
var combinedProducer: SignalProducer<(Int, Double), NoError>!
var observer: Signal<Int, NoError>.Observer!
var otherObserver: Signal<Double, NoError>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe()
let (otherSignal, incomingOtherObserver) = SignalProducer<Double, NoError>.pipe()
combinedProducer = producer.combineLatest(with: otherSignal)
observer = incomingObserver
otherObserver = incomingOtherObserver
}
it("should forward the latest values from both inputs") {
var latest: (Int, Double)?
combinedProducer.startWithValues { latest = $0 }
observer.send(value: 1)
expect(latest).to(beNil())
// is there a better way to test tuples?
otherObserver.send(value: 1.5)
expect(latest?.0) == 1
expect(latest?.1) == 1.5
observer.send(value: 2)
expect(latest?.0) == 2
expect(latest?.1) == 1.5
}
it("should complete when both inputs have completed") {
var completed = false
combinedProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == false
otherObserver.sendCompleted()
expect(completed) == true
}
}
describe("zipWith") {
var leftObserver: Signal<Int, NoError>.Observer!
var rightObserver: Signal<String, NoError>.Observer!
var zipped: SignalProducer<(Int, String), NoError>!
beforeEach {
let (leftProducer, incomingLeftObserver) = SignalProducer<Int, NoError>.pipe()
let (rightProducer, incomingRightObserver) = SignalProducer<String, NoError>.pipe()
leftObserver = incomingLeftObserver
rightObserver = incomingRightObserver
zipped = leftProducer.zip(with: rightProducer)
}
it("should combine pairs") {
var result: [String] = []
zipped.startWithValues { result.append("\($0.0)\($0.1)") }
leftObserver.send(value: 1)
leftObserver.send(value: 2)
expect(result) == []
rightObserver.send(value: "foo")
expect(result) == [ "1foo" ]
leftObserver.send(value: 3)
rightObserver.send(value: "bar")
expect(result) == [ "1foo", "2bar" ]
rightObserver.send(value: "buzz")
expect(result) == [ "1foo", "2bar", "3buzz" ]
rightObserver.send(value: "fuzz")
expect(result) == [ "1foo", "2bar", "3buzz" ]
leftObserver.send(value: 4)
expect(result) == [ "1foo", "2bar", "3buzz", "4fuzz" ]
}
it("should complete when the shorter signal has completed") {
var result: [String] = []
var completed = false
zipped.start { event in
switch event {
case let .value(left, right):
result.append("\(left)\(right)")
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(completed) == false
leftObserver.send(value: 0)
leftObserver.sendCompleted()
expect(completed) == false
expect(result) == []
rightObserver.send(value: "foo")
expect(completed) == true
expect(result) == [ "0foo" ]
}
}
describe("materialize") {
it("should reify events from the signal") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
var latestEvent: Signal<Int, TestError>.Event?
producer
.materialize()
.startWithValues { latestEvent = $0 }
observer.send(value: 2)
expect(latestEvent).toNot(beNil())
if let latestEvent = latestEvent {
switch latestEvent {
case let .value(value):
expect(value) == 2
case .failed, .completed, .interrupted:
fail()
}
}
observer.send(error: TestError.default)
if let latestEvent = latestEvent {
switch latestEvent {
case .failed:
break
case .value, .completed, .interrupted:
fail()
}
}
}
}
describe("dematerialize") {
typealias IntEvent = Signal<Int, TestError>.Event
var observer: Signal<IntEvent, NoError>.Observer!
var dematerialized: SignalProducer<Int, TestError>!
beforeEach {
let (producer, incomingObserver) = SignalProducer<IntEvent, NoError>.pipe()
observer = incomingObserver
dematerialized = producer.dematerialize()
}
it("should send values for Value events") {
var result: [Int] = []
dematerialized
.assumeNoErrors()
.startWithValues { result.append($0) }
expect(result).to(beEmpty())
observer.send(value: .value(2))
expect(result) == [ 2 ]
observer.send(value: .value(4))
expect(result) == [ 2, 4 ]
}
it("should error out for Error events") {
var errored = false
dematerialized.startWithFailed { _ in errored = true }
expect(errored) == false
observer.send(value: .failed(TestError.default))
expect(errored) == true
}
it("should complete early for Completed events") {
var completed = false
dematerialized.startWithCompleted { completed = true }
expect(completed) == false
observer.send(value: IntEvent.completed)
expect(completed) == true
}
}
describe("takeLast") {
var observer: Signal<Int, TestError>.Observer!
var lastThree: SignalProducer<Int, TestError>!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, TestError>.pipe()
observer = incomingObserver
lastThree = producer.take(last: 3)
}
it("should send the last N values upon completion") {
var result: [Int] = []
lastThree
.assumeNoErrors()
.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
expect(result).to(beEmpty())
observer.sendCompleted()
expect(result) == [ 2, 3, 4 ]
}
it("should send less than N values if not enough were received") {
var result: [Int] = []
lastThree
.assumeNoErrors()
.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
observer.sendCompleted()
expect(result) == [ 1, 2 ]
}
it("should send nothing when errors") {
var result: [Int] = []
var errored = false
lastThree.start { event in
switch event {
case let .value(value):
result.append(value)
case .failed:
errored = true
case .completed, .interrupted:
break
}
}
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
expect(errored) == false
observer.send(error: TestError.default)
expect(errored) == true
expect(result).to(beEmpty())
}
}
describe("timeoutWithError") {
var testScheduler: TestScheduler!
var producer: SignalProducer<Int, TestError>!
var observer: Signal<Int, TestError>.Observer!
beforeEach {
testScheduler = TestScheduler()
let (baseProducer, incomingObserver) = SignalProducer<Int, TestError>.pipe()
producer = baseProducer.timeout(after: 2, raising: TestError.default, on: testScheduler)
observer = incomingObserver
}
it("should complete if within the interval") {
var completed = false
var errored = false
producer.start { event in
switch event {
case .completed:
completed = true
case .failed:
errored = true
case .value, .interrupted:
break
}
}
testScheduler.schedule(after: .seconds(1)) {
observer.sendCompleted()
}
expect(completed) == false
expect(errored) == false
testScheduler.run()
expect(completed) == true
expect(errored) == false
}
it("should error if not completed before the interval has elapsed") {
var completed = false
var errored = false
producer.start { event in
switch event {
case .completed:
completed = true
case .failed:
errored = true
case .value, .interrupted:
break
}
}
testScheduler.schedule(after: .seconds(3)) {
observer.sendCompleted()
}
expect(completed) == false
expect(errored) == false
testScheduler.run()
expect(completed) == false
expect(errored) == true
}
it("should be available for NoError") {
let producer: SignalProducer<Int, TestError> = SignalProducer<Int, NoError>.never
.timeout(after: 2, raising: TestError.default, on: testScheduler)
_ = producer
}
}
describe("attempt") {
it("should forward original values upon success") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attempt { _ in
return .success(())
}
var current: Int?
producer
.assumeNoErrors()
.startWithValues { value in
current = value
}
for value in 1...5 {
observer.send(value: value)
expect(current) == value
}
}
it("should error if an attempt fails") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attempt { _ in
return .failure(.default)
}
var error: TestError?
producer.startWithFailed { err in
error = err
}
observer.send(value: 42)
expect(error) == TestError.default
}
}
describe("attemptMap") {
it("should forward mapped values upon success") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attemptMap { num -> Result<Bool, TestError> in
return .success(num % 2 == 0)
}
var even: Bool?
producer
.assumeNoErrors()
.startWithValues { value in
even = value
}
observer.send(value: 1)
expect(even) == false
observer.send(value: 2)
expect(even) == true
}
it("should error if a mapping fails") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attemptMap { _ -> Result<Bool, TestError> in
return .failure(.default)
}
var error: TestError?
producer.startWithFailed { err in
error = err
}
observer.send(value: 42)
expect(error) == TestError.default
}
}
describe("combinePrevious") {
var observer: Signal<Int, NoError>.Observer!
let initialValue: Int = 0
var latestValues: (Int, Int)?
beforeEach {
latestValues = nil
let (signal, baseObserver) = SignalProducer<Int, NoError>.pipe()
observer = baseObserver
signal.combinePrevious(initialValue).startWithValues { latestValues = $0 }
}
it("should forward the latest value with previous value") {
expect(latestValues).to(beNil())
observer.send(value: 1)
expect(latestValues?.0) == initialValue
expect(latestValues?.1) == 1
observer.send(value: 2)
expect(latestValues?.0) == 1
expect(latestValues?.1) == 2
}
}
}
}
private func testAsyncInterruptionScheduler(
op: String,
file: FileString = #file,
line: UInt = #line,
transform: (SignalProducer<Int, NoError>, TestScheduler) -> SignalProducer<Int, NoError>
) {
var isInterrupted = false
let scheduler = TestScheduler()
let producer = transform(SignalProducer(0 ..< 128), scheduler)
let failedExpectations = gatherFailingExpectations {
let disposable = producer.startWithInterrupted { isInterrupted = true }
expect(isInterrupted) == false
disposable.dispose()
expect(isInterrupted) == false
scheduler.run()
expect(isInterrupted) == true
}
if !failedExpectations.isEmpty {
fail("The async operator `\(op)` does not interrupt on the appropriate scheduler.",
location: SourceLocation(file: file, line: line))
}
}
private func testAsyncASAPInterruption(
op: String,
file: FileString = #file,
line: UInt = #line,
transform: (SignalProducer<Int, NoError>, TestScheduler) -> SignalProducer<Int, NoError>
) {
var valueCount = 0
var interruptCount = 0
var unexpectedEventCount = 0
let scheduler = TestScheduler()
let disposable = transform(SignalProducer(0 ..< 128), scheduler)
.start { event in
switch event {
case .value:
valueCount += 1
case .interrupted:
interruptCount += 1
case .failed, .completed:
unexpectedEventCount += 1
}
}
expect(interruptCount) == 0
expect(unexpectedEventCount) == 0
expect(valueCount) == 0
disposable.dispose()
scheduler.run()
let failedExpectations = gatherFailingExpectations {
expect(interruptCount) == 1
expect(unexpectedEventCount) == 0
expect(valueCount) == 0
}
if !failedExpectations.isEmpty {
fail("The ASAP interruption test of the async operator `\(op)` has failed.",
location: SourceLocation(file: file, line: line))
}
}
| 26.325505 | 143 | 0.650418 |
e86127eaed8c04f0974f1c5af436c316afe0424b | 442 | //
// OtroReplace.swift
// myCustomTestCharly
//
// Created by Charly Maxter on 17/10/2018.
//
import Foundation
class OtroReplace{
private var user: String = "user"
private var pass: String = "pass"
init(us: String, pass: String) {
self.user = us
self.pass = pass
}
private func setUser(){
}
public func getUser() -> String{
return self.user
}
}
| 15.241379 | 43 | 0.552036 |
e9d1d58bf3387a045f2cee595902f282244fbf3c | 6,535 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class GroupCreateViewController: AAViewController, UITextFieldDelegate {
private var addPhotoButton = UIButton()
private var avatarImageView = UIImageView()
private var hint = UILabel()
private var groupName = UITextField()
private var groupNameFieldSeparator = UIView()
private var image: UIImage?
override init(){
super.init(nibName: nil, bundle: nil)
self.navigationItem.title = NSLocalizedString("CreateGroupTitle", comment: "Compose Title")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: localized("NavigationNext"), style: UIBarButtonItemStyle.Plain, target: self, action: "doNext")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
view.addSubview(addPhotoButton)
view.addSubview(avatarImageView)
view.addSubview(hint)
view.addSubview(groupName)
view.addSubview(groupNameFieldSeparator)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 110, height: 110), false, 0.0);
let context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor);
CGContextFillEllipseInRect(context, CGRectMake(0.0, 0.0, 110.0, 110.0));
CGContextSetStrokeColorWithColor(context, UIColor.RGB(0xd9d9d9).CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextStrokeEllipseInRect(context, CGRectMake(0.5, 0.5, 109.0, 109.0));
let buttonImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
addPhotoButton.exclusiveTouch = true
addPhotoButton.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
addPhotoButton.addTarget(self, action: "photoTap", forControlEvents: UIControlEvents.TouchUpInside)
let addPhotoLabelFirst = UILabel()
addPhotoLabelFirst.text = NSLocalizedString("AuthProfileAddPhoto1", comment: "Title")
addPhotoLabelFirst.font = UIFont.systemFontOfSize(15.0)
addPhotoLabelFirst.backgroundColor = UIColor.clearColor()
addPhotoLabelFirst.textColor = UIColor.RGB(0xd9d9d9)
addPhotoLabelFirst.sizeToFit()
let addPhotoLabelSecond = UILabel()
addPhotoLabelSecond.text = NSLocalizedString("AuthProfileAddPhoto2", comment: "Title")
addPhotoLabelSecond.font = UIFont.systemFontOfSize(15.0)
addPhotoLabelSecond.backgroundColor = UIColor.clearColor()
addPhotoLabelSecond.textColor = UIColor.RGB(0xd9d9d9)
addPhotoLabelSecond.sizeToFit()
addPhotoButton.addSubview(addPhotoLabelFirst)
addPhotoButton.addSubview(addPhotoLabelSecond)
addPhotoLabelFirst.frame = CGRectIntegral(CGRectMake((80 - addPhotoLabelFirst.frame.size.width) / 2, 22, addPhotoLabelFirst.frame.size.width, addPhotoLabelFirst.frame.size.height));
addPhotoLabelSecond.frame = CGRectIntegral(CGRectMake((80 - addPhotoLabelSecond.frame.size.width) / 2, 22 + 22, addPhotoLabelSecond.frame.size.width, addPhotoLabelSecond.frame.size.height));
// groupName.backgroundColor = UIColor.whiteColor()
groupName.backgroundColor = MainAppTheme.list.bgColor
groupName.textColor = MainAppTheme.list.textColor
groupName.font = UIFont.systemFontOfSize(20)
groupName.keyboardType = UIKeyboardType.Default
groupName.returnKeyType = UIReturnKeyType.Next
groupName.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("CreateGroupNamePlaceholder", comment: "Enter group title"), attributes: [NSForegroundColorAttributeName: MainAppTheme.list.hintColor])
groupName.delegate = self
groupName.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
groupName.autocapitalizationType = UITextAutocapitalizationType.Words
groupNameFieldSeparator.backgroundColor = MainAppTheme.list.separatorColor
hint.text = localized("CreateGroupHint")
hint.font = UIFont.systemFontOfSize(15)
hint.lineBreakMode = .ByWordWrapping
hint.numberOfLines = 0
hint.textColor = MainAppTheme.list.hintColor
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let screenSize = UIScreen.mainScreen().bounds.size
avatarImageView.frame = CGRectMake(20, 20 + 66, 80, 80)
addPhotoButton.frame = avatarImageView.frame
hint.frame = CGRectMake(120, 20 + 66, screenSize.width - 140, 80)
groupName.frame = CGRectMake(20, 106 + 66, screenSize.width - 20, 56.0)
groupNameFieldSeparator.frame = CGRectMake(20, 156 + 66, screenSize.width - 20, 1)
}
func photoTap() {
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.avatarImageView.image != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.avatarImageView.image = nil
self.image = nil
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
self.image = image
self.avatarImageView.image = image.roundImage(80)
})
}
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
groupName.becomeFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
doNext()
return false
}
func doNext() {
let title = groupName.text!.trim()
if (title.length == 0) {
shakeView(groupName, originalX: groupName.frame.origin.x)
return
}
navigateNext(GroupMembersController(title: title, image: image), removeCurrent: true)
}
} | 44.760274 | 222 | 0.669472 |
1c4de4249560856dbd8ac0e55848137a3c7376e1 | 2,898 | import Foundation
import CiFoundation
import Emcee
import SingletonHell
import RemoteFiles
import Bash
public final class EmceeFileUploaderImpl: EmceeFileUploader {
private let fileUploader: FileUploader
private let temporaryFileProvider: TemporaryFileProvider
private let bashExecutor: BashExecutor
public init(
fileUploader: FileUploader,
temporaryFileProvider: TemporaryFileProvider,
bashExecutor: BashExecutor)
{
self.fileUploader = fileUploader
self.temporaryFileProvider = temporaryFileProvider
self.bashExecutor = bashExecutor
}
public func upload(path: String) throws -> URL {
let basename = (path as NSString).lastPathComponent
let components = basename.components(separatedBy: ".")
guard let `extension` = components.last else {
throw ErrorString("upload requires file to have an extension. file: \(path)")
}
let filename = components.dropLast().joined(separator: ".")
let sum = try checksum(file: path)
return try upload_zipped_for_emcee(
file: path,
remoteName: "\(filename)-\(sum).\(`extension`)"
)
}
public func upload_zipped_for_emcee(
file: String)
throws
-> URL
{
return try upload_zipped_for_emcee(
file: file,
remoteName: (file as NSString).lastPathComponent
)
}
public func upload_zipped_for_emcee(
file: String,
remoteName: String)
throws
-> URL
{
let temporaryDirectory = temporaryFileProvider.temporaryFilePath()
try FileManager.default.createDirectory(
atPath: temporaryDirectory,
withIntermediateDirectories: true,
attributes: nil
)
let basename = (file as NSString).lastPathComponent
_ = try bashExecutor.executeOrThrow(
command: """
zip -r "\(temporaryDirectory)/\(remoteName).zip" "\(basename)" 1>/dev/null 2>/dev/null
""",
currentDirectory: (file as NSString).deletingLastPathComponent
)
let remoteZip = try fileUploader.upload(
file: "\(temporaryDirectory)/\(remoteName).zip",
remoteName: "\(remoteName).zip"
)
return try URL.from(string: "\(remoteZip.absoluteString)#\(basename)")
}
// supports folders
public func checksum(file: String) throws -> String {
return try bashExecutor.executeAndReturnTrimmedOutputOrThrow(
command:
"""
set -o pipefail
find "\(file)" -type f -print0 \
| sort -z \
| xargs -0 shasum \
| shasum \
| grep -oE "^\\S+"
"""
)
}
}
| 29.876289 | 98 | 0.586611 |
dbef684347dab9bd869474f07230e8bdaadd0f05 | 9,550 | //
// ViewController.swift
// Sech
//
// Created by Peter Stoehr on 29.08.15.
// Copyright © 2015 Peter Stoehr. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet var detailView: NSTextView!
@IBOutlet weak var ComboBox_Detail: NSComboBox!
var dateFormatter = NSDateFormatter()
//Show select documentbag
@IBAction func itemIsSelect(sender: NSComboBoxCell) {
print("\n")
print(sender.objectValue)
// self.detailRequestJSON.setKeyValuePair("documentBadge", value: [sender.objectValue!])
}
var msg:NSData? = nil
let MAINCONTROLLER = MainController()
override func viewDidLoad() {
super.viewDidLoad()
//fill KeyWordType ComboBox
self.ComboBox_TypeOfKeyword.addItemWithObjectValue(JSONManager.CONTEXT_KEYWORDS_MISC)
self.ComboBox_TypeOfKeyword.addItemWithObjectValue(JSONManager.CONTEXT_KEYWORDS_PERSON)
self.ComboBox_TypeOfKeyword.addItemWithObjectValue(JSONManager.CONTEXT_KEYWORDS_LOCATION)
self.ComboBox_TypeOfKeyword.addItemWithObjectValue(JSONManager.CONTEXT_KEYWORDS_ORGANIZATION)
self.ComboBox_TypeOfKeyword.selectItemWithObjectValue(JSONManager.CONTEXT_KEYWORDS_ORGANIZATION)
self.ComboBox_Detail.addItemWithObjectValue("take all")
self.ComboBox_TypeOfKeyword.selectItemWithObjectValue("take all")
self.genderComboBox.addItemWithObjectValue("male")
self.genderComboBox.addItemWithObjectValue("female")
self.languageComboBox.addItemWithObjectValue("de")
self.languageComboBox.addItemWithObjectValue("en")
self.languageComboBox.selectItemWithObjectValue("de")
// --------------
self.MAINCONTROLLER.setMethodForResponse({ (succeeded: Bool, msg: NSData) -> () in
if(succeeded) {
dispatch_async(dispatch_get_main_queue(), {
let str = String(data: msg, encoding: NSUTF8StringEncoding)!
self.response.string = str
self.msg = msg
// self.MAINCONTROLLER.mapOfJSONs.removeAll()
self.MAINCONTROLLER.mapOfJSONs["\(self.recommendation.stringValue)"] = JSONObject(data: msg)
self.ComboBox_Detail.addItemsWithObjectValues(self.MAINCONTROLLER.seperateDocumentBages(self.MAINCONTROLLER.mapOfJSONs["\(self.recommendation.stringValue)"]!))
})
}
else {
self.response.string = "Error"
}
})
self.MAINCONTROLLER.setMethodForDetaileResponce({(succeeded: Bool, msg: NSData) -> () in
if(succeeded)
{
dispatch_async(dispatch_get_main_queue(), {
self.detailView.string = String(data: msg, encoding: NSUTF8StringEncoding)!
self.msg = msg
self.MAINCONTROLLER.mapOfJSONs["\(self.recommendation.stringValue)_DETAIL"] = JSONObject(data: msg)
})
}
else {
self.response.string = "Error"
}
})
// Do any additional setup after loading the view.
recommendation.delegate = self
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
// -------------------------------------------------Request----------------------------------
@IBOutlet weak var ComboBox_RequestKeywords: NSComboBox!
@IBOutlet weak var ComboBox_TypeOfKeyword: NSComboBox!
@IBOutlet weak var recommendation: NSTextField!
@IBOutlet var response: NSTextView!
@IBOutlet weak var checkBoxIsMainTopic: NSButton!
@IBOutlet weak var genderComboBox: NSComboBox!
@IBOutlet weak var languageComboBox: NSComboBox!
@IBOutlet weak var cityTextField: NSTextField!
@IBOutlet weak var countryTextField: NSTextField!
@IBOutlet weak var agePicker: NSDatePicker!
var jsonKeys = [[String:JSONObject]]()
var preferences = [String:String]()
@IBAction func DoIt(sender: NSButtonCell) {
doSplit()
}
@IBAction func sendRequest(sender: AnyObject) {
let now = NSDate()
let dateOfBirth = agePicker.dateValue
preferences["gender"] = genderComboBox.stringValue
preferences["language"] = languageComboBox.stringValue
preferences["city"] = cityTextField.stringValue
preferences["country"] = countryTextField.stringValue
let ageInYears = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: dateOfBirth, toDate: now, options: NSCalendarOptions.WrapComponents).year
preferences["age"] = String (ageInYears)
var jsons = [[JSONObject]]()
for json in jsonKeys{
var jsonArray = [JSONObject]()
for jsonValue in json {
jsonArray.append(jsonValue.1)
}
jsons.append(jsonArray)
}
if let jsonT = self.MAINCONTROLLER.createJSONForRequest(["numResults":5,"ContextKeywords":jsons,"queryID":generateQueryID()],detail: false, pref: preferences){
print("Request:\n\(jsonT)\n")
self.MAINCONTROLLER.makeRequest(jsonT, detail: false)
}
}
private func generateQueryID()->String{
var queryID = ""
for char in recommendation.stringValue.utf8{
queryID += String(char)
}
return queryID
}
@IBAction func changeKeyContext(sender: NSButton) {
let isTopic:Bool?
if checkBoxIsMainTopic.state == NSOnState {
isTopic = true
}else{
isTopic = false
}
var keyValues:[String:AnyObject] = ["type":self.ComboBox_TypeOfKeyword.stringValue]
keyValues["isMainTopic"] = isTopic
for key in jsonKeys{
for subKey in key {
print("\(subKey.1)\n")
if subKey.0 == ComboBox_RequestKeywords.stringValue {
// jsonKeys[ComboBox_RequestKeywords.stringValue]!.setKeyValuePairs(keyValues)
subKey.1.setKeyValuePairs(keyValues)
}
}
}
for key in jsonKeys{
for subKey in key {
print("\(subKey)\n")
}
}
}
private func doSplit()
{
jsonKeys.removeAll()
var jsonArray = [String:JSONObject]()
var key = ""
if !recommendation.stringValue.hasSuffix(",") && !recommendation.stringValue.hasSuffix("|") && !recommendation.stringValue.isEmpty {
recommendation.stringValue += "|"
}
for c in recommendation.stringValue.characters{
if(c == ","){
// jsonKeys[key] = JSONObject(keyValuePairs: ["text":key])
jsonArray[key] = (JSONObject(keyValuePairs: ["text":key,"isMainTopic":false,"type":JSONManager.CONTEXT_KEYWORDS_MISC]))
key = ""
}else if c == "|" {
jsonArray[key] = (JSONObject(keyValuePairs: ["text":key,"isMainTopic":false,"type":JSONManager.CONTEXT_KEYWORDS_MISC]))
key = ""
self.jsonKeys.append(jsonArray)
jsonArray.removeAll()
}else{
key.append(c)
}
}
// self.jsonKeys.append(jsonArray)
self.ComboBox_RequestKeywords.removeAllItems()
for key in jsonKeys{
for subKey in key {
print("\(subKey.1)\n")
self.ComboBox_RequestKeywords.addItemWithObjectValue(subKey.0)
}
}
}
@IBAction func selectKeyWord(sender: NSComboBox) {
for key in jsonKeys{
for subKey in key {
print("\(subKey.1)\n")
if subKey.0 == ComboBox_RequestKeywords.stringValue {
// jsonKeys[ComboBox_RequestKeywords.stringValue]!.setKeyValuePairs(keyValues)
if (subKey.1.getBool("isMainTopic")!){
self.checkBoxIsMainTopic.state = 1
}else{
self.checkBoxIsMainTopic.state = 0
}
ComboBox_TypeOfKeyword.selectItemWithObjectValue(subKey.1.getString("type"))
}
}
}
}
// ---------------------------------------------------Detail-Request--------------------------
// action click on detail search
@IBAction func startSearchDetails(sender: AnyObject) {
print("--> Send details \n")
print("\n")
if let docBags = self.ComboBox_Detail.objectValueOfSelectedItem as? [String:AnyObject]{
if let json = self.MAINCONTROLLER.createJSONForRequest(["json":JSONObject(keyValuePairs: docBags)], detail: true, pref: preferences){
print("Detail Request:\n\(json)\n")
self.MAINCONTROLLER.makeRequest(json, detail: true)
}
}else{
if let json = self.MAINCONTROLLER.createJSONForRequest(["json":MAINCONTROLLER.seperateDocumentBages(MAINCONTROLLER.getFirstItem())], detail: true, pref:preferences){
print("Detail Request:\n\(json)\n")
self.MAINCONTROLLER.makeRequest(json, detail: true)
}
}
}
}
| 38.508065 | 179 | 0.585759 |
72237da40a635a416e5d714326f9528fc17b0e56 | 1,657 | // Copyright (c) 2019 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 MobiusCore
public typealias AssertFirst<Model, Effect> = (First<Model, Effect>) -> Void
public final class InitSpec<Model, Effect> {
let initiator: Initiator<Model, Effect>
public init(_ initiator: @escaping Initiator<Model, Effect>) {
self.initiator = initiator
}
public func when(_ model: Model) -> Then {
return Then(model, initiator: initiator)
}
public struct Then {
let model: Model
let initiator: Initiator<Model, Effect>
public init(_ model: Model, initiator: @escaping Initiator<Model, Effect>) {
self.model = model
self.initiator = initiator
}
public func then(_ assertion: AssertFirst<Model, Effect>) {
let first = initiator(model)
assertion(first)
}
}
}
| 33.14 | 84 | 0.687387 |
efc419a8b21935fafb40d9d3e371764a10fce331 | 16,207 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t -enable-library-evolution %S/Inputs/property_wrapper_defs.swift
// RUN: %target-swift-emit-silgen -primary-file %s -I %t | %FileCheck %s
import property_wrapper_defs
@propertyWrapper
struct Wrapper<T> {
var wrappedValue: T
init(value: T) {
wrappedValue = value
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
}
protocol DefaultInit {
init()
}
extension Int: DefaultInit { }
struct HasMemberwiseInit<T: DefaultInit> {
@Wrapper(value: false)
var x: Bool
@WrapperWithInitialValue
var y: T = T()
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
}
func forceHasMemberwiseInit() {
_ = HasMemberwiseInit(x: Wrapper(value: true), y: 17, z: WrapperWithInitialValue(wrappedValue: 42))
_ = HasMemberwiseInit<Int>(x: Wrapper(value: true))
_ = HasMemberwiseInit(y: 17)
_ = HasMemberwiseInit<Int>(z: WrapperWithInitialValue(wrappedValue: 42))
_ = HasMemberwiseInit<Int>()
}
// CHECK: sil_global private @$s17property_wrappers9UseStaticV13_staticWibble33_{{.*}}AA4LazyOySaySiGGvpZ : $Lazy<Array<Int>>
// HasMemberwiseInit.x.setter
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1xSbvs : $@convention(method) <T where T : DefaultInit> (Bool, @inout HasMemberwiseInit<T>) -> () {
// CHECK: bb0(%0 : $Bool, %1 : $*HasMemberwiseInit<T>):
// CHECK: [[MODIFY_SELF:%.*]] = begin_access [modify] [unknown] %1 : $*HasMemberwiseInit<T>
// CHECK: [[X_BACKING:%.*]] = struct_element_addr [[MODIFY_SELF]] : $*HasMemberwiseInit<T>, #HasMemberwiseInit._x
// CHECK: [[X_BACKING_VALUE:%.*]] = struct_element_addr [[X_BACKING]] : $*Wrapper<Bool>, #Wrapper.wrappedValue
// CHECK: assign %0 to [[X_BACKING_VALUE]] : $*Bool
// CHECK: end_access [[MODIFY_SELF]] : $*HasMemberwiseInit<T>
// variable initialization expression of HasMemberwiseInit._x
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_x33_{{.*}}AA7WrapperVySbGvpfi : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool> {
// CHECK: integer_literal $Builtin.Int1, 0
// CHECK-NOT: return
// CHECK: function_ref @$sSb22_builtinBooleanLiteralSbBi1__tcfC : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers7WrapperV5valueACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0> // user: %9
// CHECK: return {{%.*}} : $Wrapper<Bool>
// variable initialization expression of HasMemberwiseInit.$y
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_y33_{{.*}}23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <T where T : DefaultInit> () -> @out
// CHECK: bb0(%0 : $*T):
// CHECK-NOT: return
// CHECK: witness_method $T, #DefaultInit.init!allocator.1 : <Self where Self : DefaultInit> (Self.Type) -> () -> Self : $@convention(witness_method: DefaultInit) <τ_0_0 where τ_0_0 : DefaultInit> (@thick τ_0_0.Type) -> @out τ_0_0
// variable initialization expression of HasMemberwiseInit._z
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_z33_{{.*}}23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> {
// CHECK: bb0:
// CHECK-NOT: return
// CHECK: integer_literal $Builtin.IntLiteral, 17
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07wrappedF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0>
// default argument 0 of HasMemberwiseInit.init(x:y:z:)
// CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA_ : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool>
// default argument 1 of HasMemberwiseInit.init(x:y:z:)
// CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA0_ : $@convention(thin) <T where T : DefaultInit> () -> @out T {
// default argument 2 of HasMemberwiseInit.init(x:y:z:)
// CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA1_ : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> {
// HasMemberwiseInit.init()
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitVACyxGycfC : $@convention(method) <T where T : DefaultInit> (@thin HasMemberwiseInit<T>.Type) -> @out HasMemberwiseInit<T> {
// Initialization of x
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_x33_{{.*}}7WrapperVySbGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> Wrapper<Bool>
// Initialization of y
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_y33_{{.*}}23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> @out τ_0_0
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07wrappedF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0>
// Initialization of z
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_z33_{{.*}}23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> WrapperWithInitialValue<Int>
// CHECK: return
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers9HasNestedV2_y33_{{.*}}14PrivateWrapperAELLVyx_SayxGGvpfi : $@convention(thin) <T> () -> @owned Array<T> {
// CHECK: bb0:
// CHECK: function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
struct HasNested<T> {
@propertyWrapper
private struct PrivateWrapper<U> {
var wrappedValue: U
}
@PrivateWrapper
private var y: [T] = []
static func blah(y: [T]) -> HasNested<T> {
return HasNested<T>()
}
}
// FIXME: For now, we are only checking that we don't crash.
struct HasDefaultInit {
@Wrapper(value: true)
var x
@WrapperWithInitialValue
var y = 25
static func defaultInit() -> HasDefaultInit {
return HasDefaultInit()
}
static func memberwiseInit(x: Bool, y: Int) -> HasDefaultInit {
return HasDefaultInit(x: Wrapper(value: x), y: y)
}
}
struct WrapperWithAccessors {
@Wrapper
var x: Int
// Synthesized setter
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers20WrapperWithAccessorsV1xSivs : $@convention(method) (Int, @inout WrapperWithAccessors) -> ()
// CHECK-NOT: return
// CHECK: struct_element_addr {{%.*}} : $*WrapperWithAccessors, #WrapperWithAccessors._x
mutating func test() {
x = 17
}
}
func consumeOldValue(_: Int) { }
func consumeNewValue(_: Int) { }
struct WrapperWithDidSetWillSet {
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivs
// CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivw
// CHECK: struct_element_addr {{%.*}} : $*WrapperWithDidSetWillSet, #WrapperWithDidSetWillSet._x
// CHECK-NEXT: struct_element_addr {{%.*}} : $*Wrapper<Int>, #Wrapper.wrappedValue
// CHECK-NEXT: assign %0 to {{%.*}} : $*Int
// CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivW
@Wrapper
var x: Int {
didSet {
consumeNewValue(oldValue)
}
willSet {
consumeOldValue(newValue)
}
}
mutating func test(x: Int) {
self.x = x
}
}
@propertyWrapper
struct WrapperWithStorageValue<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(value: wrappedValue)
}
}
struct UseWrapperWithStorageValue {
// UseWrapperWithStorageValue._x.getter
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers26UseWrapperWithStorageValueV2$xAA0D0VySiGvg : $@convention(method) (UseWrapperWithStorageValue) -> Wrapper<Int>
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers23WrapperWithStorageValueV09projectedF0AA0C0VyxGvg
@WrapperWithStorageValue(wrappedValue: 17) var x: Int
}
@propertyWrapper
enum Lazy<Value> {
case uninitialized(() -> Value)
case initialized(Value)
init(wrappedValue initialValue: @autoclosure @escaping () -> Value) {
self = .uninitialized(initialValue)
}
var wrappedValue: Value {
mutating get {
switch self {
case .uninitialized(let initializer):
let value = initializer()
self = .initialized(value)
return value
case .initialized(let value):
return value
}
}
set {
self = .initialized(newValue)
}
}
}
struct UseLazy<T: DefaultInit> {
@Lazy var foo = 17
@Lazy var bar = T()
@Lazy var wibble = [1, 2, 3]
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers7UseLazyV3foo3bar6wibbleACyxGSi_xSaySiGtcfC : $@convention(method) <T where T : DefaultInit> (Int, @in T, @owned Array<Int>, @thin UseLazy<T>.Type) -> @out UseLazy<T>
// CHECK: function_ref @$s17property_wrappers7UseLazyV4_foo33_{{.*}}AA0D0OySiGvpfiSiycfu_ : $@convention(thin) (@owned Int) -> Int
// CHECK: function_ref @$s17property_wrappers4LazyO12wrappedValueACyxGxyXA_tcfC : $@convention(method) <τ_0_0> (@owned @callee_guaranteed () -> @out τ_0_0, @thin Lazy<τ_0_0>.Type) -> @out Lazy<τ_0_0>
}
struct X { }
func triggerUseLazy() {
_ = UseLazy<Int>()
_ = UseLazy<Int>(foo: 17)
_ = UseLazy(bar: 17)
_ = UseLazy<Int>(wibble: [1, 2, 3])
}
struct UseStatic {
// CHECK: sil hidden [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvgZ
// CHECK: sil private [global_init] [ossa] @$s17property_wrappers9UseStaticV13_staticWibble33_{{.*}}4LazyOySaySiGGvau
// CHECK: sil hidden [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvsZ
@Lazy static var staticWibble = [1, 2, 3]
}
extension WrapperWithInitialValue {
func test() { }
}
class ClassUsingWrapper {
@WrapperWithInitialValue var x = 0
}
extension ClassUsingWrapper {
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17ClassUsingWrapperC04testcdE01cyAC_tF : $@convention(method) (@guaranteed ClassUsingWrapper, @guaranteed ClassUsingWrapper) -> () {
func testClassUsingWrapper(c: ClassUsingWrapper) {
// CHECK: ref_element_addr %1 : $ClassUsingWrapper, #ClassUsingWrapper._x
self._x.test()
}
}
//
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var storage: T?
init() {
self.storage = nil
}
init(wrappedValue initialValue: T) {
self.storage = initialValue
}
var wrappedValue: T {
get { return storage! }
set { storage = newValue }
}
}
class UseWrapperWithDefaultInit {
@WrapperWithDefaultInit var name: String
}
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers25UseWrapperWithDefaultInitC5_name33_F728088E0028E14D18C6A10CF68512E8LLAA0defG0VySSGvpfi : $@convention(thin) () -> @owned WrapperWithDefaultInit<String>
// CHECK: function_ref @$s17property_wrappers22WrapperWithDefaultInitVACyxGycfC
// CHECK: return {{%.*}} : $WrapperWithDefaultInit<String>
// Property wrapper composition.
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
}
@propertyWrapper
struct WrapperC<Value> {
var wrappedValue: Value?
}
/* TODO: Reenable composed property wrappers
struct CompositionMembers {
// CompositionMembers.p1.getter
// C/HECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p1SiSgvg : $@convention(method) (@guaranteed CompositionMembers) -> Optional<Int>
// C/HECK: bb0([[SELF:%.*]] : @guaranteed $CompositionMembers):
// C/HECK: [[P1:%.*]] = struct_extract [[SELF]] : $CompositionMembers, #CompositionMembers._p1
// C/HECK: [[P1_VALUE:%.*]] = struct_extract [[P1]] : $WrapperA<WrapperB<WrapperC<Int>>>, #WrapperA.wrappedValue
// C/HECK: [[P1_VALUE2:%.*]] = struct_extract [[P1_VALUE]] : $WrapperB<WrapperC<Int>>, #WrapperB.wrappedValue
// C/HECK: [[P1_VALUE3:%.*]] = struct_extract [[P1_VALUE2]] : $WrapperC<Int>, #WrapperC.wrappedValue
// C/HECK: return [[P1_VALUE3]] : $Optional<Int>
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
// variable initialization expression of CompositionMembers.$p2
// C/HECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers18CompositionMembersV3_p233_{{.*}}8WrapperAVyAA0N1BVyAA0N1CVySSGGGvpfi : $@convention(thin) () -> @owned Optional<String> {
// C/HECK: %0 = string_literal utf8 "Hello"
// C/HECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p12p2ACSiSg_SSSgtcfC : $@convention(method) (Optional<Int>, @owned Optional<String>, @thin CompositionMembers.Type) -> @owned CompositionMembers
// C/HECK: function_ref @$s17property_wrappers8WrapperCV12wrappedValueACyxGxSg_tcfC
// C/HECK: function_ref @$s17property_wrappers8WrapperBV12wrappedValueACyxGx_tcfC
// C/HECK: function_ref @$s17property_wrappers8WrapperAV12wrappedValueACyxGx_tcfC
}
func testComposition() {
_ = CompositionMembers(p1: nil)
}
*/
// Observers with non-default mutatingness.
@propertyWrapper
struct NonMutatingSet<T> {
private var fixed: T
var wrappedValue: T {
get { fixed }
nonmutating set { }
}
init(wrappedValue initialValue: T) {
fixed = initialValue
}
}
@propertyWrapper
struct MutatingGet<T> {
private var fixed: T
var wrappedValue: T {
mutating get { fixed }
set { }
}
init(wrappedValue initialValue: T) {
fixed = initialValue
}
}
struct ObservingTest {
// ObservingTest.text.setter
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers13ObservingTestV4textSSvs : $@convention(method) (@owned String, @guaranteed ObservingTest) -> ()
// CHECK: function_ref @$s17property_wrappers14NonMutatingSetV12wrappedValuexvg
@NonMutatingSet var text: String = "" {
didSet { }
}
@NonMutatingSet var integer: Int = 17 {
willSet { }
}
@MutatingGet var text2: String = "" {
didSet { }
}
@MutatingGet var integer2: Int = 17 {
willSet { }
}
}
// Tuple initial values.
struct WithTuples {
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers10WithTuplesVACycfC : $@convention(method) (@thin WithTuples.Type) -> WithTuples {
// CHECK: function_ref @$s17property_wrappers10WithTuplesV10_fractions33_F728088E0028E14D18C6A10CF68512E8LLAA07WrapperC12InitialValueVySd_S2dtGvpfi : $@convention(thin) () -> (Double, Double, Double)
// CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07wrappedF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0>
@WrapperWithInitialValue var fractions = (1.3, 0.7, 0.3)
static func getDefault() -> WithTuples {
return .init()
}
}
// Resilience with DI of wrapperValue assignments.
// rdar://problem/52467175
class TestResilientDI {
@MyPublished var data: Int? = nil
// CHECK: assign_by_wrapper {{%.*}} : $Optional<Int> to {{%.*}} : $*MyPublished<Optional<Int>>, init {{%.*}} : $@callee_guaranteed (Optional<Int>) -> @out MyPublished<Optional<Int>>, set {{%.*}} : $@callee_guaranteed (Optional<Int>) -> ()
func doSomething() {
self.data = Int()
}
}
// CHECK-LABEL: sil_vtable ClassUsingWrapper {
// CHECK-NEXT: #ClassUsingWrapper.x!getter.1: (ClassUsingWrapper) -> () -> Int : @$s17property_wrappers17ClassUsingWrapperC1xSivg // ClassUsingWrapper.x.getter
// CHECK-NEXT: #ClassUsingWrapper.x!setter.1: (ClassUsingWrapper) -> (Int) -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivs // ClassUsingWrapper.x.setter
// CHECK-NEXT: #ClassUsingWrapper.x!modify.1: (ClassUsingWrapper) -> () -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivM // ClassUsingWrapper.x.modify
// CHECK-NEXT: #ClassUsingWrapper.init!allocator.1: (ClassUsingWrapper.Type) -> () -> ClassUsingWrapper : @$s17property_wrappers17ClassUsingWrapperCACycfC
// CHECK-NEXT: #ClassUsingWrapper.deinit!deallocator.1: @$s17property_wrappers17ClassUsingWrapperCfD
// CHECK-NEXT: }
| 38.405213 | 239 | 0.731412 |
4bd35655bc990f238795cdb5e1a3831b7b69bbff | 3,753 | // HomeViewController.swift
// Auth0Sample
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// 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
import Auth0
class HomeViewController: UIViewController {
private var isAuthenticated = false
// MARK: - IBAction
@IBAction func showLoginController(_ sender: UIButton) {
guard let clientInfo = plistValues(bundle: Bundle.main) else { return }
if(!isAuthenticated){
Auth0
.webAuth()
.scope("openid profile")
.audience("https://" + clientInfo.domain + "/userinfo")
.start {
switch $0 {
case .failure(let error):
print("Error: \(error)")
case .success(let credentials):
guard let accessToken = credentials.accessToken else { return }
self.showSuccessAlert("accessToken: \(accessToken)")
self.isAuthenticated = true
sender.setTitle("Log out", for: .normal)
}
}
}
else{
Auth0
.webAuth()
.clearSession(federated:false){
switch $0{
case true:
sender.setTitle("Log in", for: .normal)
self.isAuthenticated = false
case false:
self.showSuccessAlert("An error occurred")
}
}
}
}
// MARK: - Private
fileprivate func showSuccessAlert(_ message: String) {
let alert = UIAlertController(title: "Message", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func plistValues(bundle: Bundle) -> (clientId: String, domain: String)? {
guard
let path = bundle.path(forResource: "Auth0", ofType: "plist"),
let values = NSDictionary(contentsOfFile: path) as? [String: Any]
else {
print("Missing Auth0.plist file with 'ClientId' and 'Domain' entries in main bundle!")
return nil
}
guard
let clientId = values["ClientId"] as? String,
let domain = values["Domain"] as? String
else {
print("Auth0.plist file at \(path) is missing 'ClientId' and/or 'Domain' entries!")
print("File currently has the following entries: \(values)")
return nil
}
return (clientId: clientId, domain: domain)
}
| 39.925532 | 98 | 0.59206 |
0a1205f2c8b72508c9ce87bb48489675338ec9ed | 4,623 | //
// IndexRequestHandler.swift
// Spotlight
//
// Created by Joseph Mattiello on 2/12/18.
// Copyright © 2018 James Addyman. All rights reserved.
//
import CoreSpotlight
import CoreServices
import PVLibrary
import PVSupport
import RealmSwift
public enum SpotlightError: Error {
case appGroupsNotSupported
case dontHandleDatatype
case notFound
}
public final class IndexRequestHandler: CSIndexExtensionRequestHandler {
public override init() {
super.init()
if RealmConfiguration.supportsAppGroups {
RealmConfiguration.setDefaultRealmConfig()
}
}
public override func searchableIndex(_: CSSearchableIndex, reindexAllSearchableItemsWithAcknowledgementHandler acknowledgementHandler: @escaping () -> Void) {
if RealmConfiguration.supportsAppGroups {
let database = RomDatabase.sharedInstance
let allGames = database.all(PVGame.self)
indexResults(allGames)
} else {
WLOG("App Groups not setup")
}
acknowledgementHandler()
}
public override func searchableIndex(_: CSSearchableIndex, reindexSearchableItemsWithIdentifiers identifiers: [String], acknowledgementHandler: @escaping () -> Void) {
// Reindex any items with the given identifiers and the provided index
if RealmConfiguration.supportsAppGroups {
let database = RomDatabase.sharedInstance
let allGamesMatching = database.all(PVGame.self, filter: NSPredicate(format: "md5Hash IN %@", identifiers))
indexResults(allGamesMatching)
} else {
WLOG("App Groups not setup")
}
acknowledgementHandler()
}
// public override func data(for searchableIndex: CSSearchableIndex, itemIdentifier: String, typeIdentifier: String) throws -> Data {
// if !RealmConfiguration.supportsAppGroups {
// throw SpotlightError.appGroupsNotSupported
// }
// Could make a scaled image too and supply the data
// if let p = pathOfCachedImage?.path, let t = UIImage(contentsOfFile: p), let s = t.scaledImage(withMaxResolution: 270) {
//
// if typeIdentifier == (kUTTypeImage as String) {
// do {
// let url = try fileURL(for: searchableIndex, itemIdentifier: itemIdentifier, typeIdentifier: typeIdentifier, inPlace: true)
// return try Data(contentsOf: url)
// } catch {
// throw error
// }
// } else {
// throw SpotlightError.dontHandleDatatype
// }
// }
public override func fileURL(for _: CSSearchableIndex, itemIdentifier: String, typeIdentifier: String, inPlace _: Bool) throws -> URL {
if !RealmConfiguration.supportsAppGroups {
throw SpotlightError.appGroupsNotSupported
}
// We're assuming the typeIndentifier is the game one since that's all we've been using so far
// I think it's looking for the image path
if typeIdentifier == (kUTTypeImage as String) {
let md5 = itemIdentifier.components(separatedBy: ".").last ?? ""
if let game = RomDatabase.sharedInstance.realm.object(ofType: PVGame.self, forPrimaryKey: md5), let artworkURL = game.pathOfCachedImage {
return artworkURL
} else {
throw SpotlightError.notFound
}
} else {
throw SpotlightError.dontHandleDatatype
}
}
private func indexResults(_ results: Results<PVGame>) {
#if swift(>=4.1)
let items: [CSSearchableItem] = results.compactMap({ (game) -> CSSearchableItem? in
if !game.md5Hash.isEmpty {
return CSSearchableItem(uniqueIdentifier: "com.provenance-emu.game.\(game.md5Hash)", domainIdentifier: "com.provenance-emu.game", attributeSet: game.spotlightContentSet)
} else {
return nil
}
})
#else
let items: [CSSearchableItem] = results.flatMap({ (game) -> CSSearchableItem? in
if !game.md5Hash.isEmpty {
return CSSearchableItem(uniqueIdentifier: "com.provenance-emu.game.\(game.md5Hash)", domainIdentifier: "com.provenance-emu.game", attributeSet: game.spotlightContentSet)
} else {
return nil
}
})
#endif
CSSearchableIndex.default().indexSearchableItems(items) { error in
if let error = error {
ELOG("indexing error: \(error)")
}
}
}
}
| 37.282258 | 189 | 0.628596 |
1c1c7090c6005a49f686dda8d17508ba7afc5252 | 1,574 | //
// Bullet.swift
// ARViewer
//
// Created by Faris Sbahi on 6/6/17.
// Copyright © 2017 Faris Sbahi. All rights reserved.
//
import UIKit
import SceneKit
// Spheres that are shot at the "ships"
class Bullet: SCNNode {
var image: UIImage?
init(geometry: SCNGeometry) {
super.init()
self.geometry = geometry
// self.image = UIImage(named: String(describing: self.geometry))!
setBullet()
}
override init () {
super.init()
// let sphere = SCNSphere(radius: 0.025)
self.geometry = SCNBox(width: 0.025, height: 0.025, length: 0.025, chamferRadius: 0.0)
// self.image = UIImage(named:String(describing: self.geometry))!
setBullet()
}
func setBullet() {
let shape = SCNPhysicsShape(geometry: self.geometry!, options: nil)
self.physicsBody = SCNPhysicsBody(type: .dynamic, shape: shape)
self.physicsBody?.isAffectedByGravity = false
// see http://texnotes.me/post/5/ for details on collisions and bit masks
self.physicsBody?.categoryBitMask = CollisionCategory.bullets.rawValue
self.physicsBody?.contactTestBitMask = CollisionCategory.ship.rawValue
// add texture
let material = SCNMaterial()
material.diffuse.contents = UIImage(named: "bullet_texture")
self.geometry?.materials = [material]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 28.107143 | 94 | 0.613088 |
2233a1cbbe38460a61d806d59c80c0a3eca84e5c | 484 | //
// BetaBuildLocalizationResponse.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 12/11/2018.
//
import Foundation
/// A response containing a single resource.
public struct BetaBuildLocalizationResponse: Codable {
/// The resource data.
public let data: BetaBuildLocalization
/// The requested relationship data.
public let included: [Build]?
/// Navigational links that include the self-link.
public let links: DocumentLinks
}
| 22 | 54 | 0.725207 |
e5c72c9afd1df5048838841075745f18662254a4 | 3,261 | //
// LocalizationTeamViewController.swift
// BattleBuddy
//
// Created by Mike on 8/28/19.
// Copyright © 2019 Veritas. All rights reserved.
//
import UIKit
struct LanguageTeam {
let languageCodes: [String]
let members: [String]
}
class LocalizationTeamViewController: BaseTableViewController {
lazy var teams: [LanguageTeam] = {
return [
LanguageTeam(languageCodes: ["no"], members: ["Vegard Kjølås"]),
LanguageTeam(languageCodes: ["nl"], members: ["Robinblitz"]),
LanguageTeam(languageCodes: ["ru"], members: ["JackWithMeat", "Danila \"Danilablond\"", "Anatoly \"Nagodre\" Kotov", "Alexey Byron"]),
LanguageTeam(languageCodes: ["it"], members: ["Adriano Crippa"]),
LanguageTeam(languageCodes: ["sv"], members: ["Octane", "Scout Commando Prox"]),
LanguageTeam(languageCodes: ["es_es"], members: ["Hugo Gómez"]),
LanguageTeam(languageCodes: ["sr", "hr"], members: ["ANDstriker"]),
LanguageTeam(languageCodes: ["ro"], members: ["FreeSpy443", "Glupin_Blupin"]),
LanguageTeam(languageCodes: ["lt"], members: ["Rokas \"Alacrino\" Juodelis"]),
LanguageTeam(languageCodes: ["pl"], members: ["hot gamer girl, Emin3X"]),
LanguageTeam(languageCodes: ["de"], members: ["Nico \"Desteny\"", "PaaX", "Keks / McKnopp"]),
LanguageTeam(languageCodes: ["fr"], members: ["Jean-Michel Fiché S"]),
LanguageTeam(languageCodes: ["es_419"], members: ["Rusty"]),
LanguageTeam(languageCodes: ["pt_pt"], members: ["Joel Fernandes \"jel\""]),
LanguageTeam(languageCodes: ["pt_br"], members: ["Spuritika", "Sir_Tai"]),
LanguageTeam(languageCodes: ["hu"], members: ["Patkosi"]),
LanguageTeam(languageCodes: ["cs"], members: ["Frren"]),
LanguageTeam(languageCodes: ["zh-hk"], members: ["jasonlin12356789", "Allen Chang"])
]
}()
required init?(coder aDecoder: NSCoder) { fatalError() }
init() {
super.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
title = "attributions_translations".local()
tableView.rowHeight = UITableView.automaticDimension
tableView.tableFooterView = UIView()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let codes = teams[section].languageCodes
return codes.compactMap { Locale.autoupdatingCurrent.localizedString(forLanguageCode: $0) }.joined(separator: ", ")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return teams.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return teams[section].members.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NameCell") as? BaseTableViewCell ?? BaseTableViewCell(style: .default, reuseIdentifier: "NameCell")
cell.textLabel?.text = teams[indexPath.section].members[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
| 43.48 | 165 | 0.645508 |
d51580de0fd6260ce1f2657b7ecfd99013197c70 | 3,743 | //
// MultilineInputTableViewCell.swift
// Lumenshine
//
// Created by Soneso GmbH on 12/12/2018.
// Munich, Germany
// web: https://soneso.com
// email: [email protected]
// Copyright © 2018 Soneso. All rights reserved.
//
import UIKit
import Material
class MultilineInputTableViewCell: InputTableViewCell {
// MARK: - Parameters & Constants
override class var CellIdentifier: String {
return "MultilineInputDataCell"
}
// MARK: - Properties
fileprivate let horizontalSpacing: CGFloat = 15.0
fileprivate let textView = UITextView()
fileprivate let separator = UIView()
fileprivate var placeholder: String?
var cellSizeChangedCallback: ((_ size:CGFloat) -> ())?
override func prepareForReuse() {
super.prepareForReuse()
cellSizeChangedCallback = nil
}
override func commonInit() {
selectionStyle = .none
backgroundColor = .clear
contentView.backgroundColor = Stylesheet.color(.white)
textView.autocapitalizationType = .none
textView.autocorrectionType = .no
textView.delegate = self
textView.isScrollEnabled = false
textView.font = R.font.encodeSansSemiBold(size: 14)
textView.textColor = Stylesheet.color(.lightBlack)
textView.tintColor = Stylesheet.color(.lightBlack)
textView.textContainerInset = UIEdgeInsets(top: 0, left: -5, bottom: 2, right: 0)
contentView.addSubview(textView)
textView.snp.makeConstraints { (make) in
make.top.equalTo(horizontalSpacing)
make.left.equalTo(horizontalSpacing)
make.right.equalTo(-horizontalSpacing)
make.bottom.equalTo(-horizontalSpacing)
}
separator.borderColor = Stylesheet.color(.lightGray)
separator.borderWidthPreset = .border1
contentView.addSubview(separator)
separator.snp.makeConstraints { make in
make.height.equalTo(1)
make.left.equalTo(horizontalSpacing)
make.right.equalTo(-horizontalSpacing)
make.top.equalTo(textView.snp.bottom)
}
}
override func setPlaceholder(_ placeholder: String?) {
self.placeholder = placeholder
if textView.text.isEmpty {
textView.text = placeholder
}
}
override func setText(_ text: String?) {
textView.text = text
textView.sizeToFit()
cellSizeChangedCallback?(textView.newHeight(withBaseHeight: 25))
}
}
extension MultilineInputTableViewCell: UITextViewDelegate {
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
guard let callback = shouldBeginEditingCallback else {
return true
}
return callback()
}
func textViewDidChange(_ textView: UITextView) {
textEditingCallback?(textView.text)
cellSizeChangedCallback?(textView.newHeight(withBaseHeight: 25))
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == placeholder {
textView.text = ""
}
separator.borderColor = Stylesheet.color(.gray)
separator.borderWidthPreset = .border3
separator.snp.updateConstraints { make in
make.height.equalTo(2)
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = placeholder
}
separator.borderColor = Stylesheet.color(.lightGray)
separator.borderWidthPreset = .border1
separator.snp.updateConstraints { make in
make.height.equalTo(1)
}
}
}
| 30.430894 | 89 | 0.636388 |
eb14f1fc2c5949fc9fbe5fa56f007e22b8b8f022 | 892 | //
// Spatial.swift
// Pods
//
// Created by Lim, Jennifer on 1/6/17.
//
//
//
/// Spatial stores all information related to threesixty video
public class Spatial: VIMModelObject {
@objc public static let StereoFormatMono = "mono"
@objc public static let StereoFormatLeftRight = "left-right"
@objc public static let StereoFormatTopBottom = "top-bottom"
/// Represents the projection. Value returned by the server can be: "equirectangular", "cylindrical", "cubical", "pyramid", "dome".
@objc dynamic public private(set) var projection: String?
/// Represents the format. Value returned by the server can be: "mono", "left-right", "top-bottom"
@objc dynamic public private(set) var stereoFormat: String?
// MARK: - VIMMappable
public override func getObjectMapping() -> Any {
return ["stereo_format" : "stereoFormat"]
}
}
| 31.857143 | 135 | 0.678251 |
33cb48f47866efb0f9a6c1c5901f34f6a9bcdda2 | 2,172 | //
// UIWindow+Shake.swift
// IssueReporter
//
// Created by Hakon Hanesand on 10/6/16.
// Copyright © 2017 abello. All rights reserved.
//
//
import Foundation
import UIKit
internal extension Notification.Name {
static let onWindowShake = Notification.Name("shakeyshakey")
}
internal extension UIWindow {
internal static var _onceTracker = [String]()
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
internal class func once(token: String, block: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
internal class func swizzleMotionEnded() {
UIWindow.once(token: "swizzleMotionEnded") {
let originalSelector = #selector(UIWindow.motionEnded(_:with:))
let swizzledSelector = #selector(UIWindow.abe_motionEnded(_:with:))
let originalMethod = class_getInstanceMethod(UIWindow.self, originalSelector)
let swizzledMethod = class_getInstanceMethod(UIWindow.self, swizzledSelector)
let didAddMethod = class_addMethod(UIWindow.self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(UIWindow.self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
}
@objc internal func abe_motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if let event = event, event.type == .motion, event.subtype == .motionShake {
NotificationCenter.default.post(name: .onWindowShake, object: self)
}
}
}
| 32.909091 | 163 | 0.678637 |
1c0eedb692704005c80774d9049ee622993f1ba0 | 6,264 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The view controller shown to select an ice-cream part for a partially built ice cream.
*/
import UIKit
class BuildIceCreamViewController: UIViewController {
// MARK: Properties
static let storyboardIdentifier = "BuildIceCreamViewController"
weak var delegate: BuildIceCreamViewControllerDelegate?
var iceCream: IceCream? {
didSet {
guard let iceCream = iceCream else { return }
// Determine the ice cream parts to show in the collection view.
if iceCream.base == nil {
iceCreamParts = Base.all.map { $0 }
prompt = NSLocalizedString("Select a base", comment: "")
}
else if iceCream.scoops == nil {
iceCreamParts = Scoops.all.map { $0 }
prompt = NSLocalizedString("Add some scoops", comment: "")
}
else if iceCream.topping == nil {
iceCreamParts = Topping.all.map { $0 }
prompt = NSLocalizedString("Finish with a topping", comment: "")
}
}
}
/// An array of `IceCreamPart`s to show in the collection view.
var iceCreamParts = [IceCreamPart]() {
didSet {
// Update the collection view to show the new ice cream parts.
guard isViewLoaded else { return }
collectionView.reloadData()
}
}
var prompt: String?
@IBOutlet weak var promptLabel: UILabel!
@IBOutlet weak var iceCreamView: IceCreamView!
@IBOutlet weak var iceCreamViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Make sure the prompt and ice cream view are showing the correct information.
promptLabel.text = prompt
iceCreamView.iceCream = iceCream
/*
We want the collection view to decelerate faster than normal so comes
to rests on a body part more quickly.
*/
collectionView.decelerationRate = UIScrollViewDecelerationRateFast
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// There is nothing to layout of there are no ice cream parts to pick from.
guard !iceCreamParts.isEmpty else { return }
guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { fatalError("Expected the collection view to have a UICollectionViewFlowLayout") }
// The ideal cell width is 1/3 of the width of the collection view.
layout.itemSize.width = floor(view.bounds.size.width / 3.0)
// Set the cell height using the aspect ratio of the ice cream part images.
let iceCreamPartImageSize = iceCreamParts[0].image.size
guard iceCreamPartImageSize.width > 0 else { return }
let imageAspectRatio = iceCreamPartImageSize.width / iceCreamPartImageSize.height
layout.itemSize.height = floor(layout.itemSize.width / imageAspectRatio)
// Set the collection view's height constraint to match the cell size.
collectionViewHeightConstraint.constant = layout.itemSize.height
// Adjust the collection view's `contentInset` so the first item is centered.
var contentInset = collectionView.contentInset
contentInset.left = (view.bounds.size.width - layout.itemSize.width) / 2.0
contentInset.right = contentInset.left
collectionView.contentInset = contentInset
// Calculate the ideal height of the ice cream view.
let iceCreamViewContentHeight = iceCreamView.arrangedSubviews.reduce(0.0) { total, arrangedSubview in
return total + arrangedSubview.intrinsicContentSize.height
}
let iceCreamPartImageScale = layout.itemSize.height / iceCreamPartImageSize.height
iceCreamViewHeightConstraint.constant = floor(iceCreamViewContentHeight * iceCreamPartImageScale)
}
// MARK: Interface Builder actions
@IBAction func didTapSelect(_: AnyObject) {
// Determine the index path of the centered cell in the collection view.
guard let layout = collectionView.collectionViewLayout as? IceCreamPartCollectionViewLayout else { fatalError("Expected the collection view to have a IceCreamPartCollectionViewLayout") }
let halfWidth = collectionView.bounds.size.width / 2.0
guard let indexPath = layout.indexPathForVisibleItemClosest(to: collectionView.contentOffset.x + halfWidth) else { return }
// Call the delegate with the body part for the centered cell.
delegate?.buildIceCreamViewController(self, didSelect: iceCreamParts[indexPath.row])
}
}
/**
A delegate protocol for the `BuildIceCreamViewController` class.
*/
protocol BuildIceCreamViewControllerDelegate: class {
/// Called when the user taps to select an `IceCreamPart` in the `BuildIceCreamViewController`.
func buildIceCreamViewController(_ controller: BuildIceCreamViewController, didSelect iceCreamPart: IceCreamPart)
}
/**
Extends `BuildIceCreamViewController` to conform to the `UICollectionViewDataSource`
protocol.
*/
extension BuildIceCreamViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return iceCreamParts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IceCreamPartCell.reuseIdentifier, for: indexPath as IndexPath) as? IceCreamPartCell else { fatalError("Unable to dequeue a BodyPartCell") }
let iceCreamPart = iceCreamParts[indexPath.row]
cell.imageView.image = iceCreamPart.image
return cell
}
}
| 40.675325 | 220 | 0.681992 |
ff2ff562d73f607bfa139da6936d301aef8ded08 | 8,136 | //
// GAPDataType.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/// Generic Access Profile Data Type
///
/// Assigned numbers are used in GAP for inquiry response, EIR data type values, manufacturer-specific data,
/// advertising data, low energy UUIDs and appearance characteristics, and class of device.
///
/// - SeeAlso:
/// [Generic Access Profile](https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile)
@frozen
public struct GAPDataType: RawRepresentable, Equatable, Hashable {
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
// MARK: - Defined Types
public extension GAPDataType {
/// Flags
///
/// **Reference**:
///
/// Bluetooth Core Specification Vol. 3, Part C, section 8.1.3 (v2.1 + EDR, 3.0 + HS and 4.0)
///
/// Bluetooth Core Specification Vol. 3, Part C, sections 11.1.3 and 18.1 (v4.0)
///
/// Core Specification Supplement, Part A, section 1.3
static let flags: GAPDataType = 0x01
/// Incomplete List of 16-bit Service Class UUIDs
static let incompleteListOf16BitServiceClassUUIDs: GAPDataType = 0x02
/// Complete List of 16-bit Service Class UUIDs
static let completeListOf16CitServiceClassUUIDs: GAPDataType = 0x03
/// Incomplete List of 32-bit Service Class UUIDs
static let incompleteListOf32BitServiceClassUUIDs: GAPDataType = 0x04
/// Complete List of 32-bit Service Class UUIDs
static let completeListOf32BitServiceClassUUIDs: GAPDataType = 0x05
/// Incomplete List of 128-bit Service Class UUIDs
static let incompleteListOf128BitServiceClassUUIDs: GAPDataType = 0x06
/// Complete List of 128-bit Service Class UUIDs
static let completeListOf128BitServiceClassUUIDs: GAPDataType = 0x07
/// Shortened Local Name
static let shortLocalName: GAPDataType = 0x08
/// Complete Local Name
static let completeLocalName: GAPDataType = 0x09
/// TX Power Level
static let txPowerLevel: GAPDataType = 0x0A
/// Class of Device
static let classOfDevice: GAPDataType = 0x0D
/// Simple Pairing Hash C
static let simplePairingHashC: GAPDataType = 0x0E
/// Simple Pairing Randomizer
static let simplePairingRandomizerR: GAPDataType = 0x0F
/// Security Manager TK Value
static let securityManagerTKValue: GAPDataType = 0x10
/// Security Manager Out of Band Flags
static let securityManagerOutOfBandFlags: GAPDataType = 0x11
/// Slave Connection Interval Range
static let slaveConnectionIntervalRange: GAPDataType = 0x12
/// List of 16-bit Service Solicitation UUIDs
static let listOf16BitServiceSolicitationUUIDs: GAPDataType = 0x14
/// List of 128-bit Service Solicitation UUIDs
static let listOf128BitServiceSolicitationUUIDs: GAPDataType = 0x15
/// Service Data - 16-bit UUID
static let serviceData16BitUUID: GAPDataType = 0x16
/// Public Target Address
static let publicTargetAddress: GAPDataType = 0x17
/// Random Target Address
static let randomTargetAddress: GAPDataType = 0x18
/// Appearance
static let appearance: GAPDataType = 0x19
/// Advertising Interval
static let advertisingInterval: GAPDataType = 0x1A
/// LE Bluetooth Device Address
static let lowEnergyDeviceAddress: GAPDataType = 0x1B
/// LE Role
static let lowEnergyRole: GAPDataType = 0x1C
/// Simple Pairing Hash C-256
static let simplePairingHashC256: GAPDataType = 0x1D
/// Simple Pairing Randomizer R-256
static let simplePairingRandomizerR256: GAPDataType = 0x1E
/// List of 32-bit Service Solicitation UUIDs
static let listOf32BitServiceSolicitationUUIDs: GAPDataType = 0x1F
/// Service Data - 32-bit UUID
static let serviceData32BitUUID: GAPDataType = 0x20
/// Service Data - 128-bit UUID
static let serviceData128BitUUID: GAPDataType = 0x21
/// LE Secure Connections Confirmation Value
static let lowEnergySecureConnectionsConfirmation: GAPDataType = 0x22
/// LE Secure Connections Random Value
static let lowEnergySecureConnectionsRandom: GAPDataType = 0x23
/// URI
static let uri: GAPDataType = 0x24
/// Indoor Positioning
static let indoorPositioning: GAPDataType = 0x25
/// Transport Discovery Data
static let transportDiscoveryData: GAPDataType = 0x26
/// LE Supported Features
static let lowEnergySupportedFeatures: GAPDataType = 0x27
/// Channel Map Update Indication
static let channelMapUpdateIndication: GAPDataType = 0x28
/// PB-ADV
static let pbAdv: GAPDataType = 0x29
/// Mesh Message
static let meshMessage: GAPDataType = 0x2A
/// Mesh Beacon
static let meshBeacon: GAPDataType = 0x2B
/// 3D Information Data
static let informationData3D: GAPDataType = 0x3D
/// Manufacturer Specific Data
static let manufacturerSpecificData: GAPDataType = 0xFF
}
// MARK: - ExpressibleByIntegerLiteral
extension GAPDataType: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt8) {
self.rawValue = value
}
}
// MARK: - CustomStringConvertible
extension GAPDataType: CustomStringConvertible {
public var name: String? {
return gapDataTypeNames[self]
}
public var description: String {
return name ?? "GAP Data Type (\(rawValue))"
}
}
/// Standard GAP Data Type names
internal let gapDataTypeNames: [GAPDataType: String] = [
.flags: "Flags",
.incompleteListOf16BitServiceClassUUIDs: "Incomplete List of 16-bit Service Class UUIDs",
.completeListOf16CitServiceClassUUIDs: "Complete List of 16-bit Service Class UUIDs",
.incompleteListOf32BitServiceClassUUIDs: "Incomplete List of 32-bit Service Class UUIDs",
.completeListOf32BitServiceClassUUIDs: "Complete List of 32-bit Service Class UUIDs",
.incompleteListOf128BitServiceClassUUIDs: "Incomplete List of 128-bit Service Class UUIDs",
.completeListOf128BitServiceClassUUIDs: "Complete List of 128-bit Service Class UUIDs",
.shortLocalName: "Shortened Local Name",
.completeLocalName: "Complete Local Name",
.txPowerLevel: "Tx Power Level",
.classOfDevice: "Class of Device",
.simplePairingHashC: "Simple Pairing Hash C",
.simplePairingRandomizerR: "Simple Pairing Randomizer R",
.securityManagerTKValue: "Security Manager TK Value",
.securityManagerOutOfBandFlags: "Security Manager Out of Band Flags",
.slaveConnectionIntervalRange: "Slave Connection Interval Range",
.listOf16BitServiceSolicitationUUIDs: "List of 16-bit Service Solicitation UUIDs",
.listOf32BitServiceSolicitationUUIDs: "List of 32-bit Service Solicitation UUIDs",
.listOf128BitServiceSolicitationUUIDs: "List of 128-bit Service Solicitation UUIDs",
.serviceData16BitUUID: "Service Data - 16-bit UUID",
.serviceData32BitUUID: "Service Data - 32-bit UUID",
.serviceData128BitUUID: "Service Data - 128-bit UUID",
.publicTargetAddress: "Public Target Address",
.randomTargetAddress: "Random Target Address",
.appearance: "Appearance",
.advertisingInterval: "Advertising Interval",
.lowEnergyDeviceAddress: "LE Bluetooth Device Address",
.lowEnergyRole: "LE Role",
.lowEnergySecureConnectionsConfirmation: "LE Secure Connections Confirmation Value",
.lowEnergySecureConnectionsRandom: "LE Secure Connections Random Value",
.uri: "URI",
.indoorPositioning: "Indoor Positioning",
.transportDiscoveryData: "Transport Discovery Data",
.lowEnergySupportedFeatures: "LE Supported Features",
.channelMapUpdateIndication: "Channel Map Update Indication",
.pbAdv: "PB-ADV",
.meshMessage: "Mesh Message",
.meshBeacon: "Mesh Beacon",
.informationData3D: "3D Information Data",
.manufacturerSpecificData: "Manufacturer Specific Data"
]
| 35.220779 | 110 | 0.71116 |
0ee22712a4dcda4fb5ab67ef86bc7cf7bf3b2bc4 | 2,988 | //
// JMLocationPermissionManager.swift
//
//
// Created by Jevon Mao on 1/31/21.
//
import Foundation
import MapKit
class JMLocationPermissionManager: NSObject, CLLocationManagerDelegate {
static var shared = JMLocationPermissionManager()
var locationManager: LocationManager
var completionHandler: JMPermissionAuthorizationHandlerCompletionBlock?
var locationPermissionType: LocationPermissionType?
enum LocationPermissionType {
case whenInUse
case always
}
init(locationManager:LocationManager = CLLocationManager()){
self.locationManager = locationManager
super.init()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .notDetermined {
return
}
if let completionHandler = completionHandler {
let status = CLLocationManager.authorizationStatus()
if self.locationPermissionType == .always {
completionHandler(status == .authorizedAlways ? true : false)
}
else {
completionHandler(status == .authorizedAlways || status == .authorizedWhenInUse ? true : false)
}
}
}
func requestAlwaysPermission(_ completionHandler: @escaping JMPermissionAuthorizationHandlerCompletionBlock) {
self.completionHandler = completionHandler
self.locationPermissionType = .always
var status:CLAuthorizationStatus{
locationManager.authorizationStatus()
}
switch status {
case .notDetermined:
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
case .authorizedWhenInUse:
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
default:
completionHandler(status == .authorizedAlways ? true : false)
}
}
func requestInUsePermission(_ completionHandler: @escaping JMPermissionAuthorizationHandlerCompletionBlock) {
self.completionHandler = completionHandler
self.locationPermissionType = .whenInUse
let status = CLLocationManager.authorizationStatus()
switch status {
case .notDetermined:
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
default:
completionHandler(status == .authorizedWhenInUse || status == .authorizedAlways ? true : false)
}
}
// var isAuthorized: Bool {
// let status = CLLocationManager.authorizationStatus()
// if status == .authorizedAlways {
// return true
// }
// return false
// }
deinit {
locationManager.delegate = nil
}
}
extension JMLocationPermissionManager {
typealias JMPermissionAuthorizationHandlerCompletionBlock = (Bool) -> Void
}
| 33.2 | 114 | 0.663655 |
23bee84ba3b77efc7d1b178cdb9a6818e437862b | 14,708 | //
// BaseObject.swift
// RelationBook
//
// Created by 曾問 on 2021/5/11.
//
import UIKit
import Kingfisher
enum Collections: String {
case user = "Users"
case event = "Events"
case relation = "Relations"
}
protocol Icon: Codable {
var id: Int { get }
var isCustom: Bool { get }
var title: String { get }
var imageLink: String { get }
var backgroundColor: String { get }
}
extension Icon {
func getImage(completion: @escaping (UIImage?) -> Void) {
if imageLink.verifyUrl() {
UIImage.loadImage(imageLink, completion: completion)
} else if let image = UIImage(systemName: imageLink) ?? UIImage(named: imageLink) {
completion(image)
}
}
func getColor() -> UIColor {
return UIColor.UIColorFromString(string: backgroundColor)
}
}
class CategoryViewModel: Codable {
enum CategoryType: String, Codable {
case relation = "relationSet"
case event = "eventSet"
case feature = "featureSet"
}
struct CategoryData {
var title: String
var imageLink: String
var backgroundColor: String
}
var type: CategoryType
var filter: [String] = []
var main: [Category] = []
var sub: [Category] = []
init(type: CategoryType) {
self.type = type
switch type {
case .relation:
initialDefaultRelationCategory()
case .feature:
initialDefaultFeatureCategory()
case .event:
initialDefaultEventCategory()
}
}
func getMainCategories(superIndex: Int) -> [Category] {
if superIndex == -1 {
return main
}
return main.filter { $0.superIndex == superIndex }
}
func getSubCategories(superIndex: Int) -> [Category] {
if superIndex == -1 {
return sub
}
return sub.filter { $0.superIndex == superIndex }
}
func toDict() -> [String: Any] {
return [
"filter": filter,
"main": main.compactMap { category in category.toDict() },
"sub": sub.compactMap { category in category.toDict() },
"type": type.rawValue
]
}
private func initialDefaultRelationCategory() {
filter = ["家庭成員", "閨蜜死黨", "同儕好友", "導師前輩", "同事下屬", "鄰里住居", "親暱關係", "結拜關係", "其他"]
let mainData = [
[
CategoryData(title: "祖父母", imageLink: "icon_32px_c_l_17", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "父母", imageLink: "icon_32px_c_l_13", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "叔叔姑姑", imageLink: "icon_32px_c_l_13", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "兄弟姐妹", imageLink: "icon_32px_c_l_13", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "姪子姪女", imageLink: "icon_32px_c_l_13", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "夫妻", imageLink: "icon_32px_c_l_18", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "子女", imageLink: "icon_32px_c_l_15", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "孫子孫女", imageLink: "icon_32px_c_l_15", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "遠親", imageLink: "icon_32px_c_l_13", backgroundColor: UIColor.color1.stringFromUIColor())
],
[
CategoryData(title: "閨蜜", imageLink: "icon_32px_c_l_19", backgroundColor: UIColor.color9.stringFromUIColor()),
CategoryData(title: "死黨", imageLink: "icon_32px_c_l_19", backgroundColor: UIColor.color9.stringFromUIColor())
],
[
CategoryData(title: "學長姐", imageLink: "icon_32px_c_l_25", backgroundColor: UIColor.color2.stringFromUIColor()),
CategoryData(title: "學弟妹", imageLink: "icon_32px_c_l_25", backgroundColor: UIColor.color2.stringFromUIColor()),
CategoryData(title: "社團好友", imageLink: "icon_32px_c_l_25", backgroundColor: UIColor.color2.stringFromUIColor())
],
[
CategoryData(title: "老師", imageLink: "icon_32px_c_l_8", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "學生", imageLink: "icon_32px_c_l_8", backgroundColor: UIColor.color3.stringFromUIColor())
],
[
CategoryData(title: "老闆", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "主管", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "同事", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "前老闆", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "前主管", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "前同事", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor())
],
[
CategoryData(title: "鄰居", imageLink: "icon_32px_c_l_33", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "房東", imageLink: "icon_32px_c_l_33", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "房客", imageLink: "icon_32px_c_l_33", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "同居人", imageLink: "icon_32px_c_l_33", backgroundColor: UIColor.color5.stringFromUIColor())
],
[
CategoryData(title: "男女朋友", imageLink: "icon_32px_c_l_18", backgroundColor: UIColor.color6.stringFromUIColor()),
CategoryData(title: "前男女朋友", imageLink: "icon_32px_c_l_18", backgroundColor: UIColor.color6.stringFromUIColor()),
CategoryData(title: "老友", imageLink: "icon_32px_c_l_23", backgroundColor: UIColor.color6.stringFromUIColor())
],
[
CategoryData(title: "乾爹乾媽", imageLink: "icon_32px_c_l_24", backgroundColor: UIColor.color7.stringFromUIColor()),
CategoryData(title: "乾兄弟", imageLink: "icon_32px_c_l_24", backgroundColor: UIColor.color7.stringFromUIColor()),
CategoryData(title: "乾姐妹", imageLink: "icon_32px_c_l_24", backgroundColor: UIColor.color7.stringFromUIColor())
],
[
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
]
]
main = convertDateToCategory(data: mainData, isSubEnable: true)
}
private func initialDefaultFeatureCategory() {
filter = ["個人資訊", "情感狀態", "學習歷程", "職涯發展", "興趣特長", "其他"]
let mainData = [
[
CategoryData(title: "暱稱", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "生理性別", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "電話號碼", imageLink: "icon_32px_f_l_46", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "生日", imageLink: "icon_32px_f_l_26", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "星座", imageLink: "icon_32px_f_l_106", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "居住地", imageLink: "icon_32px_c_l_12", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "外貌特徵", imageLink: "icon_32px_f_l_65", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "個性", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
],
[
CategoryData(title: "交往", imageLink: "icon_32px_c_l_20", backgroundColor: UIColor.color6.stringFromUIColor()),
CategoryData(title: "婚嫁", imageLink: "icon_32px_c_l_20", backgroundColor: UIColor.color6.stringFromUIColor())
],
[
CategoryData(title: "畢業", imageLink: "icon_32px_c_l_6", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "休學", imageLink: "icon_32px_c_l_6", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "培訓", imageLink: "icon_32px_f_l_36", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "證書", imageLink: "icon_32px_c_l_6", backgroundColor: UIColor.color3.stringFromUIColor())
],
[
CategoryData(title: "任職", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "升職", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "降職", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "調職", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "離職", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor()),
CategoryData(title: "外派", imageLink: "icon_32px_c_l_26", backgroundColor: UIColor.color4.stringFromUIColor())
],
[
CategoryData(title: "運動", imageLink: "icon_32px_f_l_94", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "閱讀", imageLink: "icon_32px_c_l_9", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "飲食", imageLink: "icon_32px_f_l_1", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "旅遊", imageLink: "icon_32px_f_l_38", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "才藝", imageLink: "icon_32px_f_l_86", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "數位遊戲", imageLink: "icon_32px_f_l_93", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "實體遊戲", imageLink: "icon_32px_f_l_96", backgroundColor: UIColor.color5.stringFromUIColor()),
CategoryData(title: "多語言", imageLink: "icon_32px_f_l_107", backgroundColor: UIColor.color5.stringFromUIColor())
],
[
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
]
]
main = convertDateToCategory(data: mainData, isSubEnable: false)
}
private func initialDefaultEventCategory() {
filter = ["新關係", "日常互動", "赴約", "衝突", "其他"]
let mainData = [
[
CategoryData(title: "偶遇", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "同學", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "同事", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "介紹", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "同好", imageLink: "icon_32px_f_l_45", backgroundColor: UIColor.color1.stringFromUIColor()),
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
],
[
CategoryData(title: "閒聊", imageLink: "icon_32px_f_l_107", backgroundColor: UIColor.color2.stringFromUIColor()),
CategoryData(title: "八卦", imageLink: "icon_32px_f_l_107", backgroundColor: UIColor.color2.stringFromUIColor()),
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
],
[
CategoryData(title: "聚會", imageLink: "icon_32px_c_l_30", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "會議", imageLink: "icon_32px_c_l_27", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "遊戲", imageLink: "icon_32px_f_l_103", backgroundColor: UIColor.color3.stringFromUIColor()),
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
],
[
CategoryData(title: "誤會", imageLink: "icon_32px_f_l_108", backgroundColor: UIColor.color8.stringFromUIColor()),
CategoryData(title: "爭執", imageLink: "icon_32px_f_l_108", backgroundColor: UIColor.color8.stringFromUIColor()),
CategoryData(title: "指責", imageLink: "icon_32px_f_l_108", backgroundColor: UIColor.color8.stringFromUIColor()),
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
],
[
CategoryData(title: "其他", imageLink: "ellipsis", backgroundColor: UIColor.systemGray.stringFromUIColor())
]
]
main = convertDateToCategory(data: mainData, isSubEnable: false)
}
private func convertDateToCategory(data: [[CategoryData]], isSubEnable: Bool) -> [Category] {
var id = 0
var result: [Category] = []
for filterIndex in 0..<data.count {
for index in 0..<data[filterIndex].count {
let source = data[filterIndex][index]
result.append(Category(
id: id,
isCustom: false,
superIndex: filterIndex,
isSubEnable: isSubEnable,
title: source.title,
imageLink: source.imageLink,
backgroundColor: source.backgroundColor))
id += 1
}
}
return result
}
}
struct Category: Icon {
internal init(id: Int, isCustom: Bool, superIndex: Int, isSubEnable: Bool, title: String, imageLink: String, backgroundColor: String) {
self.id = id
self.isCustom = isCustom
self.superIndex = superIndex
self.isSubEnable = isSubEnable
self.title = title
self.imageLink = imageLink
self.backgroundColor = backgroundColor
}
init() {
self.id = -1
self.isCustom = false
self.superIndex = -1
self.isSubEnable = false
self.title = .empty
self.imageLink = .empty
self.imageLink = .empty
self.backgroundColor = .empty
}
var id: Int
var isCustom: Bool
var superIndex: Int
var isSubEnable: Bool
var title: String
var imageLink: String
var backgroundColor: String
}
extension Category {
func isInitialed() -> Bool {
return id != -1 && superIndex != -1
}
func toDict() -> [String: Any] {
return [
"id": id,
"isCustom": isCustom,
"superIndex": superIndex,
"isSubEnable": isSubEnable,
"title": title,
"imageLink": imageLink,
"backgroundColor": backgroundColor
]
}
static func canSubView(type: CategoryType, hierarchy: CategoryHierarchy) -> Bool {
switch type {
case .relation:
if hierarchy == .main {
return true
} else {
return false
}
default:
return false
}
}
}
| 43.005848 | 137 | 0.687041 |
f45aae226f1cb8206ba6aa517fdfe98e4d2dedfd | 15,059 |
public class File: CustomStringConvertible {
var _fd: Int32
public let path: String
// Lower level constructor. The validity of the fd parameter is not checked.
public init(path: String, fd: Int32) {
self.path = path
self._fd = fd
}
public init(path: String, mode: FileOperation = .R) throws {
self.path = path
_fd = Sys.openFile(path, operation: mode)
if _fd == -1 {
throw FileError.Open
}
}
deinit { close() }
public func printList(string: String) {
// 10 - new line
write(string)
if string.isEmpty || string.utf16.codeUnitAt(string.utf16.count - 1) != 10 {
let a: [UInt8] = [10]
writeBytes(a, maxBytes: a.count)
}
}
public func print(v: String) {
write(v)
}
public func read(maxBytes: Int = -1) throws -> String? {
if maxBytes < 0 {
let a = try readAllCChar()
return String.fromCharCodes(a)
} else {
var a = [CChar](count: maxBytes, repeatedValue: 0)
try readCChar(&a, maxBytes: maxBytes)
return String.fromCharCodes(a)
}
}
public func readBytes(inout buffer: [UInt8], maxBytes: Int) throws -> Int {
return try doRead(&buffer, maxBytes: maxBytes)
}
public func readAllBytes() throws -> [UInt8] {
var a = [UInt8](count: length, repeatedValue: 0)
let n = try readBytes(&a, maxBytes: a.count)
if n != a.count {
throw FileError.Read
}
return a
}
public func readCChar(inout buffer: [CChar], maxBytes: Int) throws -> Int {
return try doRead(&buffer, maxBytes: maxBytes)
}
public func readAllCChar() throws -> [CChar] {
var a = [CChar](count: length, repeatedValue: 0)
let n = try readCChar(&a, maxBytes: a.count)
if n != a.count {
throw FileError.Read
}
return a
}
public func readLines() throws -> [String?] {
var r: [String?] = []
let a = try readAllCChar()
var si = 0
for i in 0..<a.count {
if a[i] == 10 {
r.append(String.fromCharCodes(a, start: si, end: i))
si = i + 1
}
}
return r
}
public func write(string: String) -> Int {
return Sys.writeString(_fd, string: string)
}
public func writeBytes(bytes: [UInt8], maxBytes: Int) -> Int {
return Sys.write(_fd, address: bytes, length: maxBytes)
}
public func writeCChar(bytes: [CChar], maxBytes: Int) -> Int {
return Sys.write(_fd, address: bytes, length: maxBytes)
}
public func flush() {
// Not implemented yet.
}
public func close() {
if _fd != -1 {
Sys.close(_fd)
}
_fd = -1
}
public var isOpen: Bool { return _fd != -1 }
public var fd: Int32 { return _fd }
public func doRead(address: UnsafeMutablePointer<Void>, maxBytes: Int) throws
-> Int {
assert(maxBytes >= 0)
let n = Sys.read(_fd, address: address, length: maxBytes)
if n == -1 {
throw FileError.Read
}
return n
}
func seek(offset: Int, whence: Int32) -> Int {
return Sys.lseek(_fd, offset: offset, whence: whence)
}
public var position: Int {
get {
return seek(0, whence: PosixSys.SEEK_CUR)
}
set(value) {
seek(value, whence: PosixSys.SEEK_SET)
}
}
public var length: Int {
let current = position
if current == -1 {
return -1
} else {
let end = seek(0, whence: PosixSys.SEEK_END)
position = current
return end
}
}
public var description: String { return "File(path: \(inspect(path)))" }
public static func open(path: String, mode: FileOperation = .R,
fn: (f: File) throws -> Void) throws {
let f = try File(path: path, mode: mode)
defer { f.close() }
try fn(f: f)
}
public static func exists(path: String) -> Bool {
var buf = Sys.statBuffer()
return Sys.stat(path, buffer: &buf) == 0
}
public static func stat(path: String) -> Stat? {
var buf = Sys.statBuffer()
return Sys.stat(path, buffer: &buf) == 0 ? Stat(buffer: buf) : nil
}
public static func delete(path: String) throws {
if Sys.unlink(path) == -1 {
throw FileError.Delete
}
}
public static func rename(oldPath: String, newPath: String) throws {
if Sys.rename(oldPath, newPath: newPath) == -1 {
throw FileError.Rename
}
}
// Aliases for handy FilePath methods.
public static func join(firstPath: String, _ secondPath: String) -> String {
return FilePath.join(firstPath, secondPath)
}
public static func baseName(path: String, suffix: String? = nil) -> String {
return FilePath.baseName(path, suffix: suffix)
}
public static func dirName(path: String) -> String {
return FilePath.dirName(path)
}
public static func extName(path: String) -> String {
return FilePath.extName(path)
}
public static func expandPath(path: String) throws -> String {
return try FilePath.expandPath(path)
}
}
public enum FileError: ErrorType {
case Open
case Delete
case Rename
case Read
}
// The file will be closed and removed automatically when it can be garbage
// collected.
//
// The file will be created with the file mode of read/write by the user.
//
// **Note**: If the process is cancelled (CTRL+C) or does not terminate
// normally, the files may not be removed automatically.
public class TempFile: File {
init(prefix: String = "", suffix: String = "", directory: String? = nil)
throws {
var d = "/tmp/"
if let ad = directory {
d = ad
let len = d.utf16.count
if len == 0 || d.utf16.codeUnitAt(len - 1) != 47 { // /
d += "/"
}
}
var fd: Int32 = -1
var attempts = 0
var path = ""
while fd == -1 {
path = "\(d)\(prefix)\(RNG().nextUInt64())\(suffix)"
fd = Sys.openFile(path, operation: .W, mode: PosixSys.USER_RW_FILE_MODE)
if attempts >= 100 {
throw TempFileError.Create(message: "Too many attempts.")
} else if attempts % 10 == 0 {
IO.sleep(0.00000001)
}
attempts += 1
}
super.init(path: path, fd: fd)
}
deinit {
closeAndUnlink()
}
public func closeAndUnlink() {
close()
Sys.unlink(path)
}
}
public enum TempFileError: ErrorType {
case Create(message: String)
}
public class FilePath {
public static func join(firstPath: String, _ secondPath: String) -> String {
let fpa = firstPath.bytes
let i = skipTrailingSlashes(fpa, lastIndex: fpa.count - 1)
let fps = String.fromCharCodes(fpa, start: 0, end: i) ?? ""
if !secondPath.isEmpty && secondPath.utf16.codeUnitAt(0) == 47 { // /
return "\(fps)\(secondPath)"
}
return "\(fps)/\(secondPath)"
}
public static func skipTrailingSlashes(bytes: [UInt8], lastIndex: Int)
-> Int {
var i = lastIndex
while i >= 0 && bytes[i] == 47 { // /
i -= 1
}
return i
}
public static func skipTrailingChars(bytes: [UInt8], lastIndex: Int) -> Int {
var i = lastIndex
while i >= 0 && bytes[i] != 47 { // /
i -= 1
}
return i
}
public static func baseName(path: String, suffix: String? = nil) -> String {
let bytes = path.bytes
let len = bytes.count
var ei = skipTrailingSlashes(bytes, lastIndex: len - 1)
if ei >= 0 {
var si = 0
if ei > 0 {
si = skipTrailingChars(bytes, lastIndex: ei - 1) + 1
}
if let sf = suffix {
ei = skipSuffix(bytes, suffix: sf, lastIndex: ei)
}
return String.fromCharCodes(bytes, start: si, end: ei) ?? ""
}
return "/"
}
public static func skipSuffix(bytes: [UInt8], suffix: String, lastIndex: Int)
-> Int {
var a = suffix.bytes
var i = lastIndex
var j = a.count - 1
while i >= 0 && j >= 0 && bytes[i] == a[j] {
i -= 1
j -= 1
}
return j < 0 ? i : lastIndex
}
public static func dirName(path: String) -> String {
let bytes = path.bytes
let len = bytes.count
var i = skipTrailingSlashes(bytes, lastIndex: len - 1)
if i > 0 {
//var ei = i
i = skipTrailingChars(bytes, lastIndex: i - 1)
let ci = i
i = skipTrailingSlashes(bytes, lastIndex: i - 1)
if i >= 0 {
return String.fromCharCodes(bytes, start: 0, end: i) ?? ""
} else if ci > 0 {
return String.fromCharCodes(bytes, start: ci - 1, end: len - 1) ?? ""
} else if ci == 0 {
return "/"
}
} else if i == 0 {
// Ignore.
} else {
return String.fromCharCodes(bytes,
start: len - (len > 1 ? 2 : 1), end: len) ?? ""
}
return "."
}
public static func extName(path: String) -> String {
let bytes = path.bytes
var i = bytes.count - 1
if bytes[i] != 46 {
while i >= 0 && bytes[i] != 46 { // Skip trailing chars.
i -= 1
}
return String.fromCharCodes(bytes, start: i) ?? ""
}
return ""
}
public static func skipSlashes(bytes: [UInt8], startIndex: Int,
maxBytes: Int) -> Int {
var i = startIndex
while i < maxBytes && bytes[i] == 47 {
i += 1
}
return i
}
public static func skipChars(bytes: [UInt8], startIndex: Int,
maxBytes: Int) -> Int {
var i = startIndex
while i < maxBytes && bytes[i] != 47 {
i += 1
}
return i
}
static func checkHome(path: String?) throws -> String {
if let hd = path {
return hd
} else {
throw FilePathError.ExpandPath(message: "Invalid home directory.")
}
}
public static func expandPath(path: String) throws -> String {
let bytes = path.bytes
let len = bytes.count
if len > 0 {
var i = 0
let fc = bytes[0]
if fc == 126 { // ~
var homeDir = ""
if len == 1 || bytes[1] == 47 { // /
homeDir = try checkHome(IO.env["HOME"])
i = 1
} else {
i = skipChars(bytes, startIndex: 1, maxBytes: len)
if let name = String.fromCharCodes(bytes, start: 1, end: i - 1) {
let ps = Sys.getpwnam(name)
if ps != nil {
homeDir = try checkHome(String.fromCString(ps.memory.pw_dir))
} else {
throw FilePathError.ExpandPath(message: "User does not exist.")
}
} else {
throw FilePathError.ExpandPath(message: "Invalid name.")
}
}
if i >= len {
return homeDir
}
return join(homeDir, doExpandPath(bytes, startIndex: i,
maxBytes: len))
} else if fc != 47 { // /
if let cd = Dir.cwd {
if fc == 46 { // .
let za = join(cd, path).bytes
return doExpandPath(za, startIndex: 0, maxBytes: za.count)
}
return join(cd, doExpandPath(bytes, startIndex: 0, maxBytes: len))
} else {
throw FilePathError.ExpandPath(message: "Invalid current directory.")
}
}
return doExpandPath(bytes, startIndex: i, maxBytes: len)
}
return ""
}
public static func doExpandPath(bytes: [UInt8], startIndex: Int,
maxBytes: Int) -> String {
var i = startIndex
var a = [String]()
var ai = -1
var sb = ""
func add() {
let si = i
i = skipChars(bytes, startIndex: i + 1, maxBytes: maxBytes)
ai += 1
let s = String.fromCharCodes(bytes, start: si, end: i - 1) ?? ""
if ai < a.count {
a[ai] = s
} else {
a.append(s)
}
i = skipSlashes(bytes, startIndex: i + 1, maxBytes: maxBytes)
}
func stepBack() {
if ai >= 0 {
ai -= 1
}
i = skipSlashes(bytes, startIndex: i + 2, maxBytes: maxBytes)
}
if maxBytes > 0 {
let lasti = maxBytes - 1
while i < maxBytes && bytes[i] == 47 { //
sb += "/"
i += 1
}
if i >= maxBytes {
return sb
}
while i < maxBytes {
var c = bytes[i]
if c == 46 { // .
if i < lasti {
c = bytes[i + 1]
if c == 46 { // ..
if i < lasti - 1 {
c = bytes[i + 2]
if c == 47 { // /
stepBack()
} else {
add()
}
} else {
stepBack()
}
} else if c == 47 { // /
i = skipSlashes(bytes, startIndex: i + 2, maxBytes: maxBytes)
} else {
add()
}
} else {
break
}
} else {
add()
}
}
var slash = false
for i in 0...ai {
if slash {
sb += "/"
}
sb += a[i]
slash = true
}
if bytes[lasti] == 47 { // /
sb += "/"
}
}
return sb
}
}
enum FilePathError: ErrorType {
case ExpandPath(message: String)
}
public class FileStream {
public var fp: CFilePointer?
let SIZE = 80 // Starting buffer size.
public init(fp: CFilePointer) {
self.fp = fp
}
deinit { close() }
public func close() {
if let afp = fp {
Sys.fclose(afp)
}
fp = nil
}
public func readAllCChar(command: String) throws -> [CChar] {
guard let afp = fp else { return [CChar]() }
var a = [CChar](count: SIZE, repeatedValue: 0)
var buffer = [CChar](count: SIZE, repeatedValue: 0)
var alen = SIZE
var j = 0
while Sys.fgets(&buffer, length: Int32(SIZE), fp: afp) != nil {
for i in 0..<SIZE {
let c = buffer[i]
if c == 0 {
break
}
if j >= alen {
var b = [CChar](count: alen * 8, repeatedValue: 0)
for m in 0..<alen {
b[m] = a[m]
}
a = b
alen = b.count
}
a[j] = c
j += 1
}
}
return a
}
public func readLines(command: String, fn: (string: String?)
-> Void) throws {
guard let afp = fp else { return }
var a = [CChar](count: SIZE, repeatedValue: 0)
var buffer = [CChar](count: SIZE, repeatedValue: 0)
var alen = SIZE
var j = 0
while Sys.fgets(&buffer, length: Int32(SIZE), fp: afp) != nil {
var i = 0
while i < SIZE {
let c = buffer[i]
if c == 0 {
break
}
if j >= alen {
var b = [CChar](count: alen * 8, repeatedValue: 0)
for m in 0..<alen {
b[m] = a[m]
}
a = b
alen = b.count
}
a[j] = c
if c == 10 {
fn(string: String.fromCharCodes(a, start: 0, end: j))
j = 0
} else {
j += 1
}
i += 1
}
}
if j > 0 {
fn(string: String.fromCharCodes(a, start: 0, end: j - 1))
}
}
public func readByteLines(command: String, maxBytes: Int = 80,
fn: (bytes: [UInt8], length: Int) -> Void) throws {
guard let afp = fp else { return }
var buffer = [UInt8](count: Int(maxBytes), repeatedValue: 0)
while true {
let n = Sys.fread(&buffer, size: 1, nmemb: maxBytes, fp: afp)
if n > 0 {
fn(bytes: buffer, length: n)
} else {
break
}
}
}
}
| 24.606209 | 80 | 0.538482 |
091ae35fe9e835060d3ee8ed5b987670a410d2b2 | 1,029 | /*
* Copyright 2020 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
/*
Some of the Credentials needs to be populated for the Swift Tests to work.
Please follow the following steps to populate the valid Credentials
and copy it to Credentials.swift file:
You will need to replace the following values:
$KUSER_NAME
The name of the user for Auth SignIn
$KPASSWORD
The password.
*/
class Credentials {
static let kUserName = KUSER_NAME
static let kPassword = KPASSWORD
}
| 28.583333 | 75 | 0.749271 |
1a4a4b7a1e10806d2a8e82399621496b0ca2812d | 1,995 | // Copyright 2021 Chip Jarred
//
// 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 Cocoa
import MacMenuBar
// -------------------------------------
let viewMenu = StandardMenu(title: "View")
{
TextMenuItem(title: "Show Toolbar", action: .showToolbar).enabled(false)
TextMenuItem(title: "Customize Toolbar...", action: .customizeToolbar).enabled(false)
MenuSeparator()
TextMenuItem(title: "Show Sidebar", action: .showSidebar).enabled(false)
TextMenuItem(title: "Enter Full Screen", action: .enterFullScreen)
.afterAction
{ menuItem in
if AppDelegate.isFullScreen
{
menuItem.title = "Exit Full Screen"
KeyEquivalent.escape.set(in: menuItem)
}
else
{
menuItem.title = "Enter Full Screen"
(.command + .control + "f").set(in: menuItem)
}
}
}
.refuseAutoinjectedMenuItems()
| 39.9 | 89 | 0.675188 |
7a9bc97a5997176200039dc61bd29c0f1f822fc1 | 2,421 | // UITextFieldExtension.swift
// Copyright (c) 2019 Jerome Hsieh. All rights reserved.
// Created by Jerome Hsieh.
import UIKit
extension UITextField {
public func setInputView(view: UIView, doneTitle: String, cancelTitle: String, target: Any, selector: Selector) {
// Create a UIDatePicker object and assign to inputView
let screenWidth = UIScreen.main.bounds.width
inputView = view
// Create a toolbar and assign it to inputAccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: cancelTitle, style: .plain, target: nil, action: #selector(tapCancel))
let barButton = UIBarButtonItem(title: doneTitle, style: .plain, target: target, action: selector)
toolBar.setItems([cancel, flexible, barButton], animated: false)
inputAccessoryView = toolBar
}
public func setInputViewDatePicker(defaultDate: Date = Date(), maximumDate: Date = Date(), doneTitle: String, cancelTitle: String, target: Any, selector: Selector) {
// Create a UIDatePicker object and assign to inputView
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
datePicker.datePickerMode = .date
datePicker.date = defaultDate
datePicker.maximumDate = maximumDate
if #available(iOS 13.4, *) {
datePicker.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
inputView = datePicker
// Create a toolbar and assign it to inputAccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: cancelTitle, style: .plain, target: nil, action: #selector(tapCancel))
let barButton = UIBarButtonItem(title: doneTitle, style: .plain, target: target, action: selector)
toolBar.setItems([cancel, flexible, barButton], animated: false)
inputAccessoryView = toolBar
}
@objc func tapCancel() {
resignFirstResponder()
}
public var textIsNotEmpty: Bool {
guard let notNilText = text, notNilText.isEmpty == false else {
return false
}
return true
}
}
| 43.232143 | 167 | 0.71582 |
d9e8897b47b481ed70e8cfff943468d3f48c2489 | 822 | //
// DrienDistanceTableViewCell.swift
// FIT5140Assignment3iOS
//
// Created by Shirley on 2020/11/2.
//
import UIKit
import Charts
class DrienDistanceTableViewCell: UITableViewCell {
@IBOutlet weak var contentBackgroundview: UIView!
@IBOutlet weak var barChart: BarChartView!
@IBOutlet weak var headerLaebl: UILabel!
static let identifier = "DrienDistanceTableViewCell"
static func nib()->UINib{
return UINib(nibName: "DrienDistanceTableViewCell", bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
contentBackgroundview.layer.cornerRadius = 24
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 24.909091 | 72 | 0.70073 |
0eebaf567258b1d2ac85242c8ad75c820cf48a68 | 3,891 | //
// Copyright (c) 2017 Adyen B.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Foundation
internal class CardOneClickDetailsPresenter: PaymentDetailsPresenter {
private let hostViewController: UINavigationController
private let pluginConfiguration: PluginConfiguration
internal weak var delegate: PaymentDetailsPresenterDelegate?
internal init(hostViewController: UINavigationController, pluginConfiguration: PluginConfiguration) {
self.hostViewController = hostViewController
self.pluginConfiguration = pluginConfiguration
}
internal func start() {
hostViewController.present(alertController, animated: true)
}
private func submit(cvc: String) {
let paymentDetails = PaymentDetails(details: pluginConfiguration.paymentMethod.inputDetails ?? [])
paymentDetails.fillCard(cvc: cvc)
delegate?.paymentDetailsPresenter(self, didSubmit: paymentDetails)
}
// MARK: - Alert Controller
private lazy var alertController: UIAlertController = {
let paymentMethod = self.pluginConfiguration.paymentMethod
let paymentSetup = self.pluginConfiguration.paymentSetup
let title = ADYLocalizedString("creditCard.oneClickVerification.title")
let message = ADYLocalizedString("creditCard.oneClickVerification.message", paymentMethod.displayName)
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addTextField(configurationHandler: { textField in
textField.textAlignment = .center
textField.keyboardType = .numberPad
textField.placeholder = ADYLocalizedString("creditCard.cvcField.placeholder")
textField.accessibilityLabel = ADYLocalizedString("creditCard.cvcField.title")
})
let cancelActionTitle = ADYLocalizedString("cancelButton")
let cancelAction = UIAlertAction(title: cancelActionTitle, style: .cancel, handler: nil)
alertController.addAction(cancelAction)
let formattedAmount = CurrencyFormatter.format(paymentSetup.amount, currencyCode: paymentSetup.currencyCode) ?? ""
let confirmActionTitle = ADYLocalizedString("payButton.formatted", formattedAmount)
let confirmAction = UIAlertAction(title: confirmActionTitle, style: .default) { [unowned self] _ in
self.didSelectOneClickAlertControllerConfirmAction()
}
alertController.addAction(confirmAction)
return alertController
}()
private func didSelectOneClickAlertControllerConfirmAction() {
// Verify that a non-empty CVC has been entered. If not, present an alert.
guard
let textField = alertController.textFields?.first,
let cvc = textField.text, cvc.characters.count > 0
else {
presentInvalidCVCAlertController()
return
}
submit(cvc: cvc)
}
private func presentInvalidCVCAlertController() {
let alertController = UIAlertController(title: ADYLocalizedString("creditCard.oneClickVerification.invalidInput.title"),
message: ADYLocalizedString("creditCard.oneClickVerification.invalidInput.message"),
preferredStyle: .alert)
let dismissActionTitle = ADYLocalizedString("dismissButton")
let dismissAction = UIAlertAction(title: dismissActionTitle, style: .default) { [unowned self] _ in
self.start() // Restart the flow.
}
alertController.addAction(dismissAction)
hostViewController.present(alertController, animated: false)
}
}
| 41.83871 | 132 | 0.682344 |
8f91a6f985d95cee4fe75e4d2dbce64744b48954 | 4,854 | //
// MouseState.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 3/21/19.
// Copyright © 2019 Ian Ynda-Hummel. All rights reserved.
//
import Foundation
import Silica
/**
These are the possible actions that the mouse might be taking (that we care about).
We use this enum to convey some information about the window that the mouse might be interacting with.
*/
enum MouseState<Window: WindowType> {
case pointing
case clicking
case dragging
case moving(window: Window)
case resizing(screen: NSScreen, ratio: CGFloat)
case doneDragging(atTime: Date)
}
/// MouseStateKeeper will need a few things to do its job effectively
protocol MouseStateKeeperDelegate: class {
associatedtype Window: WindowType
func recommendMainPaneRatio(_ ratio: CGFloat)
func swapDraggedWindowWithDropzone(_ draggedWindow: Window)
}
/**
Maintains state information about the mouse for the purposes of mouse-based window operations.
MouseStateKeeper exists because we need a single shared mouse state between all applications being observed. This class captures the state and coordinates any Amethyst reflow actions that are required in response to mouse events.
Note that some actions may be initiated here and some actions may be completed here; we don't know whether the mouse event stream or the accessibility event stream will fire first.
This class by itself can only understand clicking, dragging, and "pointing" (no mouse buttons down). The SIApplication observers are able to augment that understanding of state by "upgrading" a drag action to a "window move" or a "window resize" event since those observers will have proper context.
*/
class MouseStateKeeper<Delegate: MouseStateKeeperDelegate> {
public let dragRaceThresholdSeconds = 0.15 // prevent race conditions during drag ops
public var state: MouseState<Delegate.Window>
private(set) weak var delegate: Delegate?
private var monitor: Any?
init(delegate: Delegate) {
self.delegate = delegate
state = .pointing
let mouseEventsToWatch: NSEvent.EventTypeMask = [.leftMouseDown, .leftMouseUp, .leftMouseDragged]
monitor = NSEvent.addGlobalMonitorForEvents(matching: mouseEventsToWatch, handler: self.handleMouseEvent)
}
deinit {
guard let oldMonitor = monitor else { return }
NSEvent.removeMonitor(oldMonitor)
}
// Update our understanding of the current state unless an observer has already
// done it for us. mouseUp events take precedence over anything an observer had
// found -- you can't be dragging or resizing with a mouse button up, even if
// you're using the "3 finger drag" accessibility option, where no physical button
// is being pressed.
func handleMouseEvent(anEvent: NSEvent) {
switch anEvent.type {
case .leftMouseDown:
self.state = .clicking
case .leftMouseDragged:
switch self.state {
case .moving, .resizing:
break // ignore - we have what we need
case .pointing, .clicking, .dragging, .doneDragging:
self.state = .dragging
}
case .leftMouseUp:
switch self.state {
case .dragging:
// assume window move event will come shortly after
self.state = .doneDragging(atTime: Date())
case let .moving(draggedWindow):
self.state = .pointing // flip state first to prevent race condition
self.swapDraggedWindowWithDropzone(draggedWindow)
case let .resizing(_, ratio):
self.state = .pointing
self.resizeFrameToDraggedWindowBorder(ratio)
case .doneDragging:
self.state = .doneDragging(atTime: Date()) // reset the clock I guess
case .pointing, .clicking:
self.state = .pointing
}
default: ()
}
}
// React to a reflow event. Typically this means that any window we were dragging
// is no longer valid and should be de-correlated from the mouse
func handleReflowEvent() {
switch self.state {
case .doneDragging:
self.state = .pointing // remove associated timestamp
case .moving:
self.state = .dragging // remove associated window
default: ()
}
}
// Execute an action that was initiated by the observer and completed by the state keeper
func resizeFrameToDraggedWindowBorder(_ ratio: CGFloat) {
delegate?.recommendMainPaneRatio(ratio)
}
// Execute an action that was initiated by the observer and completed by the state keeper
func swapDraggedWindowWithDropzone(_ draggedWindow: Delegate.Window) {
delegate?.swapDraggedWindowWithDropzone(draggedWindow)
}
}
| 39.786885 | 299 | 0.685002 |
505333f29f5d966c8510f1286d12b327499bac00 | 4,088 | //===----------------------------------------------------------------------===//
//
// This source file is part of the KafkaNIO open source project
//
// Copyright © 2020 Thomas Bartelmess.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
extension Consumer {
private func _joinGroup(groupCoordinator: BrokerConnectionProtocol, memberID: String = "") -> EventLoopFuture<JoinGroupResponse> {
logger.info("Joining group as with memberID: \(memberID)")
return groupCoordinator.requestJoinGroup(groupID: self.configuration.groupID,
topics: configuration.subscribedTopics,
sessionTimeout: Int32(configuration.sessionTimeout),
rebalanceTimeout: Int32(configuration.rebalanceTimeout),
memberID: memberID,
groupInstanceID: nil)
.flatMap { response in
if response.errorCode == .memberIdRequired {
return self._joinGroup(groupCoordinator: groupCoordinator, memberID: response.memberID)
}
if response.errorCode != .noError {
return self.eventLoop.makeFailedFuture(KafkaError.unexpectedKafkaErrorCode(response.errorCode))
}
return self.eventLoop.makeSucceededFuture(response)
}
}
func joinGroup(groupCoordinator: BrokerConnectionProtocol, memberID: String = "") -> EventLoopFuture<GroupInfo> {
self._joinGroup(groupCoordinator: groupCoordinator, memberID: memberID)
.flatMapResult { response -> Result<GroupInfo, KafkaError> in
// Older brokers that don't support KIP-394, won't sent a .memberIDRequired error.
let assignedMemberID = response.memberID
guard response.errorCode == .noError else {
self.logger.error("Failed to join group: \(response.errorCode)")
return .failure(.unexpectedKafkaErrorCode(response.errorCode))
}
guard let protocolName = response.protocolName,
let assignmentProtocol = AssignmentProtocol(rawValue: protocolName) else {
return .failure(.unsupportedAssignmentProtocol)
}
let groupStatus: GroupStatus
if response.leader == assignedMemberID {
do {
let memberMetadata = try response.members.map { responseMember -> MemberMetadata in
let subscription = try responseMember.subscription()
return MemberMetadata(memberID: responseMember.memberID,
groupInstanceID: responseMember.groupInstanceID,
subscription: subscription)
}
groupStatus = .leader(memberMetadata: memberMetadata)
} catch let error as KafkaError {
return .failure(error)
} catch {
fatalError("Unexpected error: \(error)")
}
} else {
groupStatus = .notLeader
}
let groupInfo = GroupInfo(groupID: self.configuration.groupID,
memberID: assignedMemberID,
generationID: response.generationID,
assignmentProtocol: assignmentProtocol,
groupStatus: groupStatus,
coordinator: groupCoordinator)
return .success(groupInfo)
}
}
}
| 48.666667 | 134 | 0.513454 |
f41de2ba9601eabf83103822709981daae64759c | 2,045 | //
// DeviceSpecificInputSetProvider.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-03.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
/**
This protocol extends `InputSetProvider` and can be used by
any provider that bases its input set on the current device.
For now, this provider will return the iPhone input set for
any device that is not explicitly iPad.
*/
public protocol DeviceSpecificInputSetProvider: InputSetProvider {}
public extension DeviceSpecificInputSetProvider {
/**
Create an input row from phone and pad-specific strings.
*/
func row(
phone: String,
pad: String,
deviceType: DeviceType = .current) -> InputSetRow {
InputSetRow(deviceType == .pad ? pad.chars : phone.chars)
}
/**
Create an input row from phone and pad-specific arrays.
*/
func row(
phone: [String],
pad: [String],
deviceType: DeviceType = .current) -> InputSetRow {
InputSetRow(deviceType == .pad ? pad : phone)
}
/**
Create an input row from phone and pad-specific strings.
*/
func row(
phoneLowercased: String,
phoneUppercased: String,
padLowercased: String,
padUppercased: String,
deviceType: DeviceType = .current) -> InputSetRow {
InputSetRow(
lowercased: deviceType == .pad ? padLowercased.chars : phoneLowercased.chars,
uppercased: deviceType == .pad ? padUppercased.chars : phoneUppercased.chars)
}
/**
Create an input row from phone and pad-specific arrays.
*/
func row(
phoneLowercased: [String],
phoneUppercased: [String],
padLowercased: [String],
padUppercased: [String],
deviceType: DeviceType = .current) -> InputSetRow {
InputSetRow(
lowercased: deviceType == .pad ? padLowercased : phoneLowercased,
uppercased: deviceType == .pad ? padUppercased : phoneUppercased)
}
}
| 29.214286 | 89 | 0.634719 |
e8a3c03165eb9750fb94a4a0b2748f43609ce364 | 832 | //
// UIView.swift
// Hungry Enough
//
// Created by Diep Nguyen Hoang on 7/5/15.
// Copyright © 2017 Hungry Enough. All rights reserved.
//
import UIKit
extension UIView {
var x: CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame.origin.x = newValue
}
}
var y: CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame.origin.y = newValue
}
}
var width: CGFloat {
get {
return self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
var height: CGFloat {
get {
return self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
}
| 16.979592 | 56 | 0.471154 |
def4cfa2c000140da06af7d54cbce5ec7e4a5ccf | 2,453 | //
// ViewController.swift
// LuBottomAlertView
//
// Created by 路政浩 on 2016/11/11.
// Copyright © 2016年 RamboLu. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
lazy var testTableView : UITableView = {
var testTableView = UITableView()
testTableView.backgroundColor = UIColor.lightGray
testTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
testTableView.delegate = self
testTableView.dataSource = self
return testTableView
}()
let textArr = ["弹出相同样式列表",
"弹出上灰下红样式列表",
"弹出时间轴"]
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(testTableView)
testTableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
}
}
extension ViewController{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
cell.textLabel?.text = textArr[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
debugPrint("\(indexPath)")
switch indexPath.row {
case 0:
let str = ["0","测试测试测试1","测试测试测试2","测试测试测试3","测试测试测试4"]
LuBottomAlertView().showBottomTableView(indexTextArr: str, bottomAction: { (num) in
debugPrint("所选角标:\(num!)")
})
break
case 1:
let str = ["1","测试标题","测试测试测试"]
LuBottomAlertView().showBottomTableView(indexTextArr: str, bottomAction: { (num) in
debugPrint("所选角标:\(num!)")
})
break
case 2:
LuBottomAlertView().showBottomDatePickerView{ (num) in
debugPrint("返回年龄数值:\(num!)")
}
break
default:
break
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (UIScreen.main.bounds.size.height-64)/5
}
}
| 30.6625 | 100 | 0.605789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.