repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hoffmanjon/SwiftyBones
examples/MotionSensor/SwiftyBones/SwiftyBonesDigitalGPIO.swift
2
6660
#if arch(arm) && os(Linux) import Glibc #else import Darwin #endif /** The list of available GPIO. */ var DigitalGPIOPins:[String: BBExpansionPin] = [ "gpio38": (header:.P8, pin:3), "gpio39": (header:.P8, pin:4), "gpio34": (header:.P8, pin:5), "gpio35": (header:.P8, pin:6), "gpio66": (header:.P8, pin:7), "gpio67": (header:.P8, pin:8), "gpio69": (header:.P8, pin:9), "gpio68": (header:.P8, pin:10), "gpio45": (header:.P8, pin:11), "gpio44": (header:.P8, pin:12), "gpio23": (header:.P8, pin:13), "gpio26": (header:.P8, pin:14), "gpio47": (header:.P8, pin:15), "gpio46": (header:.P8, pin:16), "gpio27": (header:.P8, pin:17), "gpio65": (header:.P8, pin:18), "gpio22": (header:.P8, pin:19), "gpio63": (header:.P8, pin:20), "gpio62": (header:.P8, pin:21), "gpio37": (header:.P8, pin:22), "gpio36": (header:.P8, pin:23), "gpio33": (header:.P8, pin:24), "gpio32": (header:.P8, pin:25), "gpio61": (header:.P8, pin:26), "gpio86": (header:.P8, pin:27), "gpio88": (header:.P8, pin:28), "gpio87": (header:.P8, pin:29), "gpio89": (header:.P8, pin:30), "gpio10": (header:.P8, pin:31), "gpio11": (header:.P8, pin:32), "gpio9": (header:.P8, pin:33), "gpio81": (header:.P8, pin:34), "gpio8": (header:.P8, pin:35), "gpio80": (header:.P8, pin:36), "gpio78": (header:.P8, pin:37), "gpio79": (header:.P8, pin:38), "gpio76": (header:.P8, pin:39), "gpio77": (header:.P8, pin:40), "gpio74": (header:.P8, pin:41), "gpio75": (header:.P8, pin:42), "gpio72": (header:.P8, pin:43), "gpio73": (header:.P8, pin:44), "gpio70": (header:.P8, pin:45), "gpio71": (header:.P8, pin:46), "gpio30": (header:.P9, pin:11), "gpio60": (header:.P9, pin:12), "gpio31": (header:.P9, pin:13), "gpio50": (header:.P9, pin:14), "gpio48": (header:.P9, pin:15), "gpio51": (header:.P9, pin:16), "gpio5": (header:.P9, pin:17), "gpio4": (header:.P9, pin:18), "gpio3": (header:.P9, pin:21), "gpio2": (header:.P9, pin:22), "gpio49": (header:.P9, pin:23), "gpio15": (header:.P9, pin:24), "gpio117": (header:.P9, pin:25), "gpio14": (header:.P9, pin:26), "gpio115": (header:.P9, pin:27), "gpio113": (header:.P9, pin:28), "gpio111": (header:.P9, pin:29), "gpio112": (header:.P9, pin:30), "gpio110": (header:.P9, pin:31), "gpio20": (header:.P9, pin:41), "gpio7": (header:.P9, pin:42) ] /** Direction that pin can be configured for */ enum DigitalGPIODirection: String { case IN="in" case OUT="out" } /** The value of the digitial GPIO pins */ enum DigitalGPIOValue: String { case HIGH="1" case LOW="0" } /** Type that represents a GPIO pin on the Beaglebone Black */ struct SBDigitalGPIO: GPIO { /** Variables and paths needed */ private static let GPIO_BASE_PATH = "/sys/class/gpio/" private static let GPIO_EXPORT_PATH = GPIO_BASE_PATH + "export" private static let GPIO_DIRECTION_FILE = "/direction" private static let GPIO_VALUE_FILE = "/value" private var header: BBExpansionHeader private var pin: Int private var id: String private var direction: DigitalGPIODirection /** Failable initiator which will fail if an invalid ID is entered - Parameter id: The ID of the pin. The ID starts with gpio and then contains the gpio number - Parameter direction: The direction to configure the pin for */ init?(id: String, direction: DigitalGPIODirection) { if let val = DigitalGPIOPins[id] { self.id = id self.header = val.header self.pin = val.pin self.direction = direction if !initPin() { return nil } } else { return nil } } /** Failable initiator which will fail if either the header or pin number is invalid - Parameter header: This is the header which will be either .P8 or .P9 - pin: the pin number - Parameter direction: The direction to configure the pin for */ init?(header: BBExpansionHeader, pin: Int, direction: DigitalGPIODirection) { for (key, expansionPin) in DigitalGPIOPins where expansionPin.header == header && expansionPin.pin == pin { self.header = header self.pin = pin self.id = key self.direction = direction if !initPin() { return nil } return } return nil } /** This method configures the pin for Digital I/O - Returns: true if the pin was successfully configured for digitial I/O */ func initPin() -> Bool { let range = id.startIndex.advancedBy(4)..<id.endIndex.advancedBy(0) let gpioId = id[range] let gpioSuccess = writeStringToFile(gpioId, path: SBDigitalGPIO.GPIO_EXPORT_PATH) let directionSuccess = writeStringToFile(direction.rawValue, path: getDirectionPath()) if !gpioSuccess || !directionSuccess { return false } return true } /** This function checks to see if the pin is configured for Digital I/O - Returns: true if the pin is already configured otherwise false */ func isPinActive() -> Bool { if let _ = getValue() { return true } else { return false } } /** Gets the present value from the pin - Returns: returns the value for the pin eith .HIGH or .LOW */ func getValue() -> DigitalGPIOValue? { if let valueStr = readStringFromFile(getValuePath()) { return valueStr == DigitalGPIOValue.HIGH.rawValue ? DigitalGPIOValue.HIGH : DigitalGPIOValue.LOW } else { return nil } } /** Sets the value for the pin - Parameter value: The value for the pin either .HIGH or .LOW */ func setValue(value: DigitalGPIOValue) { writeStringToFile(value.rawValue, path: getValuePath()) } /** Determines the path to the file for this particular digital pin direction file - Returns: Path to file */ private func getDirectionPath() -> String { return SBDigitalGPIO.GPIO_BASE_PATH + id + SBDigitalGPIO.GPIO_DIRECTION_FILE } /** Determines the path to the file for this particular digital pin - Returns: Path to file */ private func getValuePath() -> String { return SBDigitalGPIO.GPIO_BASE_PATH + id + SBDigitalGPIO.GPIO_VALUE_FILE } }
mit
8b979e9781ae0fd911c3d8f74db2bb46
29.976744
115
0.578979
3.245614
false
false
false
false
broccolii/NetworkService
NetworkService/NetworkService/ViewController/TestNetworkViewController.swift
1
1101
// // ViewController.swift // NetworkService // // Created by Broccoli on 16/1/4. // Copyright © 2016年 Broccoli. All rights reserved. // import UIKit import RxSwift import RxCocoa class TestNetworkViewController: UIViewController { @IBOutlet var tableView: UITableView! let disposeBag = DisposeBag() let testNetworkViewModel = TestNetworkViewModel() var tableViewDataArr = [ModelBasic]() override func viewDidLoad() { super.viewDidLoad() testNetworkViewModel.getJson() } } // MARK: - UITableViewDataSource private let CellIdentifier = "TestNetworkViewCell" extension TestNetworkViewController { func bindtoTableView() { testNetworkViewModel.tableViewData.asObservable().bindTo(tableView.rx_itemsWithCellIdentifier(CellIdentifier)) {(row, element, cell) in guard let myCell: UITableViewCell = cell else { return } myCell.textLabel?.text = "\(element.date)" myCell.detailTextLabel?.text = "\(element.s)" }.addDisposableTo(disposeBag) } }
mit
71752a56d19d2834d60a124f6aca09c1
26.475
143
0.67122
4.945946
false
true
false
false
Jnosh/swift
stdlib/public/SDK/Foundation/Decimal.swift
2
18913
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import _SwiftCoreFoundationOverlayShims extension Decimal { public typealias RoundingMode = NSDecimalNumber.RoundingMode public typealias CalculationError = NSDecimalNumber.CalculationError public static let leastFiniteMagnitude = Decimal(_exponent: 127, _length: 8, _isNegative: 1, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) public static let greatestFiniteMagnitude = Decimal(_exponent: 127, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) public static let leastNormalMagnitude = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) public static let leastNonzeroMagnitude = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) public static let pi = Decimal(_exponent: -38, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58)) public var exponent: Int { get { return Int(_exponent) } } public var significand: Decimal { get { return Decimal(_exponent: 0, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa) } } public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) { self.init(_exponent: Int32(exponent) + significand._exponent, _length: significand._length, _isNegative: sign == .plus ? 0 : 1, _isCompact: significand._isCompact, _reserved: 0, _mantissa: significand._mantissa) } public init(signOf: Decimal, magnitudeOf magnitude: Decimal) { self.init(_exponent: magnitude._exponent, _length: magnitude._length, _isNegative: signOf._isNegative, _isCompact: magnitude._isCompact, _reserved: 0, _mantissa: magnitude._mantissa) } public var sign: FloatingPointSign { return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus } public static var radix: Int { return 10 } public var ulp: Decimal { if !self.isFinite { return Decimal.nan } return Decimal(_exponent: _exponent, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not yet fully adopt FloatingPoint") } public mutating func negate() { _isNegative = _isNegative == 0 ? 1 : 0 } public func isEqual(to other: Decimal) -> Bool { var lhs = self var rhs = other return NSDecimalCompare(&lhs, &rhs) == .orderedSame } public func isLess(than other: Decimal) -> Bool { var lhs = self var rhs = other return NSDecimalCompare(&lhs, &rhs) == .orderedAscending } public func isLessThanOrEqualTo(_ other: Decimal) -> Bool { var lhs = self var rhs = other let order = NSDecimalCompare(&lhs, &rhs) return order == .orderedAscending || order == .orderedSame } public func isTotallyOrdered(belowOrEqualTo other: Decimal) -> Bool { // Notes: Decimal does not have -0 or infinities to worry about if self.isNaN { return false } else if self < other { return true } else if other < self { return false } // fall through to == behavior return true } public var isCanonical: Bool { return true } public var nextUp: Decimal { return self + Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } public var nextDown: Decimal { return self - Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } public static func +(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalAdd(&res, &leftOp, &rightOp, .plain) return res } public static func -(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalSubtract(&res, &leftOp, &rightOp, .plain) return res } public static func /(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalDivide(&res, &leftOp, &rightOp, .plain) return res } public static func *(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalMultiply(&res, &leftOp, &rightOp, .plain) return res } } public func pow(_ x: Decimal, _ y: Int) -> Decimal { var res = Decimal() var num = x NSDecimalPower(&res, &num, y, .plain) return res } extension Decimal : Hashable, Comparable { internal var doubleValue : Double { var d = 0.0 if _length == 0 && _isNegative == 0 { return Double.nan } for i in 0..<8 { let index = 8 - i - 1 switch index { case 0: d = d * 65536 + Double(_mantissa.0) case 1: d = d * 65536 + Double(_mantissa.1) case 2: d = d * 65536 + Double(_mantissa.2) case 3: d = d * 65536 + Double(_mantissa.3) case 4: d = d * 65536 + Double(_mantissa.4) case 5: d = d * 65536 + Double(_mantissa.5) case 6: d = d * 65536 + Double(_mantissa.6) case 7: d = d * 65536 + Double(_mantissa.7) default: fatalError("conversion overflow") } } if _exponent < 0 { for _ in _exponent..<0 { d /= 10.0 } } else { for _ in 0..<_exponent { d *= 10.0 } } return _isNegative != 0 ? -d : d } public var hashValue: Int { return Int(bitPattern: __CFHashDouble(doubleValue)) } public static func ==(lhs: Decimal, rhs: Decimal) -> Bool { var lhsVal = lhs var rhsVal = rhs return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame } public static func <(lhs: Decimal, rhs: Decimal) -> Bool { var lhsVal = lhs var rhsVal = rhs return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending } } extension Decimal : ExpressibleByFloatLiteral { public init(floatLiteral value: Double) { self.init(value) } } extension Decimal : ExpressibleByIntegerLiteral { public init(integerLiteral value: Int) { self.init(value) } } extension Decimal : SignedNumeric { public var magnitude: Decimal { return Decimal( _exponent: self._exponent, _length: self._length, _isNegative: 0, _isCompact: self._isCompact, _reserved: 0, _mantissa: self._mantissa) } // FIXME(integers): implement properly public init?<T : BinaryInteger>(exactly source: T) { fatalError() } public static func +=(_ lhs: inout Decimal, _ rhs: Decimal) { var rhs = rhs NSDecimalAdd(&lhs, &lhs, &rhs, .plain) } public static func -=(_ lhs: inout Decimal, _ rhs: Decimal) { var rhs = rhs NSDecimalSubtract(&lhs, &lhs, &rhs, .plain) } public static func *=(_ lhs: inout Decimal, _ rhs: Decimal) { var rhs = rhs NSDecimalMultiply(&lhs, &lhs, &rhs, .plain) } public static func /=(_ lhs: inout Decimal, _ rhs: Decimal) { var rhs = rhs NSDecimalDivide(&lhs, &lhs, &rhs, .plain) } } extension Decimal { @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func add(_ other: Decimal) { self += other } @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func subtract(_ other: Decimal) { self -= other } @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func multiply(by other: Decimal) { self *= other } @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func divide(by other: Decimal) { self /= other } } extension Decimal : Strideable { public func distance(to other: Decimal) -> Decimal { return self - other } public func advanced(by n: Decimal) -> Decimal { return self + n } } extension Decimal { public init(_ value: UInt8) { self.init(UInt64(value)) } public init(_ value: Int8) { self.init(Int64(value)) } public init(_ value: UInt16) { self.init(UInt64(value)) } public init(_ value: Int16) { self.init(Int64(value)) } public init(_ value: UInt32) { self.init(UInt64(value)) } public init(_ value: Int32) { self.init(Int64(value)) } public init(_ value: Double) { if value.isNaN { self = Decimal.nan } else if value == 0.0 { self = Decimal(_exponent: 0, _length: 0, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } else { let negative = value < 0 var val = negative ? -1 * value : value var exponent = 0 while val < Double(UInt64.max - 1) { val *= 10.0 exponent -= 1 } while Double(UInt64.max - 1) < val { val /= 10.0 exponent += 1 } var mantissa = UInt64(val) var i = UInt32(0) // this is a bit ugly but it is the closest approximation of the C initializer that can be expressed here. _mantissa = (0, 0, 0, 0, 0, 0, 0, 0) while mantissa != 0 && i < 8 /* NSDecimalMaxSize */ { switch i { case 0: _mantissa.0 = UInt16(mantissa & 0xffff) case 1: _mantissa.1 = UInt16(mantissa & 0xffff) case 2: _mantissa.2 = UInt16(mantissa & 0xffff) case 3: _mantissa.3 = UInt16(mantissa & 0xffff) case 4: _mantissa.4 = UInt16(mantissa & 0xffff) case 5: _mantissa.5 = UInt16(mantissa & 0xffff) case 6: _mantissa.6 = UInt16(mantissa & 0xffff) case 7: _mantissa.7 = UInt16(mantissa & 0xffff) default: fatalError("initialization overflow") } mantissa = mantissa >> 16 i += 1 } _length = i _isNegative = negative ? 1 : 0 _isCompact = 0 _exponent = Int32(exponent) NSDecimalCompact(&self) } } public init(_ value: UInt64) { self.init(Double(value)) } public init(_ value: Int64) { self.init(Double(value)) } public init(_ value: UInt) { self.init(UInt64(value)) } public init(_ value: Int) { self.init(Int64(value)) } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public static var infinity: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public static var signalingNaN: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") } public var isSignalingNaN: Bool { return false } public static var nan: Decimal { return quietNaN } public static var quietNaN: Decimal { return Decimal(_exponent: 0, _length: 0, _isNegative: 1, _isCompact: 0, _reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0)) } /// The IEEE 754 "class" of this type. public var floatingPointClass: FloatingPointClassification { if _length == 0 && _isNegative == 1 { return .quietNaN } else if _length == 0 { return .positiveZero } // NSDecimal does not really represent normal and subnormal in the same manner as the IEEE standard, for now we can probably claim normal for any nonzero, nonnan values if _isNegative == 1 { return .negativeNormal } else { return .positiveNormal } } /// `true` iff `self` is negative. public var isSignMinus: Bool { return _isNegative != 0 } /// `true` iff `self` is normal (not zero, subnormal, infinity, or /// NaN). public var isNormal: Bool { return !isZero && !isInfinite && !isNaN } /// `true` iff `self` is zero, subnormal, or normal (not infinity /// or NaN). public var isFinite: Bool { return !isNaN } /// `true` iff `self` is +0.0 or -0.0. public var isZero: Bool { return _length == 0 && _isNegative == 0 } /// `true` iff `self` is subnormal. public var isSubnormal: Bool { return false } /// `true` iff `self` is infinity. public var isInfinite: Bool { return false } /// `true` iff `self` is NaN. public var isNaN: Bool { return _length == 0 && _isNegative == 1 } /// `true` iff `self` is a signaling NaN. public var isSignaling: Bool { return false } } extension Decimal : CustomStringConvertible { public init?(string: String, locale: Locale? = nil) { let scan = Scanner(string: string) var theDecimal = Decimal() scan.locale = locale if !scan.scanDecimal(&theDecimal) { return nil } self = theDecimal } public var description: String { var val = self return NSDecimalString(&val, nil) } } extension Decimal : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDecimalNumber { return NSDecimalNumber(decimal: self) } public static func _forceBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSDecimalNumber, result: inout Decimal?) -> Bool { result = input.decimalValue return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDecimalNumber?) -> Decimal { guard let src = source else { return Decimal(_exponent: 0, _length: 0, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0)) } return src.decimalValue } } extension Decimal : Codable { private enum CodingKeys : Int, CodingKey { case exponent case length case isNegative case isCompact case mantissa } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let exponent = try container.decode(CInt.self, forKey: .exponent) let length = try container.decode(CUnsignedInt.self, forKey: .length) let isNegative = try container.decode(Bool.self, forKey: .isNegative) let isCompact = try container.decode(Bool.self, forKey: .isCompact) var mantissaContainer = try container.nestedUnkeyedContainer(forKey: .mantissa) var mantissa: (CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort) = (0,0,0,0,0,0,0,0) mantissa.0 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.1 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.2 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.3 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.4 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.5 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.6 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.7 = try mantissaContainer.decode(CUnsignedShort.self) self.init(_exponent: exponent, _length: length, _isNegative: CUnsignedInt(isNegative ? 1 : 0), _isCompact: CUnsignedInt(isCompact ? 1 : 0), _reserved: 0, _mantissa: mantissa) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(_exponent, forKey: .exponent) try container.encode(_length, forKey: .length) try container.encode(_isNegative == 0 ? false : true, forKey: .isNegative) try container.encode(_isCompact == 0 ? false : true, forKey: .isCompact) var mantissaContainer = container.nestedUnkeyedContainer(forKey: .mantissa) try mantissaContainer.encode(_mantissa.0) try mantissaContainer.encode(_mantissa.1) try mantissaContainer.encode(_mantissa.2) try mantissaContainer.encode(_mantissa.3) try mantissaContainer.encode(_mantissa.4) try mantissaContainer.encode(_mantissa.5) try mantissaContainer.encode(_mantissa.6) try mantissaContainer.encode(_mantissa.7) } }
apache-2.0
a8415bed8b363192415d560d13edf3e2
34.617702
219
0.589806
4.329899
false
false
false
false
adow/SlideBoxDemo
SideBoxDemo/SlideBoxCollectionLayout.swift
1
6643
// // SideBoxCollectionLayout.swift // SideBoxDemo // // Created by 秦 道平 on 15/11/13. // Copyright © 2015年 秦 道平. All rights reserved. // import UIKit func divmod(a:CGFloat,b:CGFloat) -> (quotient:CGFloat, remainder:CGFloat){ return (a / b, a % b) } // MARK: - LayoutAttributes class SlideBoxCollectionLayoutAttributes:UICollectionViewLayoutAttributes { var ratio:CGFloat! { didSet{ let scale = max(min(1.1, ratio), 0.0) let transform_scale = CGAffineTransformMakeScale(scale, scale) if ratio > 1.0 { var translate : CGFloat! if ratio >= 1.1 { translate = -1.0 * (self.screenSize.width / 2.0 + self.cardWidth / 2.0) } else { translate = -1.0 * (ratio - floor(ratio)) * pageDistance * 10.0 if translate == 0.0 { translate = -pageDistance } } // print("\(a),\(ratio),\(scale), \(translate)") self.transform = CGAffineTransformTranslate(transform_scale, translate, 0.0) } else { // print("\(a),\(ratio),\(scale)") self.transform = transform_scale } } } lazy var screenSize:CGSize = UIScreen.mainScreen().bounds.size var pageDistance:CGFloat! var cardWidth:CGFloat! var cardHeight:CGFloat! class func attribuatesForIndexPath(indexPath:NSIndexPath, pageDistance:CGFloat, cardWidth:CGFloat,cardHeight: CGFloat) -> SlideBoxCollectionLayoutAttributes{ let attributes = SlideBoxCollectionLayoutAttributes(forCellWithIndexPath: indexPath) attributes.pageDistance = pageDistance attributes.cardWidth = cardWidth attributes.cardHeight = cardHeight return attributes } override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! SlideBoxCollectionLayoutAttributes copy.screenSize = self.screenSize copy.pageDistance = self.pageDistance copy.cardWidth = self.cardWidth copy.cardHeight = self.cardHeight copy.ratio = ratio return copy } } // MARK: - Layout class SlideBoxCollectionLayout: UICollectionViewFlowLayout { let pageDistance : CGFloat = ceil(UIScreen.mainScreen().bounds.width * 0.5 + UIScreen.mainScreen().bounds.width * 0.6) let cardWidth : CGFloat = UIScreen.mainScreen().bounds.width * 0.9 let cardHeight : CGFloat = UIScreen.mainScreen().bounds.height * 0.9 private var attributesList : [UICollectionViewLayoutAttributes] = [] /// 用来在滚动时限定在一个固定的位置 private var targetOffsetX : CGFloat = 0.0 override init() { super.init() self.scrollDirection = UICollectionViewScrollDirection.Horizontal } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func collectionViewContentSize() -> CGSize { let numberOfItems = self.collectionView!.numberOfItemsInSection(0) return CGSizeMake(self.pageDistance * CGFloat(numberOfItems) + self.collectionView!.bounds.width, self.collectionView!.bounds.width) } override func prepareLayout() { super.prepareLayout() var array : [UICollectionViewLayoutAttributes] = [] let numberOfItems = self.collectionView!.numberOfItemsInSection(0) let offset_x = self.collectionView!.contentOffset.x let center_x : CGFloat = self.collectionView!.bounds.width / 2.0 + offset_x let center_y : CGFloat = self.collectionView!.bounds.height / 2.0 let center = CGPointMake(center_x, center_y) let bounds = CGRectMake(0.0, 0.0, self.cardWidth, self.cardHeight) for a in 0..<numberOfItems { /// 计算 ratio, ratio 使用来确定真正位置的参数,每个 cell 直接差 0.1,还要计算当前滚动的位置 let ratio = 1.0 - ( CGFloat(a) * 0.1) + (offset_x / pageDistance) / 10.0 let indexPath = NSIndexPath(forItem: a, inSection: 0) let attributes = SlideBoxCollectionLayoutAttributes.attribuatesForIndexPath(indexPath, pageDistance: pageDistance, cardWidth: cardWidth, cardHeight: cardHeight) attributes.center = center attributes.bounds = bounds attributes.zIndex = 10000 - a attributes.ratio = ratio array.append(attributes) } self.attributesList = array } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return self.attributesList } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return self.attributesList[indexPath.row] } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override class func layoutAttributesClass() -> AnyClass { return SlideBoxCollectionViewCell.self } /// 确保每次只滚动一页的距离,不管实际滚动多少,只要和上一次位置距离超过 30 就进行页面跳转(滚动) override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { // NSLog("propsed:\(proposedContentOffset),velocity:\(velocity),offset:\(self.collectionView!.contentOffset)") var targetContentOffset = proposedContentOffset if abs(self.collectionView!.contentOffset.x - proposedContentOffset.x) >= 30.0 { /// 往后一页 if velocity.x > 0.0 { self.targetOffsetX += self.pageDistance } /// 往前一页 else { self.targetOffsetX -= self.pageDistance } self.targetOffsetX = max(self.targetOffsetX, 0.0) self.targetOffsetX = min(self.collectionView!.contentSize.width - self.collectionView!.bounds.width, self.targetOffsetX) } /// 如果滚动距离太小,就回到原来的位置 targetContentOffset.x = self.targetOffsetX // NSLog("targetOffsetX:%f",self.targetOffsetX) return targetContentOffset } override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { // print("disappearing:\(itemIndexPath.row)") return nil } }
mit
d5187cfdca750b0c3025da7142df49d5
41.370861
172
0.643795
4.749814
false
false
false
false
soyabi/wearableD
WearableD/HomeViewController.swift
2
2750
// // ViewController.swift // WearableD // // Created by Zhang, Modesty on 1/9/15. // Copyright (c) 2015 Intuit. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleWatchKitNotification:", name: "WearableDWKMsg", object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { // self.navigationController?.setNavigationBarHidden(true, animated: animated) self.title = "Wearable Transcript" super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { // self.navigationController?.setNavigationBarHidden(false, animated: animated) self.title = "Home" super.viewWillDisappear(animated) } func handleWatchKitNotification(notification: NSNotification) { println("Got notification: \(notification.object)") if let userInfo = notification.object as? [String:String] { if let viewNameStr = userInfo["viewName"] { let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let topVC = self.navigationController?.topViewController var bleVC: UIViewController? = nil if viewNameStr == "requestDoc" { if (topVC is CentralViewController) == false { self.returnToRoot() bleVC = mainStoryboard.instantiateViewControllerWithIdentifier("CentralViewController") as! CentralViewController } } else if viewNameStr == "shareDoc" { if (topVC is PeripheralViewController) == false { self.returnToRoot() bleVC = mainStoryboard.instantiateViewControllerWithIdentifier("PeripheralViewController") as! PeripheralViewController } } if bleVC != nil { self.navigationController?.pushViewController(bleVC!, animated: true) } } } } func returnToRoot() { self.dismissViewControllerAnimated(true, completion: nil) self.navigationController?.popToRootViewControllerAnimated(true) } }
apache-2.0
5fed0124e12d87d740c359e5ce755c80
35.184211
143
0.610182
5.693582
false
false
false
false
coletiv/snap-experiment
Snap Experiment/source/CameraPreviewView.swift
1
2038
/* CameraPreviewView.Swift coletiv-snap-experiment Copyright (c) 2016 Coletiv 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 class CameraPreviewView: UIView { var cameraPreviewLayer: CALayer? // MARK: Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = .blackColor() } override func layoutSubviews() { super.layoutSubviews() if let previewLayer = cameraPreviewLayer { previewLayer.frame = bounds } } // MARK: Camera Preview Layer func previewLayer() -> CALayer { return layer } func addCameraPreviewLayer(cameraPreviewLayer: CALayer) { layer.masksToBounds = true layer.addSublayer(cameraPreviewLayer) self.cameraPreviewLayer = cameraPreviewLayer } func showUnsupportedView() { // TODO: implement a placeholder view when camera is not supported } }
mit
a9e0fe797d08d386d4ceab66b7f01207
29.41791
81
0.704122
5.225641
false
false
false
false
vhbit/MastodonKit
Tests/MastodonKitTests/ResourcesTests.swift
1
9696
import XCTest @testable import MastodonKit typealias ParserFunctionType<Model> = (Any) -> Model class ResourcesTests: XCTestCase { // MARK: AccountResource func testAccountResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Account.json") let parsed = Resource<Account>.parser(json: fixture) XCTAssertNotNil(parsed) } func testAccountResourceWithInvalidArray() { let parsed = Resource<Account>.parser(json: []) XCTAssertNil(parsed) } func testAccountResourceWithInvalidDictionary() { let parsed = Resource<Account>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: AccountsResource func testAccountsResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Accounts.json") let parsed = Resource<[Account]>.parser(json: fixture) XCTAssertEqual(parsed.count, 2) } func testAccountsResourceWithInvalidArray() { let parsed = Resource<[Account]>.parser(json: []) XCTAssertEqual(parsed.count, 0) } func testAccountsResourceWithInvalidDictionary() { let parsed = Resource<[Account]>.parser(json: [:]) XCTAssertEqual(parsed.count, 0) } // MARK: AttachmentResource func testAttachmentResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Attachment.json") let parsed = Resource<Attachment>.parser(json: fixture) XCTAssertNotNil(parsed) } func testAttachmentResourceWithInvalidArray() { let parsed = Resource<Attachment>.parser(json: []) XCTAssertNil(parsed) } func testAttachmentResourceWithInvalidDictionary() { let parsed = Resource<Attachment>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: CardResource func testCardResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Card.json") let parsed = Resource<Card>.parser(json: fixture) XCTAssertNotNil(parsed) } func testCardResourceWithInvalidArray() { let parsed = Resource<Card>.parser(json: []) XCTAssertNil(parsed) } func testCardResourceWithInvalidDictionary() { let parsed = Resource<Card>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: ClientApplicationResource func testClientApplicationResource() { let fixture = try! Fixture.load(fileName: "Fixtures/ClientApplication.json") let parsed = Resource<ClientApplication>.parser(json: fixture) XCTAssertNotNil(parsed) } func testClientApplicationResourceWithInvalidArray() { let parsed = Resource<ClientApplication>.parser(json: []) XCTAssertNil(parsed) } func testClientApplicationResourceWithInvalidDictionary() { let parsed = Resource<ClientApplication>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: ContextResource func testContextResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Context.json") let parsed = Resource<Context>.parser(json: fixture) XCTAssertNotNil(parsed) } func testContextResourceWithInvalidArray() { let parsed = Resource<Context>.parser(json: []) XCTAssertNil(parsed) } func testContextResourceWithInvalidDictionary() { let parsed = Resource<Context>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: InstanceResource func testInstanceResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Instance.json") let parsed = Resource<Instance>.parser(json: fixture) XCTAssertNotNil(parsed) } func testInstanceResourceWithInvalidArray() { let parsed = Resource<Instance>.parser(json: []) XCTAssertNil(parsed) } func testInstanceResourceWithInvalidDictionary() { let parsed = Resource<Instance>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: LoginSettingsResource func testLoginSettingsResource() { let fixture = try! Fixture.load(fileName: "Fixtures/LoginSettings.json") let parsed = Resource<LoginSettings>.parser(json: fixture) XCTAssertNotNil(parsed) } func testLoginSettingsResourceWithInvalidArray() { let parsed = Resource<LoginSettings>.parser(json: []) XCTAssertNil(parsed) } func testLoginSettingsResourceWithInvalidDictionary() { let parsed = Resource<LoginSettings>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: NotificationResource func testNotificationResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Notification.json") let parsed = Resource<MastodonKit.Notification>.parser(json: fixture) XCTAssertNotNil(parsed) } func testNotificationResourceWithInvalidArray() { let parsed = Resource<MastodonKit.Notification>.parser(json: []) XCTAssertNil(parsed) } func testNotificationResourceWithInvalidDictionary() { let parsed = Resource<MastodonKit.Notification>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: NotificationsResource func testNotificationsResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Notifications.json") let parsed = Resource<[MastodonKit.Notification]>.parser(json: fixture) XCTAssertEqual(parsed.count, 2) } func testNotificationsResourceWithInvalidArray() { let parsed = Resource<[MastodonKit.Notification]>.parser(json: []) XCTAssertEqual(parsed.count, 0) } func testNotificationsResourceWithInvalidDictionary() { let parsed = Resource<[MastodonKit.Notification]>.parser(json: [:]) XCTAssertEqual(parsed.count, 0) } // MARK: RelationshipResource func testRelationshipResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Relationship.json") let parsed = Resource<Relationship>.parser(json: fixture) XCTAssertNotNil(parsed) } func testRelationshipResourceWithInvalidArray() { let parsed = Resource<Relationship>.parser(json: []) XCTAssertNil(parsed) } func testRelationshipResourceWithInvalidDictionary() { let parsed = Resource<Relationship>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: RelationshipsResource func testRelationshipsResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Relationships.json") let parsed = Resource<[Relationship]>.parser(json: fixture) XCTAssertEqual(parsed.count, 2) } func testRelationshipsResourceWithInvalidArray() { let parsed = Resource<[Relationship]>.parser(json: []) XCTAssertEqual(parsed.count, 0) } func testRelationshipsResourceWithInvalidDictionary() { let parsed = Resource<[Relationship]>.parser(json: [:]) XCTAssertEqual(parsed.count, 0) } // MARK: ReportResource func testReportResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Report.json") let parsed = Resource<Report>.parser(json: fixture) XCTAssertNotNil(parsed) } func testReportResourceWithInvalidArray() { let parsed = Resource<Report>.parser(json: []) XCTAssertNil(parsed) } func testReportResourceWithInvalidDictionary() { let parsed = Resource<Report>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: ReportsResource func testReportsResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Reports.json") let parsed = Resource<[Report]>.parser(json: fixture) XCTAssertEqual(parsed.count, 2) } func testReportsResourceWithInvalidArray() { let parsed = Resource<[Report]>.parser(json: []) XCTAssertEqual(parsed.count, 0) } func testReportsResourceWithInvalidDictionary() { let parsed = Resource<[Report]>.parser(json: [:]) XCTAssertEqual(parsed.count, 0) } // MARK: ResultsResource func testResultsResource() { let fixture = try! Fixture.load(fileName: "Fixtures/ResultsWithoutNull.json") let parsed = Resource<Results>.parser(json: fixture) XCTAssertNotNil(parsed) } func testResultsResourceWithInvalidArray() { let parsed = Resource<Results>.parser(json: []) XCTAssertNil(parsed) } func testResultsResourceWithEmptyDictionary() { let parsed = Resource<Results>.parser(json: [:]) XCTAssertNotNil(parsed) } // MARK: StatusResource func testStatusResource() { let fixture = try! Fixture.load(fileName: "Fixtures/StatusWithoutNull.json") let parsed = Resource<Status>.parser(json: fixture) XCTAssertNotNil(parsed) } func testStatusResourceWithInvalidArray() { let parsed = Resource<Status>.parser(json: []) XCTAssertNil(parsed) } func testStatusResourceWithInvalidDictionary() { let parsed = Resource<Status>.parser(json: [:]) XCTAssertNil(parsed) } // MARK: TimelineResource func testTimelineResource() { let fixture = try! Fixture.load(fileName: "Fixtures/Timeline.json") let parsed = Resource<[Status]>.parser(json: fixture) XCTAssertEqual(parsed.count, 2) } func testTimelineResourceWithInvalidArray() { let parsed = Resource<[Status]>.parser(json: []) XCTAssertEqual(parsed.count, 0) } func testTimelineResourceWithInvalidDictionary() { let parsed = Resource<[Status]>.parser(json: [:]) XCTAssertEqual(parsed.count, 0) } }
mit
171802aa132ea79362e95ab812ead09b
25.710744
85
0.660891
4.838323
false
true
false
false
mortorqrobotics/MorTeam-ios
MorTeam/Event.swift
1
1556
// // Event.swift // MorTeam // // Created by arvin zadeh on 10/12/16. // Copyright © 2016 MorTorq. All rights reserved. // import Foundation class Event { let _id: String let name: String let description: String? let audience: Audience let date: String let day: Int //Very helpful let month: Int let year: Int var attendance: [AttendanceObject] init(eventJSON: JSON){ self._id = String(describing: eventJSON["_id"]) self.name = String(describing: eventJSON["name"]) self.description = String(describing: eventJSON["description"]) self.audience = Audience(audienceJSON: eventJSON["audience"]) self.date = String(describing: eventJSON["date"]) var allAttendance = [AttendanceObject]() for(_, json):(String, JSON) in eventJSON["attendance"] { allAttendance.append(AttendanceObject(objectJSON: json)) } self.attendance = allAttendance let formatter = DateFormatter() formatter.locale = Locale(identifier: "UTC") formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let date = formatter.date(from: self.date) let day = NSCalendar.current.component(.day, from: date!) let month = NSCalendar.current.component(.month, from: date!) let year = NSCalendar.current.component(.year, from: date!) self.year = year self.day = day self.month = month } }
mit
4c29573cf511e037fc4d1e744a5da6f7
30.734694
71
0.619293
4.102902
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/LowEnergyRfTxPathCompensationValue.swift
1
1343
// // LowEnergyRfTxPathCompensationValue.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // /// RF_Tx_Path_Compensation_Value /// /// Size: 2 Octets (signed integer) /// Range: -128.0 dB (0xFB00) ≤ N ≤ 128.0 dB (0x0500) /// Units: 0.1 dB @frozen public struct LowEnergyRfTxPathCompensationValue: RawRepresentable, Equatable, Hashable, Comparable { public static let min = LowEnergyRfTxPathCompensationValue(-128) public static let max = LowEnergyRfTxPathCompensationValue(128) public let rawValue: Int16 public init?(rawValue: Int16) { guard rawValue >= LowEnergyRfTxPathCompensationValue.min.rawValue, rawValue <= LowEnergyRfTxPathCompensationValue.max.rawValue else { return nil } assert((LowEnergyRfTxPathCompensationValue.min.rawValue ... LowEnergyRfTxPathCompensationValue.max.rawValue).contains(rawValue)) self.rawValue = rawValue } // Private, unsafe private init(_ rawValue: Int16) { self.rawValue = rawValue } // Comparable public static func < (lhs: LowEnergyRfTxPathCompensationValue, rhs: LowEnergyRfTxPathCompensationValue) -> Bool { return lhs.rawValue < rhs.rawValue } }
mit
aff9da6b5065f262a69b5ffadca986ef
29.409091
136
0.675635
3.99403
false
false
false
false
SheffieldKevin/SwiftSVG
SwiftSVG/SVGProcessor.swift
1
25063
// // SVGProcessor.swift // SwiftSVGTestNT // // Created by Jonathan Wight on 2/25/15. // Copyright (c) 2015 No. All rights reserved. // import Foundation import SwiftGraphics import SwiftParsing public class SVGProcessor { public class State { var document: SVGDocument? var elementsByID: [String: SVGElement] = [: ] var events: [Event] = [] } public struct Event { enum Severity { case debug case info case warning case error } let severity: Severity let message: String } public enum Error: ErrorType { case corruptXML case expectedSVGElementNotFound } public init() { } public func processXMLDocument(xmlDocument: NSXMLDocument) throws -> SVGDocument? { let rootElement = xmlDocument.rootElement()! let state = State() let document = try self.processSVGElement(rootElement, state: state) as? SVGDocument if state.events.count > 0 { for event in state.events { print(event) } } return document } public func processSVGDocument(xmlElement: NSXMLElement, state: State) throws -> SVGDocument { let document = SVGDocument() state.document = document // Version. if let version = xmlElement["version"]?.stringValue { switch version { case "1.1": document.profile = .full document.version = SVGDocument.Version(majorVersion: 1, minorVersion: 1) default: break } xmlElement["version"] = nil } // Viewbox. if let viewbox = xmlElement["viewBox"]?.stringValue { let OPT_COMMA = zeroOrOne(COMMA).makeStripped() let VALUE_LIST = RangeOf(min: 4, max: 4, subelement: (cgFloatValue + OPT_COMMA).makeStripped().makeFlattened()) // TODO: ! can and will crash with bad data. let values: [CGFloat] = (try! VALUE_LIST.parse(viewbox).value as? [Any])!.map() { return $0 as! CGFloat } let (x, y, width, height) = (values[0], values[1], values[2], values[3]) document.viewBox = CGRect(x: x, y: y, width: width, height: height) xmlElement["viewBox"] = nil } else if let _ = xmlElement["width"]?.stringValue, let _ = xmlElement["height"]?.stringValue { let width = try SVGProcessor.stringToCGFloat(xmlElement["width"]?.stringValue) let height = try SVGProcessor.stringToCGFloat(xmlElement["height"]?.stringValue) let x = try SVGProcessor.stringToCGFloat(xmlElement["x"]?.stringValue, defaultVal: 0.0) let y = try SVGProcessor.stringToCGFloat(xmlElement["y"]?.stringValue, defaultVal: 0.0) document.viewBox = CGRect(x: x, y: y, width: width, height: height) } xmlElement["width"] = nil xmlElement["height"] = nil xmlElement["x"] = nil xmlElement["y"] = nil guard let nodes = xmlElement.children else { return document } for node in nodes where node is NSXMLElement { if let svgElement = try self.processSVGElement(node as! NSXMLElement, state: state) { svgElement.parent = document document.children.append(svgElement) } } xmlElement.setChildren(nil) return document } public func processSVGElement(xmlElement: NSXMLElement, state: State) throws -> SVGElement? { var svgElement: SVGElement? = nil guard let name = xmlElement.name else { throw Error.corruptXML } switch name { // case "defs": // svgElement = try processDEFS(xmlElement, state: state) case "svg": svgElement = try processSVGDocument(xmlElement, state: state) case "g": svgElement = try processSVGGroup(xmlElement, state: state) case "path": svgElement = try processSVGPath(xmlElement, state: state) case "line": svgElement = try processSVGLine(xmlElement, state: state) case "circle": svgElement = try processSVGCircle(xmlElement, state: state) case "rect": svgElement = try processSVGRect(xmlElement, state: state) case "ellipse": svgElement = try processSVGEllipse(xmlElement, state: state) case "polygon": svgElement = try processSVGPolygon(xmlElement, state:state) case "polyline": svgElement = try processSVGPolyline(xmlElement, state:state) case "text": svgElement = try processSVGText(xmlElement) case "title": state.document!.title = xmlElement.stringValue as String? case "desc": state.document!.documentDescription = xmlElement.stringValue as String? default: state.events.append(Event(severity: .warning, message: "Unhandled element \(xmlElement.name)")) return nil } if let svgElement = svgElement { svgElement.textStyle = try processTextStyle(xmlElement) svgElement.style = try processStyle(xmlElement, svgElement: svgElement) svgElement.transform = try processTransform(xmlElement) if let id = xmlElement["id"]?.stringValue { svgElement.id = id if state.elementsByID[id] != nil { state.events.append(Event(severity: .warning, message: "Duplicate elements with id \"\(id)\".")) } state.elementsByID[id] = svgElement xmlElement["id"] = nil } if xmlElement.attributes?.count > 0 { state.events.append(Event(severity: .warning, message: "Unhandled attributes: \(xmlElement))")) svgElement.xmlElement = xmlElement } } return svgElement } public func processDEFS(xmlElement: NSXMLElement, state: State) throws -> SVGElement? { // A def element can be children of documents and groups. // Any member of def elements should be accessible anywhere within the SVGDocument. guard let nodes = xmlElement.children else { throw Error.corruptXML } // I suspect that we might need a seperate processor for members of the defs element. var defElements = [SVGElement]() for node in nodes where node is NSXMLElement { if let svgElement = try self.processSVGElement(node as! NSXMLElement, state: state) { defElements.append(svgElement) } } return nil } public func processSVGGroup(xmlElement: NSXMLElement, state: State) throws -> SVGGroup? { guard let nodes = xmlElement.children else { return .None } var children = [SVGElement]() // A commented out <!-- --> node comes in as a NSXMLNode which causes crashes here. for node in nodes where node is NSXMLElement { if let svgElement = try self.processSVGElement(node as! NSXMLElement, state: state) { children.append(svgElement) } } let group = SVGGroup(children: children) xmlElement.setChildren(nil) return group } public func processSVGPath(xmlElement: NSXMLElement, state: State) throws -> SVGPath? { guard let string = xmlElement["d"]?.stringValue else { throw Error.expectedSVGElementNotFound } var pathArray = NSMutableArray(capacity: 0) let path = MICGPathFromSVGPath(string, pathArray: &pathArray) xmlElement["d"] = nil let svgElement = SVGPath(path: path, miPath: makePathDictionary(pathArray)) return svgElement } private class func stringToCGFloat(string: String?) throws -> CGFloat { guard let string = string else { throw Error.expectedSVGElementNotFound } // This is probably a bit reckless. let string2 = string.stringByTrimmingCharactersInSet(NSCharacterSet.lowercaseLetterCharacterSet()) guard let value = NSNumberFormatter().numberFromString(string2)?.doubleValue else { throw Error.corruptXML } return CGFloat(value) } private class func stringToOptionalCGFloat(string: String?) throws -> CGFloat? { guard let string = string else { return Optional.None } let string2 = string.stringByTrimmingCharactersInSet(NSCharacterSet.lowercaseLetterCharacterSet()) guard let value = NSNumberFormatter().numberFromString(string2)?.doubleValue else { throw Error.corruptXML } return CGFloat(value) } private class func stringToCGFloat(string: String?, defaultVal: CGFloat) throws -> CGFloat { guard let string = string else { return defaultVal } let string2 = string.stringByTrimmingCharactersInSet(NSCharacterSet.lowercaseLetterCharacterSet()) guard let value = NSNumberFormatter().numberFromString(string2)?.doubleValue else { throw Error.corruptXML } return CGFloat(value) } public func processSVGPolygon(xmlElement: NSXMLElement, state: State) throws -> SVGPolygon? { guard let pointsString = xmlElement["points"]?.stringValue else { throw Error.expectedSVGElementNotFound } let points = try parseListOfPoints(pointsString) xmlElement["points"] = nil let svgElement = SVGPolygon(points: points) return svgElement } public func processSVGPolyline(xmlElement: NSXMLElement, state: State) throws -> SVGPolyline? { guard let pointsString = xmlElement["points"]?.stringValue else { throw Error.expectedSVGElementNotFound } let points = try parseListOfPoints(pointsString) xmlElement["points"] = nil let svgElement = SVGPolyline(points: points) return svgElement } public func processSVGLine(xmlElement: NSXMLElement, state: State) throws -> SVGLine? { let x1 = try SVGProcessor.stringToCGFloat(xmlElement["x1"]?.stringValue) let y1 = try SVGProcessor.stringToCGFloat(xmlElement["y1"]?.stringValue) let x2 = try SVGProcessor.stringToCGFloat(xmlElement["x2"]?.stringValue) let y2 = try SVGProcessor.stringToCGFloat(xmlElement["y2"]?.stringValue) xmlElement["x1"] = nil xmlElement["y1"] = nil xmlElement["x2"] = nil xmlElement["y2"] = nil let startPoint = CGPoint(x: x1, y: y1) let endPoint = CGPoint(x: x2, y: y2) let svgElement = SVGLine(startPoint: startPoint, endPoint: endPoint) return svgElement } public func processSVGCircle(xmlElement: NSXMLElement, state: State) throws -> SVGCircle? { let cx = try SVGProcessor.stringToCGFloat(xmlElement["cx"]?.stringValue) let cy = try SVGProcessor.stringToCGFloat(xmlElement["cy"]?.stringValue) let r = try SVGProcessor.stringToCGFloat(xmlElement["r"]?.stringValue) xmlElement["cx"] = nil xmlElement["cy"] = nil xmlElement["r"] = nil let svgElement = SVGCircle(center: CGPoint(x: cx, y: cy), radius: r) return svgElement } public func processSVGEllipse(xmlElement: NSXMLElement, state: State) throws -> SVGEllipse? { let cx = try SVGProcessor.stringToCGFloat(xmlElement["cx"]?.stringValue, defaultVal: 0.0) let cy = try SVGProcessor.stringToCGFloat(xmlElement["cy"]?.stringValue, defaultVal: 0.0) let rx = try SVGProcessor.stringToCGFloat(xmlElement["rx"]?.stringValue) let ry = try SVGProcessor.stringToCGFloat(xmlElement["ry"]?.stringValue) xmlElement["cx"] = nil xmlElement["cy"] = nil xmlElement["rx"] = nil xmlElement["ry"] = nil let rect = CGRect(x: cx - rx, y: cy - ry, width: 2 * rx, height: 2 * ry) let svgElement = SVGEllipse(rect: rect) return svgElement } public func processSVGRect(xmlElement: NSXMLElement, state: State) throws -> SVGRect? { let x = try SVGProcessor.stringToCGFloat(xmlElement["x"]?.stringValue, defaultVal: 0.0) let y = try SVGProcessor.stringToCGFloat(xmlElement["y"]?.stringValue, defaultVal: 0.0) let width = try SVGProcessor.stringToCGFloat(xmlElement["width"]?.stringValue) let height = try SVGProcessor.stringToCGFloat(xmlElement["height"]?.stringValue) let rx = try SVGProcessor.stringToOptionalCGFloat(xmlElement["rx"]?.stringValue) let ry = try SVGProcessor.stringToOptionalCGFloat(xmlElement["ry"]?.stringValue) xmlElement["x"] = nil xmlElement["y"] = nil xmlElement["width"] = nil xmlElement["height"] = nil xmlElement["rx"] = nil xmlElement["ry"] = nil let svgElement = SVGRect(rect: CGRect(x: x, y: y, w: width, h: height), rx: rx, ry: ry) return svgElement } private func getAttributeWithKey(xmlElement: NSXMLElement, attribute: String) -> String? { if let name = xmlElement[attribute]?.stringValue { return name } // lets see if the font family name is in the style attribute. guard let style = xmlElement["style"]?.stringValue else { return Optional.None } let seperators = NSCharacterSet(charactersInString: ";") let trimChars = NSCharacterSet.whitespaceAndNewlineCharacterSet() let parts = style.componentsSeparatedByCharactersInSet(seperators) let pairSeperator = NSCharacterSet(charactersInString: ":") for part in parts { let pair = part.componentsSeparatedByCharactersInSet(pairSeperator) if pair.count != 2 { continue } let propertyName = pair[0].stringByTrimmingCharactersInSet(trimChars) let value = pair[1].stringByTrimmingCharactersInSet(trimChars) if propertyName == attribute { return value } } return Optional.None } func processSVGTextSpan(xmlElement: NSXMLElement, textOrigin: CGPoint) throws -> SVGTextSpan? { let x = try SVGProcessor.stringToCGFloat(xmlElement["x"]?.stringValue, defaultVal: textOrigin.x) let y = try SVGProcessor.stringToCGFloat(xmlElement["y"]?.stringValue, defaultVal: textOrigin.y) let newOrigin = CGPoint(x: x, y: y) guard let string = xmlElement.stringValue else { throw Error.corruptXML } let textSpan = SVGTextSpan(string: string, textOrigin: newOrigin) let textStyle = try self.processTextStyle(xmlElement) let style = try processStyle(xmlElement) let transform = try processTransform(xmlElement) textSpan.textStyle = textStyle textSpan.style = style textSpan.transform = transform return textSpan } public func processSVGText(xmlElement: NSXMLElement) throws -> SVGSimpleText? { // Since I am not tracking the size of drawn text we can't do any text flow. // This means any text that isn't explicitly positioned we can't render. let x = try SVGProcessor.stringToCGFloat(xmlElement["x"]?.stringValue, defaultVal: 0.0) let y = try SVGProcessor.stringToCGFloat(xmlElement["y"]?.stringValue, defaultVal: 0.0) let textOrigin = CGPoint(x: x, y: y) xmlElement["x"] = nil xmlElement["y"] = nil guard let nodes = xmlElement.children where nodes.count > 0 else { throw Error.expectedSVGElementNotFound } let textSpans = try nodes.map { node -> SVGTextSpan? in if let textItem = node as? NSXMLElement { return try self.processSVGTextSpan(textItem, textOrigin: textOrigin) } else if let string = node.stringValue { return SVGTextSpan(string: string, textOrigin: textOrigin) } return nil } let flattenedTextSpans = textSpans.flatMap { $0 } xmlElement.setChildren(nil) if flattenedTextSpans.count > 0 { return SVGSimpleText(spans: flattenedTextSpans) } return nil } private class func processColorString(colorString: String) -> [NSObject : AnyObject]? { // Double optional. What? let colorDict = try? SVGColors.stringToColorDictionary(colorString) if let colorDict = colorDict { return colorDict } return nil } private class func processFillColor(colorString: String, svgElement: SVGElement? = nil) -> StyleElement? { if let svgElement = svgElement where colorString == "none" { svgElement.drawFill = false return nil } if let colorDict = processColorString(colorString), let color = SVGColors.colorDictionaryToCGColor(colorDict) { return StyleElement.fillColor(color) } else { return nil } } private class func processStrokeColor(colorString: String) -> StyleElement? { if let colorDict = processColorString(colorString), let color = SVGColors.colorDictionaryToCGColor(colorDict) { return StyleElement.strokeColor(color) } else { return nil } } private class func processPresentationAttribute(style: String, inout styleElements: [StyleElement], svgElement: SVGElement? = nil) throws { let seperators = NSCharacterSet(charactersInString: ";") let trimChars = NSCharacterSet.whitespaceAndNewlineCharacterSet() let parts = style.componentsSeparatedByCharactersInSet(seperators) let pairSeperator = NSCharacterSet(charactersInString: ":") let styles:[StyleElement?] = parts.map { let pair = $0.componentsSeparatedByCharactersInSet(pairSeperator) if pair.count != 2 { return nil } let propertyName = pair[0].stringByTrimmingCharactersInSet(trimChars) let value = pair[1].stringByTrimmingCharactersInSet(trimChars) switch(propertyName) { case "fill": return processFillColor(value, svgElement: svgElement) case "stroke": return processStrokeColor(value) case "stroke-width": let floatVal = try? SVGProcessor.stringToCGFloat(value) if let strokeValue = floatVal { return StyleElement.lineWidth(strokeValue) } return nil case "stroke-miterlimit": let floatVal = try? SVGProcessor.stringToCGFloat(value) if let miterLimit = floatVal { return StyleElement.miterLimit(miterLimit) } return nil case "display": if let svgElement = svgElement where value == "none" { svgElement.display = false } return nil default: return nil } } styles.forEach { if let theStyle = $0 { styleElements.append(theStyle) } } } public func processTextStyle(xmlElement: NSXMLElement) throws -> TextStyle? { // We won't be scrubbing the style element after checking for font family and font size here. var textStyleElements: [TextStyleElement] = [] let fontFamily = self.getAttributeWithKey(xmlElement, attribute: "font-family") if let fontFamily = fontFamily { let familyName = fontFamily.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "'")) textStyleElements.append(TextStyleElement.fontFamily(familyName)) } xmlElement["font-family"] = nil let fontSizeString = self.getAttributeWithKey(xmlElement, attribute: "font-size") if let fontSizeString = fontSizeString { let fontSize = try SVGProcessor.stringToCGFloat(fontSizeString) textStyleElements.append(TextStyleElement.fontSize(fontSize)) } xmlElement["font-size"] = nil if textStyleElements.count > 0 { var textStyle = TextStyle() textStyleElements.forEach { textStyle.add($0) } return textStyle } return nil } public func processStyle(xmlElement: NSXMLElement, svgElement: SVGElement? = nil) throws -> SwiftGraphics.Style? { // http://www.w3.org/TR/SVG/styling.html var styleElements: [StyleElement] = [] if let value = xmlElement["style"]?.stringValue { try SVGProcessor.processPresentationAttribute(value, styleElements: &styleElements, svgElement: svgElement) xmlElement["style"] = nil } if let value = xmlElement["fill"]?.stringValue { if let styleElement = SVGProcessor.processFillColor(value, svgElement: svgElement) { styleElements.append(styleElement) } xmlElement["fill"] = nil } if let value = xmlElement["stroke"]?.stringValue { if let styleElement = SVGProcessor.processStrokeColor(value) { styleElements.append(styleElement) } xmlElement["stroke"] = nil } let stroke = try SVGProcessor.stringToOptionalCGFloat(xmlElement["stroke-width"]?.stringValue) if let strokeValue = stroke { styleElements.append(StyleElement.lineWidth(strokeValue)) } xmlElement["stroke-width"] = nil let mitreLimit = try SVGProcessor.stringToOptionalCGFloat(xmlElement["stroke-miterlimit"]?.stringValue) if let mitreLimitValue = mitreLimit { styleElements.append(StyleElement.miterLimit(mitreLimitValue)) } xmlElement["stroke-miterlimit"] = nil if let value = xmlElement["display"]?.stringValue { if let svgElement = svgElement where value == "none" { svgElement.display = false } xmlElement["display"] = nil } // if styleElements.count > 0 { return SwiftGraphics.Style(elements: styleElements) } else { return nil } } public func processTransform(xmlElement: NSXMLElement) throws -> Transform2D? { guard let value = xmlElement["transform"]?.stringValue else { return nil } let transform = try svgTransformAttributeStringToTransform(value) xmlElement["transform"] = nil return transform } // TODO: @schwa - I couldn't work out how to apply your parser to an array of points float,float /// Convert an even list of floats to CGPoints private func floatsToPoints(data: [Float]) throws -> [CGPoint] { guard data.count % 2 == 0 else { throw Error.corruptXML } var out : [CGPoint] = [] for var i = 0; i < data.count-1; i += 2 { out.append(CGPointMake(CGFloat(data[i]), CGFloat(data[i+1]))) } return out } /// Parse the list of points from a polygon/polyline entry private func parseListOfPoints(entry : String) throws -> [CGPoint] { // Split by all commas and whitespace, then group into coords of two floats let entry = entry.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let separating = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet() separating.addCharactersInString(",") let parts = entry.componentsSeparatedByCharactersInSet(separating).filter { !$0.isEmpty } return try floatsToPoints(parts.map({Float($0)!})) } } // MARK: - extension SVGProcessor.Event: CustomStringConvertible { public var description: String { get { switch severity { case .debug: return "DEBUG: \(message)" case .info: return "INFO: \(message)" case .warning: return "WARNING: \(message)" case .error: return "ERROR: \(message)" } } } }
bsd-2-clause
c73980da2aa37be25da214e4d7acb58f
38.656646
143
0.602362
5.025667
false
false
false
false
VernonVan/SmartClass
SmartClass/Paper/Paper Result/View/ResultChartViewController.swift
1
3183
// // ChartViewController.swift // SmartClass // // Created by FSQ on 16/5/20. // Copyright © 2016年 Vernon. All rights reserved. // import UIKit import Charts import RealmSwift class ResultChartViewController: UIViewController { var paper: Paper! @IBOutlet weak var chartView: BarChartView! let realm = try! Realm() var studentNumber = 0 override func viewDidLoad() { super.viewDidLoad() studentNumber = realm.objects(Student.self).count initChartView() setChartViewData() chartView.animate(yAxisDuration: 1.0) } func initChartView() { chartView.chartDescription?.text = "" chartView.maxVisibleCount = 20 chartView.pinchZoomEnabled = false chartView.doubleTapToZoomEnabled = false chartView.scaleXEnabled = false chartView.scaleYEnabled = false chartView.legend.enabled = true let xAxis = chartView.xAxis xAxis.labelPosition = .bottom xAxis.drawGridLinesEnabled = false let leftAxisFormatter = NumberFormatter() leftAxisFormatter.minimumFractionDigits = 0 leftAxisFormatter.maximumFractionDigits = 100 leftAxisFormatter.positiveSuffix = "%" leftAxisFormatter.negativeSuffix = "%" let leftAxis = chartView.leftAxis leftAxis.axisMinimum = 0 leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: leftAxisFormatter) let rightAxis = chartView.rightAxis rightAxis.enabled = false } func setChartViewData() { let questionCount = paper.questions.count var xVals = [String]() var yVals = [BarChartDataEntry]() var correctNumbers = [Double]() for _ in 0 ..< questionCount { correctNumbers.append(0) } for result in paper.results { let student = realm.objects(Student.self).filter("number = '\(result.number)'").first if student?.name == result.name { for correctNumber in result.correctQuestionNumbers { correctNumbers[correctNumber.number] += 1 } } } for index in 0 ..< questionCount { yVals.append(BarChartDataEntry(x: Double(index), y: correctNumbers[index] / Double(studentNumber) * 100)) (index == 0) ? xVals.append("第1题") : xVals.append("\(index+1)") } let dataSet = BarChartDataSet(values: yVals, label: "每道题的答对比例") dataSet.colors = ChartColorTemplates.material() dataSet.drawValuesEnabled = true let data = BarChartData(dataSets: [dataSet]) chartView.data = data chartView.xAxis.valueFormatter = XValsFormatter(xVals: xVals) chartView.xAxis.granularity = 1.0 } } class XValsFormatter: NSObject, IAxisValueFormatter { let xVals: [String] init(xVals: [String]) { self.xVals = xVals } func stringForValue(_ value: Double, axis: AxisBase?) -> String { return xVals[Int(value)] } }
mit
204116aeaaec6a8c4c6f16d6553cbf7b
27.214286
117
0.610759
5.047923
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveSwift/Sources/Scheduler.swift
3
19441
// // Scheduler.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2014-06-02. // Copyright (c) 2014 GitHub. All rights reserved. // import Dispatch import Foundation #if os(Linux) import let CDispatch.NSEC_PER_SEC #endif /// Represents a serial queue of work items. public protocol Scheduler: class { /// Enqueues an action on the scheduler. /// /// When the work is executed depends on the scheduler in use. /// /// - parameters: /// - action: The action to be scheduled. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(_ action: @escaping () -> Void) -> Disposable? } /// A particular kind of scheduler that supports enqueuing actions at future /// dates. public protocol DateScheduler: Scheduler { /// The current date, as determined by this scheduler. /// /// This can be implemented to deterministically return a known date (e.g., /// for testing purposes). var currentDate: Date { get } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: The start date. /// - action: A closure of the action to be performed. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? /// Schedules a recurring action at the given interval, beginning at the /// given date. /// /// - parameters: /// - date: The start date. /// - interval: A repetition interval. /// - leeway: Some delta for repetition. /// - action: A closure of the action to be performed. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? } /// A scheduler that performs all work synchronously. public final class ImmediateScheduler: Scheduler { public init() {} /// Immediately calls passed in `action`. /// /// - parameters: /// - action: A closure of the action to be performed. /// /// - returns: `nil`. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { action() return nil } } /// A scheduler that performs all work on the main queue, as soon as possible. /// /// If the caller is already running on the main queue when an action is /// scheduled, it may be run synchronously. However, ordering between actions /// will always be preserved. public final class UIScheduler: Scheduler { private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>() private static let dispatchSpecificValue = UInt8.max private static var __once: () = { DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey, value: dispatchSpecificValue) }() #if os(Linux) private var queueLength: Atomic<Int32> = Atomic(0) #else // `inout` references do not guarantee atomicity. Use `UnsafeMutablePointer` // instead. // // https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161205/004147.html private let queueLength: UnsafeMutablePointer<Int32> = { let memory = UnsafeMutablePointer<Int32>.allocate(capacity: 1) memory.initialize(to: 0) return memory }() deinit { queueLength.deinitialize() queueLength.deallocate(capacity: 1) } #endif /// Initializes `UIScheduler` public init() { /// This call is to ensure the main queue has been setup appropriately /// for `UIScheduler`. It is only called once during the application /// lifetime, since Swift has a `dispatch_once` like mechanism to /// lazily initialize global variables and static variables. _ = UIScheduler.__once } /// Queues an action to be performed on main queue. If the action is called /// on the main thread and no work is queued, no scheduling takes place and /// the action is called instantly. /// /// - parameters: /// - action: A closure of the action to be performed on the main thread. /// /// - returns: `Disposable` that can be used to cancel the work before it /// begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { let positionInQueue = enqueue() // If we're already running on the main queue, and there isn't work // already enqueued, we can skip scheduling and just execute directly. if positionInQueue == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue { action() dequeue() return nil } else { let disposable = AnyDisposable() DispatchQueue.main.async { defer { self.dequeue() } guard !disposable.isDisposed else { return } action() } return disposable } } private func dequeue() { #if os(Linux) queueLength.modify { $0 -= 1 } #else OSAtomicDecrement32(queueLength) #endif } private func enqueue() -> Int32 { #if os(Linux) return queueLength.modify { value -> Int32 in value += 1 return value } #else return OSAtomicIncrement32(queueLength) #endif } } /// A `Hashable` wrapper for `DispatchSourceTimer`. `Hashable` conformance is /// based on the identity of the wrapper object rather than the wrapped /// `DispatchSourceTimer`, so two wrappers wrapping the same timer will *not* /// be equal. private final class DispatchSourceTimerWrapper: Hashable { private let value: DispatchSourceTimer fileprivate var hashValue: Int { return ObjectIdentifier(self).hashValue } fileprivate init(_ value: DispatchSourceTimer) { self.value = value } fileprivate static func ==(lhs: DispatchSourceTimerWrapper, rhs: DispatchSourceTimerWrapper) -> Bool { return lhs === rhs } } /// A scheduler backed by a serial GCD queue. public final class QueueScheduler: DateScheduler { /// A singleton `QueueScheduler` that always targets the main thread's GCD /// queue. /// /// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a /// future date, and will always schedule asynchronously (even if /// already running on the main thread). public static let main = QueueScheduler(internalQueue: DispatchQueue.main) public var currentDate: Date { return Date() } public let queue: DispatchQueue private var timers: Atomic<Set<DispatchSourceTimerWrapper>> internal init(internalQueue: DispatchQueue) { queue = internalQueue timers = Atomic(Set()) } /// Initializes a scheduler that will target the given queue with its /// work. /// /// - note: Even if the queue is concurrent, all work items enqueued with /// the `QueueScheduler` will be serial with respect to each other. /// /// - warning: Obsoleted in OS X 10.11 @available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead") @available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.") public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") { self.init(internalQueue: DispatchQueue(label: name, target: queue)) } /// Initializes a scheduler that creates a new serial queue with the /// given quality of service class. /// /// - parameters: /// - qos: Dispatch queue's QoS value. /// - name: A name for the queue in the form of reverse domain. /// - targeting: (Optional) The queue on which this scheduler's work is /// targeted @available(OSX 10.10, *) public convenience init( qos: DispatchQoS = .default, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler", targeting targetQueue: DispatchQueue? = nil ) { self.init(internalQueue: DispatchQueue( label: name, qos: qos, target: targetQueue )) } /// Schedules action for dispatch on internal queue /// /// - parameters: /// - action: A closure of the action to be scheduled. /// /// - returns: `Disposable` that can be used to cancel the work before it /// begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { let d = AnyDisposable() queue.async { if !d.isDisposed { action() } } return d } private func wallTime(with date: Date) -> DispatchWallTime { let (seconds, frac) = modf(date.timeIntervalSince1970) let nsec: Double = frac * Double(NSEC_PER_SEC) let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec)) return DispatchWallTime(timespec: walltime) } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: The start date. /// - action: A closure of the action to be performed. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? { let d = AnyDisposable() queue.asyncAfter(wallDeadline: wallTime(with: date)) { if !d.isDisposed { action() } } return d } /// Schedules a recurring action at the given interval and beginning at the /// given start date. A reasonable default timer interval leeway is /// provided. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - action: Closure of the action to repeat. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, interval: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action) } /// Schedules a recurring action at the given interval with provided leeway, /// beginning at the given start time. /// /// - precondition: `interval` must be non-negative number. /// - precondition: `leeway` must be non-negative number. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - leeway: Some delta for repetition interval. /// - action: A closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { precondition(interval.timeInterval >= 0) precondition(leeway.timeInterval >= 0) let timer = DispatchSource.makeTimerSource( flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue ) #if swift(>=4.0) timer.schedule(wallDeadline: wallTime(with: date), repeating: interval, leeway: leeway) #else timer.scheduleRepeating(wallDeadline: wallTime(with: date), interval: interval, leeway: leeway) #endif timer.setEventHandler(handler: action) timer.resume() let wrappedTimer = DispatchSourceTimerWrapper(timer) timers.modify { timers in timers.insert(wrappedTimer) } return AnyDisposable { [weak self] in timer.cancel() if let scheduler = self { scheduler.timers.modify { timers in timers.remove(wrappedTimer) } } } } } /// A scheduler that implements virtualized time, for use in testing. public final class TestScheduler: DateScheduler { private final class ScheduledAction { let date: Date let action: () -> Void init(date: Date, action: @escaping () -> Void) { self.date = date self.action = action } func less(_ rhs: ScheduledAction) -> Bool { return date.compare(rhs.date) == .orderedAscending } } private let lock = NSRecursiveLock() private var _currentDate: Date /// The virtual date that the scheduler is currently at. public var currentDate: Date { let d: Date lock.lock() d = _currentDate lock.unlock() return d } private var scheduledActions: [ScheduledAction] = [] /// Initializes a TestScheduler with the given start date. /// /// - parameters: /// - startDate: The start date of the scheduler. public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) { lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler" _currentDate = startDate } private func schedule(_ action: ScheduledAction) -> Disposable { lock.lock() scheduledActions.append(action) scheduledActions.sort { $0.less($1) } lock.unlock() return AnyDisposable { self.lock.lock() self.scheduledActions = self.scheduledActions.filter { $0 !== action } self.lock.unlock() } } /// Enqueues an action on the scheduler. /// /// - note: The work is executed on `currentDate` as it is understood by the /// scheduler. /// /// - parameters: /// - action: An action that will be performed on scheduler's /// `currentDate`. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { return schedule(ScheduledAction(date: currentDate, action: action)) } /// Schedules an action for execution after some delay. /// /// - parameters: /// - delay: A delay for execution. /// - action: A closure of the action to perform. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after delay: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { return schedule(after: currentDate.addingTimeInterval(delay), action: action) } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: A starting date. /// - action: A closure of the action to perform. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? { return schedule(ScheduledAction(date: date, action: action)) } /// Schedules a recurring action at the given interval, beginning at the /// given start date. /// /// - precondition: `interval` must be non-negative. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - disposable: A disposable. /// - action: A closure of the action to repeat. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. private func schedule(after date: Date, interval: DispatchTimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) { precondition(interval.timeInterval >= 0) disposable.inner = schedule(after: date) { [unowned self] in action() self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action) } } /// Schedules a recurring action after given delay repeated at the given, /// interval, beginning at the given interval counted from `currentDate`. /// /// - parameters: /// - delay: A delay for action's dispatch. /// - interval: A repetition interval. /// - leeway: Some delta for repetition interval. /// - action: A closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after delay: DispatchTimeInterval, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? { return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action) } /// Schedules a recurring action at the given interval with /// provided leeway, beginning at the given start date. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - leeway: Some delta for repetition interval. /// - action: A closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? { let disposable = SerialDisposable() schedule(after: date, interval: interval, disposable: disposable, action: action) return disposable } /// Advances the virtualized clock by an extremely tiny interval, dequeuing /// and executing any actions along the way. /// /// This is intended to be used as a way to execute actions that have been /// scheduled to run as soon as possible. public func advance() { advance(by: .nanoseconds(1)) } /// Advances the virtualized clock by the given interval, dequeuing and /// executing any actions along the way. /// /// - parameters: /// - interval: Interval by which the current date will be advanced. public func advance(by interval: DispatchTimeInterval) { lock.lock() advance(to: currentDate.addingTimeInterval(interval)) lock.unlock() } /// Advances the virtualized clock to the given future date, dequeuing and /// executing any actions up until that point. /// /// - parameters: /// - newDate: Future date to which the virtual clock will be advanced. public func advance(to newDate: Date) { lock.lock() assert(currentDate.compare(newDate) != .orderedDescending) while scheduledActions.count > 0 { if newDate.compare(scheduledActions[0].date) == .orderedAscending { break } _currentDate = scheduledActions[0].date let scheduledAction = scheduledActions.remove(at: 0) scheduledAction.action() } _currentDate = newDate lock.unlock() } /// Dequeues and executes all scheduled actions, leaving the scheduler's /// date at `Date.distantFuture()`. public func run() { advance(to: Date.distantFuture) } /// Rewinds the virtualized clock by the given interval. /// This simulates that user changes device date. /// /// - parameters: /// - interval: An interval by which the current date will be retreated. public func rewind(by interval: DispatchTimeInterval) { lock.lock() let newDate = currentDate.addingTimeInterval(-interval) assert(currentDate.compare(newDate) != .orderedAscending) _currentDate = newDate lock.unlock() } }
gpl-3.0
01ecd6a239364d62acd1d2b9cbeca10f
31.080858
179
0.687825
3.890534
false
false
false
false
appcompany/SwiftSky
Sources/SwiftSky/Speed.swift
1
4021
// // Speed.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Foundation /// Contains a value, unit and a label describing speed public struct Speed { /// `Double` representing speed private(set) public var value : Double = 0 /// `SpeedUnit` of the value public let unit : SpeedUnit /// Human-readable representation of the value and unit together public var label : String { return label(as: unit) } /** Same as `Speed.label`, but converted to a specific unit - parameter unit: `SpeedUnit` to convert label to - returns: String */ public func label(as unit : SpeedUnit) -> String { let converted = (self.unit == unit ? value : convert(value, from: self.unit, to: unit)) switch unit { case .milePerHour: return "\(converted.noDecimal) mph" case .kilometerPerHour: return "\(converted.noDecimal) kph" case .meterPerSecond: return "\(converted.oneDecimal) m/s" case .knot: return "\(converted.twoDecimal) kt" case .beaufort: return "\(converted.noDecimal) bft" } } /** Same as `Speed.value`, but converted to a specific unit - parameter unit: `SpeedUnit` to convert value to - returns: Float */ public func value(as unit : SpeedUnit) -> Double { return convert(value, from: self.unit, to: unit) } private func convert(_ value : Double, from : SpeedUnit, to : SpeedUnit) -> Double { switch from { case .milePerHour: switch to { case .milePerHour: return value case .kilometerPerHour: return value * 1.609344 case .meterPerSecond: return value * 0.44704 case .knot: return value / 1.150779 case .beaufort: return beaufort(value, from: from) } case .kilometerPerHour: switch to { case .kilometerPerHour: return value case .milePerHour: return value / 1.609344 case .meterPerSecond: return value / 3.6 case .knot: return value / 1.852 case .beaufort: return beaufort(value, from: from) } case .meterPerSecond: switch to { case .meterPerSecond: return value case .milePerHour: return value / 0.44704 case .kilometerPerHour: return value * 3.6 case .knot: return value * 1.9438444924406 case .beaufort: return beaufort(value, from: from) } case .knot: switch to { case .knot: return value case .milePerHour: return value * 1.150779 case .kilometerPerHour: return value * 1.852 case .meterPerSecond: return value / 1.9438444924406 case .beaufort: return beaufort(value, from: from) } default: // cannot convert from beaufort to an actual value return value } } private let bftSpeeds : [Double] = [1,7,12,20,31,40,51,62,75,88,103,118,178,250,333,419] private func beaufort(_ value: Double, from: SpeedUnit) -> Double { let kph = convert(value, from: from, to: .kilometerPerHour) for (i,speed) in bftSpeeds.enumerated() { if kph >= speed { return Double(i + 1) } } return 0 } /// :nodoc: public init(_ value : Double, withUnit : SpeedUnit) { unit = SwiftSky.units.speed self.value = convert(value, from: withUnit, to: unit) } }
mit
74e24635d81a8949ccd9d7181cb1d210
29.687023
95
0.527612
4.398249
false
false
false
false
steelwheels/Coconut
CoconutShell/Source/CNUnixCommand.swift
1
1367
/* * @file CNUnixCommand.swift * @brief Define CNUnixCommand class * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import CoconutData import Foundation public class CNUnixCommandTable { private static var mUnixCommandTable: CNUnixCommandTable? = nil public static var shared: CNUnixCommandTable { get { if let table = mUnixCommandTable { return table } else { let newtable = CNUnixCommandTable() mUnixCommandTable = newtable return newtable } } } public struct CommandInfo { public var path: String init(path pstr: String){ path = pstr } } private var mCommandTable: Dictionary<String, CommandInfo> private init() { mCommandTable = [:] #if os(OSX) let fmanager = FileManager.default let cmddirs = ["/bin", "/usr/bin"] for cmddir in cmddirs { do { let cmdnames = try fmanager.contentsOfDirectory(atPath: cmddir) for cmdname in cmdnames { let cmdinfo = CommandInfo(path: cmddir) mCommandTable[cmdname] = cmdinfo } } catch { CNLog(logLevel: .error, message: "Can not access directory: \(cmddir)", atFunction: #function, inFile: #file) } } #endif } public var commandNames: Array<String> { get { return Array(mCommandTable.keys) } } public func search(byName name: String) -> CommandInfo? { return mCommandTable[name] } }
lgpl-2.1
f36a5ee5a8ad10bad70f994c29fbdf56
20.359375
114
0.680322
3.20892
false
false
false
false
TsinHzl/GoodCodes
iOS_tableview_spread-master/TableViewSpread-swift/TableViewSpread-swift/HelpSectionHeader.swift
1
1265
// // HelpSectionHeader.swift // TableViewSpread-swift // // Created by pxh on 2016/11/18. // Copyright © 2016年 pxh. All rights reserved. // import UIKit class HelpSectionHeader: UIView { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var spreadBtn: UIButton! typealias callBackBlock = (_ index : NSInteger,_ isSelected : Bool)->() var spreadBlock : callBackBlock! override init(frame: CGRect) { super.init(frame: frame) awakeFromNib() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clear let subView : UIView = Bundle.main.loadNibNamed("HelpSectionHeader", owner: self, options: nil)?.first as! UIView subView.frame = self.frame self.addSubview(subView) spreadBtn.tintColor = UIColor.clear } override func layoutSubviews() { super.layoutSubviews() } @IBAction func spreadBtnAction(_ sender: UIButton) { sender.isSelected = !sender.isSelected if let _ = spreadBlock{ spreadBlock(self.tag,sender.isSelected) } } }
mit
1a80cd6db607b52dbe44d70b5025d2db
24.755102
121
0.636292
4.491103
false
false
false
false
zwaldowski/ParksAndRecreation
Swift-2/UI Geometry.playground/Contents.swift
1
3580
//: ## Geometry Extensions import UIKit import XCPlayground let demoView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100)) demoView.translatesAutoresizingMaskIntoConstraints = false demoView.backgroundColor = UIColor.redColor() //: ### CGRect let baseRect = CGRect(x: 32, y: 32, width: 512, height: 128) //: Geometry baseRect.center //: Separator rect: get a hairline for a given rect edge let separatorRect1 = baseRect.rectForEdge(.MinXEdge) let separatorRect2 = baseRect.rectForEdge(.MinYEdge) let separatorRect3 = baseRect.rectForEdge(.MaxXEdge) let separatorRect4 = baseRect.rectForEdge(.MaxYEdge) let separatorRect5 = baseRect.rectForEdge(.MaxYEdge, thickness: demoView.hairline) //: Mutating version of rect divide (for iterative processes) var dividingRect = baseRect let slice1 = dividingRect.dividing(atDistance: 24, fromEdge: .MinYEdge) let slice2 = dividingRect.dividing(atDistance: 24, fromEdge: .MinYEdge) let slice3 = dividingRect.dividing(atDistance: 24, fromEdge: .MinYEdge) let slice4 = dividingRect.dividing(atDistance: 24, fromEdge: .MinYEdge) let slice5 = dividingRect.dividing(atDistance: 24, fromEdge: .MinYEdge) let slice6 = dividingRect.dividing(atDistance: 24, fromEdge: .MinYEdge) dividingRect //: Integration let toCenterIn = CGRect(x: 25, y: 25, width: 75, height: 75) let fiddlyRect = CGRect(x: 12.5, y: 19, width: 14.25, height: 11) fiddlyRect.integerRect(1) fiddlyRect.integerRect(2) fiddlyRect.rectCentered(inRect: toCenterIn, scale: 2) fiddlyRect.rectCentered(xInRect: toCenterIn, scale: 2) fiddlyRect.rectCentered(yInRect: toCenterIn, scale: 2) fiddlyRect.rectCentered(about: fiddlyRect.origin, scale: 2) //: ### Geometric scaling //: //: Though Swift has more robust operators and methods for UIKit geometry, there //: are problems it still doesn't solve. //: //: Scale geometric values for use with screen display let rounded1 = demoView.rround(1.5) let rounded2 = demoView.rround(4/3) let rounded3 = demoView.rround(1.75) //: ### Comparison utilities //: Approximately compare geometric values to compensate for floating point error 1.9999999999999999 ~== 2.0 //: Degree/radian conversion toRadians(-90) ~== -M_PI_2 toRadians(90) ~== M_PI_2 toRadians(180) ~== M_PI toRadians(270) ~== 3 * M_PI_2 toRadians(360) ~== 2 * M_PI toRadians(450) ~== 5 * M_PI_2 toDegrees(M_PI_2) toDegrees(M_PI) toDegrees(M_PI_2 * 3) //: ### `UIEdgeInsets` //: //: Initializer with common edges let insets1 = UIEdgeInsets(width: 22, edges: .Top) //: Edge removal let insets2 = UIEdgeInsets(width: 12) let insets3 = insets2.horizontalInsets let insets4 = insets2.verticalInsets //: Cardinal rotation let toBeRotatedInsets = UIEdgeInsets(top: 12, left: 0, bottom: 0, right: 0) let rotatedInsets1 = toBeRotatedInsets.insetsByRotating(toRadians(-90)) let rotatedInsets2 = toBeRotatedInsets.insetsByRotating(toRadians(0)) let rotatedInsets3 = toBeRotatedInsets.insetsByRotating(toRadians(90)) let rotatedInsets4 = toBeRotatedInsets.insetsByRotating(toRadians(180)) let rotatedInsets5 = toBeRotatedInsets.insetsByRotating(toRadians(270)) let rotatedInsets6 = toBeRotatedInsets.insetsByRotating(toRadians(360)) let rotatedInsets7 = toBeRotatedInsets.insetsByRotating(toRadians(450)) //: ### `UIUserInterfaceLayoutDirection` //: //: Extension-safe API of `UIApplication` UIUserInterfaceLayoutDirection.standardUserInterfaceLayoutDirection //: ### `UIView` //: //: Scale of the window the view is in (always 1 when not in "Full Simulator") demoView.scale //: //: Uses `scale` to determine a good thickness for a content separator demoView.hairline
mit
aca69dabba6b118767905104061b429b
34.098039
82
0.764525
3.458937
false
false
false
false
lieonCX/Live
Live/View/User/LoginAndRegister/FindPasswordVC.swift
1
12365
// // FindPasswordVC.swift // Live // // Created by lieon on 2017/6/26. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // swiftlint:disable force_unwrapping import UIKit import PromiseKit import RxCocoa import RxSwift class FindPasswordVC: BaseViewController, ViewCotrollerProtocol { var phoneNum: String = "" var popVC: UIViewController? fileprivate lazy var findPasswordVM: UserSessionViewModel = UserSessionViewModel() fileprivate var verifiCode: String = "" fileprivate lazy var phoneNumTF: UITextField = { let phoneNumTF = UITextField() phoneNumTF.placeholder = "请输入手机号" phoneNumTF.textColor = UIColor(hex: 0x222222) phoneNumTF.font = UIFont.sizeToFit(with: 14) phoneNumTF.keyboardType = .numberPad phoneNumTF.tintColor = UIColor(hex: CustomKey.Color.mainColor) return phoneNumTF }() fileprivate lazy var pwdTF: UITextField = { let pwdTF = UITextField() pwdTF.isSecureTextEntry = false pwdTF.placeholder = "请输入右侧验证码" pwdTF.textColor = UIColor(hex: 0x222222) pwdTF.font = UIFont.sizeToFit(with: 14) pwdTF.tintColor = UIColor(hex: CustomKey.Color.mainColor) pwdTF.returnKeyType = .done return pwdTF }() fileprivate lazy var userLog: UIImageView = { let imageView = UIImageView(image: UIImage(named: "user_phone_num")) imageView.contentMode = .center return imageView }() fileprivate lazy var pwdLog: UIImageView = { let pwdLog = UIImageView(image: UIImage(named: "user_center_captch")) pwdLog.contentMode = .center return pwdLog }() fileprivate lazy var line0: UIView = { let view = UIView() view.backgroundColor = UIColor(hex: 0xe6e6e6) return view }() fileprivate lazy var line1: UIView = { let view = UIView() view.backgroundColor = UIColor(hex: 0xe6e6e6) return view }() fileprivate lazy var line2: UIView = { let view = UIView() view.backgroundColor = UIColor(hex: 0xe6e6e6) return view }() fileprivate lazy var forgetPwdBtn: UIButton = { let forgetPwdBtn = UIButton() forgetPwdBtn.sizeToFit() forgetPwdBtn.titleLabel?.font = UIFont.sizeToFit(with: 14) forgetPwdBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0) forgetPwdBtn.setTitle("忘记密码", for: .normal) forgetPwdBtn.setTitleColor(UIColor(hex: 0x808080), for: .normal) return forgetPwdBtn }() fileprivate lazy var loginBtn: UIButton = { let loginBtn = UIButton() loginBtn.setBackgroundImage(UIImage(named: "loginBtn_normal"), for: .normal) loginBtn.setBackgroundImage(UIImage(named: "loginBtn_highlighted"), for: .highlighted) loginBtn.setBackgroundImage(UIImage(named: "loginBtn_highlighted"), for: .disabled) loginBtn.titleLabel?.font = UIFont.sizeToFit(with: 16) loginBtn.setTitle("下 一 步", for: .normal) loginBtn.layer.cornerRadius = 20 loginBtn.layer.masksToBounds = true loginBtn.setTitleColor(UIColor.white, for: .normal) loginBtn.isEnabled = false return loginBtn }() fileprivate lazy var descLabel: UILabel = { let descLabel = UILabel() descLabel.font = UIFont.systemFont(ofSize: CGFloat(12)) descLabel.textColor = UIColor(hex: 0x808080) descLabel.text = "我们将发送验证码到您的手机" return descLabel }() fileprivate lazy var contactBtn: UIButton = { let contactBtn = UIButton() contactBtn.titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(16)) contactBtn.setTitle("联系客服", for: .normal) contactBtn.setTitleColor(UIColor.white, for: .normal) contactBtn.sizeToFit() return contactBtn }() override func viewDidLoad() { super.viewDidLoad() setupUI() setupAction() addEndingAction() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !phoneNum.isEmpty { phoneNumTF.text = phoneNum } verifiCode = String.randomStr(withLength: 4) forgetPwdBtn.setTitle(verifiCode, for: .normal) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) phoneNumTF.becomeFirstResponder() } } extension FindPasswordVC { fileprivate func setupUI() { title = "找回密码" view.backgroundColor = .white navigationItem.rightBarButtonItem = UIBarButtonItem(customView: contactBtn) view.addSubview(descLabel) view.addSubview(userLog) view.addSubview(phoneNumTF) view.addSubview(line0) view.addSubview(pwdLog) view.addSubview(pwdTF) view.addSubview(line1) view.addSubview(forgetPwdBtn) view.addSubview(line2) view.addSubview(loginBtn) descLabel.snp.makeConstraints { (maker) in maker.left.equalTo(30) maker.top.equalTo(40) maker.bottom.equalTo(userLog.snp.top).offset(-30) } userLog.snp.makeConstraints { (maker) in maker.left.equalTo(30) maker.top.equalTo(110) maker.width.equalTo(20) } phoneNumTF.snp.makeConstraints { (maker) in maker.left.equalTo(userLog.snp.right).offset(20) maker.centerY.equalTo(userLog.snp.centerY) maker.right.equalTo(-30) } line0.snp.makeConstraints { (maker) in maker.left.equalTo(20) maker.top.equalTo(userLog.snp.bottom).offset(12) maker.right.equalTo(-20) maker.height.equalTo(0.5) } pwdLog.snp.makeConstraints { (maker) in maker.left.equalTo(userLog.snp.left).offset(2) maker.top.equalTo(line0.snp.bottom).offset(12) maker.width.equalTo(20) } forgetPwdBtn.snp.makeConstraints { (maker) in maker.right.equalTo(-35) maker.centerY.equalTo(pwdLog.snp.centerY) } line1.snp.makeConstraints { (maker) in maker.right.equalTo(forgetPwdBtn.snp.left).offset(-12) maker.height.equalTo(20) maker.centerY.equalTo(pwdLog.snp.centerY) maker.width.equalTo(0.5) } pwdTF.snp.makeConstraints { (maker) in maker.left.equalTo(phoneNumTF.snp.left) maker.right.equalTo(phoneNumTF.snp.right) maker.top.equalTo(line0.snp.bottom).offset(12) } line2.snp.makeConstraints { (maker) in maker.top.equalTo(pwdLog.snp.bottom).offset(12) maker.left.equalTo(line0.snp.left) maker.right.equalTo(line0.snp.right) maker.height.equalTo(0.5) } loginBtn.snp.makeConstraints { (maker) in maker.top.equalTo(line2.snp.bottom).offset(70) maker.left.equalTo(10) maker.right.equalTo(-10) maker.height.equalTo(40) } } fileprivate func setupAction() { let usernameValid = phoneNumTF.rx.text.orEmpty .map { $0.characters.count >= 11} .shareReplay(1) let passwordValid = pwdTF.rx.text.orEmpty .map { $0.characters.count >= 4 } .shareReplay(1) let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 } .shareReplay(1) everythingValid .bind(to: loginBtn.rx.isEnabled) .disposed(by: disposeBag) pwdTF.rx.text.orEmpty .map { (text) -> String in return text.characters.count <= 4 ? text: text.substring(to: "0123".endIndex) } .shareReplay(1) .bind(to: pwdTF.rx.text) .disposed(by: disposeBag) phoneNumTF.rx.text.orEmpty .map { (text) -> String in return text.characters.count <= 11 ? text: text.substring(to: "15608006621".endIndex) } .shareReplay(1) .bind(to: phoneNumTF.rx.text) .disposed(by: disposeBag) forgetPwdBtn.rx.tap .subscribe(onNext: { [weak self] in self?.verifiCode = String.randomStr(withLength: 4) self?.forgetPwdBtn.setTitle(self?.verifiCode, for: .normal) }) .disposed(by: disposeBag) loginBtn.rx.tap .subscribe(onNext: { [weak self] in self?.view.endEditing(true) let verifiCode: String = self?.verifiCode.lowercased() ?? "" let inputCode: String = (self?.pwdTF.text ?? "").lowercased() if !(inputCode == verifiCode) { UIApplication.shared.keyWindow?.makeToast("验证码输入错误") return } HUD.show(true, show: "", enableUserActions: false, with: self) if let phoneNum = self?.phoneNumTF.text { self?.findPasswordVM.validate(phoneNum: phoneNum) .then(execute: { isRegisetr -> Promise<Bool> in if isRegisetr { // 已经注册,发送验证码 找回密码 return self!.findPasswordVM.sendCaptcha(phoneNum: phoneNum, type: CaptchaType.findPassword) } else { // 未注册发送验证,跳转到注册页,进行注册 self?.shoAltertoRegisterVC() return Promise<Bool>(value: false) } }).then(execute: { isSuccess -> Void in if isSuccess { let vcc = FindPasswordSecondVC() vcc.phoneNum = self?.phoneNumTF.text ?? "" if let popVC = self?.popVC { vcc.popVC = popVC } self?.navigationController?.pushViewController(vcc, animated: true) } }) .always { HUD.show(false, show: "", enableUserActions: false, with: self) } .catch(execute: { (error) in if let error = error as? AppError { self?.view.makeToast(error.message) } }) } }) .disposed(by: disposeBag) contactBtn.rx.tap.subscribe(onNext: { [weak self] in let destVC = CallServiceViewController() destVC.configMsg("400-189-0090", withEnterTitle: "拨打") destVC.enterAction = {() -> Void in let str: String = "telprompt://\("400-189-0090")" if UIApplication.shared.canOpenURL(URL(string: str)!) { UIApplication.shared.openURL(URL(string: str)!) } } destVC.transitioningDelegate = self?.animator destVC.modalPresentationStyle = .custom self?.present(destVC, animated: true, completion: { _ in }) }) .disposed(by: disposeBag) } fileprivate func shoAltertoRegisterVC() { let destVC = CallServiceViewController() destVC.configMsg("该手机号码还未注册,请先注册?", withEnterTitle: "去注册", cancelTitle: "取消") destVC.enterAction = {() -> Void in let vcc = FastRegisterViewController() if let phoneNum = self.phoneNumTF.text { let param = UserRequestParam() param.username = phoneNum let newSession = SessionHandleType.normal(.register, param) vcc.session = newSession } self.navigationController?.pushViewController(vcc, animated: true) } destVC.transitioningDelegate = animator destVC.modalPresentationStyle = .custom present(destVC, animated: true, completion: { _ in }) } }
mit
9b2434cccd845cefe24edcddbe3e126e
37.967949
118
0.573038
4.504631
false
false
false
false
bgould/thrift
lib/swift/Sources/TBinaryProtocol.swift
11
11310
/* * 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 Foundation public struct TBinaryProtocolVersion { static let version1 = Int32(bitPattern: 0x80010000) static let versionMask = Int32(bitPattern: 0xffff0000) } public class TBinaryProtocol: TProtocol { public var messageSizeLimit: UInt32 = 0 public var transport: TTransport // class level properties for setting global config (useful for server in lieu of Factory design) public static var strictRead: Bool = false public static var strictWrite: Bool = true private var strictRead: Bool private var strictWrite: Bool var currentMessageName: String? var currentFieldName: String? public convenience init(transport: TTransport, strictRead: Bool, strictWrite: Bool) { self.init(on: transport) self.strictRead = strictRead self.strictWrite = strictWrite } public required init(on transport: TTransport) { self.transport = transport self.strictWrite = TBinaryProtocol.strictWrite self.strictRead = TBinaryProtocol.strictRead } func readStringBody(_ size: Int) throws -> String { var data = Data() try ProtocolTransportTry(error: TProtocolError(message: "Transport read failed")) { data = try self.transport.readAll(size: size) } return String(data: data, encoding: String.Encoding.utf8) ?? "" } /// Mark: - TProtocol public func readMessageBegin() throws -> (String, TMessageType, Int32) { let size: Int32 = try read() var messageName = "" var type = TMessageType.exception if size < 0 { let version = size & TBinaryProtocolVersion.versionMask if version != TBinaryProtocolVersion.version1 { throw TProtocolError(error: .badVersion(expected: "\(TBinaryProtocolVersion.version1)", got: "\(version)")) } type = TMessageType(rawValue: Int32(size) & 0x00FF) ?? type messageName = try read() } else { if strictRead { let errorMessage = "Missing message version, old client? Message Name: \(currentMessageName ?? "")" throw TProtocolError(error: .invalidData, message: errorMessage) } if messageSizeLimit > 0 && size > Int32(messageSizeLimit) { throw TProtocolError(error: .sizeLimit(limit: Int(messageSizeLimit), got: Int(size))) } messageName = try readStringBody(Int(size)) type = TMessageType(rawValue: Int32(try read() as UInt8)) ?? type } let seqID: Int32 = try read() return (messageName, type, seqID) } public func readMessageEnd() throws { return } public func readStructBegin() throws -> String { return "" } public func readStructEnd() throws { return } public func readFieldBegin() throws -> (String, TType, Int32) { let fieldType = TType(rawValue: Int32(try read() as UInt8)) ?? TType.stop var fieldID: Int32 = 0 if fieldType != .stop { fieldID = Int32(try read() as Int16) } return ("", fieldType, fieldID) } public func readFieldEnd() throws { return } public func readMapBegin() throws -> (TType, TType, Int32) { var raw = Int32(try read() as UInt8) guard let keyType = TType(rawValue: raw) else { throw TProtocolError(message: "Unknown value for keyType TType: \(raw)") } raw = Int32(try read() as UInt8) guard let valueType = TType(rawValue: raw) else { throw TProtocolError(message: "Unknown value for valueType TType: \(raw)") } let size: Int32 = try read() return (keyType, valueType, size) } public func readMapEnd() throws { return } public func readSetBegin() throws -> (TType, Int32) { let raw = Int32(try read() as UInt8) guard let elementType = TType(rawValue: raw) else { throw TProtocolError(message: "Unknown value for elementType TType: \(raw)") } let size: Int32 = try read() return (elementType, size) } public func readSetEnd() throws { return } public func readListBegin() throws -> (TType, Int32) { let raw = Int32(try read() as UInt8) guard let elementType = TType(rawValue: raw) else { throw TProtocolError(message: "Unknown value for elementType TType: \(raw)") } let size: Int32 = try read() return (elementType, size) } public func readListEnd() throws { return } public func read() throws -> String { let data: Data = try read() guard let str = String.init(data: data, encoding: .utf8) else { throw TProtocolError(error: .invalidData, message: "Couldn't encode UTF-8 from data read") } return str } public func read() throws -> Bool { return (try read() as UInt8) == 1 } public func read() throws -> UInt8 { var buff = Data() try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { buff = try self.transport.readAll(size: 1) } return buff[0] } public func read() throws -> Int16 { var buff = Data() try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { buff = try self.transport.readAll(size: 2) } var ret = Int16(buff[0] & 0xff) << 8 ret |= Int16(buff[1] & 0xff) return ret } public func read() throws -> Int32 { var buff = Data() try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { buff = try self.transport.readAll(size: 4) } var ret = Int32(buff[0] & 0xff) << 24 ret |= Int32(buff[1] & 0xff) << 16 ret |= Int32(buff[2] & 0xff) << 8 ret |= Int32(buff[3] & 0xff) return ret } public func read() throws -> Int64 { var buff = Data() try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { buff = try self.transport.readAll(size: 8) } var ret = Int64(buff[0] & 0xff) << 56 ret |= Int64(buff[1] & 0xff) << 48 ret |= Int64(buff[2] & 0xff) << 40 ret |= Int64(buff[3] & 0xff) << 32 ret |= Int64(buff[4] & 0xff) << 24 ret |= Int64(buff[5] & 0xff) << 16 ret |= Int64(buff[6] & 0xff) << 8 ret |= Int64(buff[7] & 0xff) return ret } public func read() throws -> Double { let val = try read() as Int64 return Double(bitPattern: UInt64(bitPattern: val)) } public func read() throws -> Data { let size = Int(try read() as Int32) var data = Data() try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) { data = try self.transport.readAll(size: size) } return data } // Write methods public func writeMessageBegin(name: String, type messageType: TMessageType, sequenceID: Int32) throws { if strictWrite { let version = TBinaryProtocolVersion.version1 | Int32(messageType.rawValue) try write(version) try write(name) try write(sequenceID) } else { try write(name) try write(UInt8(messageType.rawValue)) try write(sequenceID) } currentMessageName = name } public func writeMessageEnd() throws { currentMessageName = nil } public func writeStructBegin(name: String) throws { return } public func writeStructEnd() throws { return } public func writeFieldBegin(name: String, type fieldType: TType, fieldID: Int32) throws { try write(UInt8(fieldType.rawValue)) try write(Int16(fieldID)) } public func writeFieldStop() throws { try write(UInt8(TType.stop.rawValue)) } public func writeFieldEnd() throws { return } public func writeMapBegin(keyType: TType, valueType: TType, size: Int32) throws { try write(UInt8(keyType.rawValue)) try write(UInt8(valueType.rawValue)) try write(size) } public func writeMapEnd() throws { return } public func writeSetBegin(elementType: TType, size: Int32) throws { try write(UInt8(elementType.rawValue)) try write(size) } public func writeSetEnd() throws { return } public func writeListBegin(elementType: TType, size: Int32) throws { try write(UInt8(elementType.rawValue)) try write(size) } public func writeListEnd() throws { return } public func write(_ value: String) throws { try write(value.data(using: .utf8)!) } public func write(_ value: Bool) throws { let byteVal: UInt8 = value ? 1 : 0 try write(byteVal) } public func write(_ value: UInt8) throws { let buff = Data([value]) try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { try self.transport.write(data: buff) } } public func write(_ value: Int16) throws { var buff = Data() buff.append(Data([UInt8(0xff & (value >> 8))])) buff.append(Data([UInt8(0xff & (value))])) try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { try self.transport.write(data: buff) } } public func write(_ value: Int32) throws { var buff = Data() buff.append(Data([UInt8(0xff & (value >> 24))])) buff.append(Data([UInt8(0xff & (value >> 16))])) buff.append(Data([UInt8(0xff & (value >> 8))])) buff.append(Data([UInt8(0xff & (value))])) try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { try self.transport.write(data: buff) } } public func write(_ value: Int64) throws { var buff = Data() buff.append(Data([UInt8(0xff & (value >> 56))])) buff.append(Data([UInt8(0xff & (value >> 48))])) buff.append(Data([UInt8(0xff & (value >> 40))])) buff.append(Data([UInt8(0xff & (value >> 32))])) buff.append(Data([UInt8(0xff & (value >> 24))])) buff.append(Data([UInt8(0xff & (value >> 16))])) buff.append(Data([UInt8(0xff & (value >> 8))])) buff.append(Data([UInt8(0xff & (value))])) try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { try self.transport.write(data: buff) } } public func write(_ value: Double) throws { // Notably unsafe, since Double and Int64 are the same size, this should work fine try self.write(Int64(bitPattern: value.bitPattern)) } public func write(_ data: Data) throws { try write(Int32(data.count)) try ProtocolTransportTry(error: TProtocolError(message: "Transport write failed")) { try self.transport.write(data: data) } } }
apache-2.0
9b72f133bdc20ee12368aa136271374c
28.453125
107
0.641733
3.879931
false
false
false
false
braintree/braintree_ios
UnitTests/BraintreePayPalTests/BTPaymentMethodNonceParser_PayPal_Tests.swift
1
5985
import XCTest class BTPaymentMethodNonceParser_PayPal_Tests: XCTestCase { func testSharedParser_whenTypeIsPayPal_returnsPayPalAccountNonce() { let sharedParser = BTPaymentMethodNonceParser.shared() let payPalAccountJSON = BTJSON(value: [ "consumed": false, "description": "[email protected]", "details": [ "email": "[email protected]", ], "isLocked": false, "nonce": "a-nonce", "securityQuestions": [], "type": "PayPalAccount", "default": true ]) let payPalAccountNonce = sharedParser.parseJSON(payPalAccountJSON, withParsingBlockForType: "PayPalAccount") as! BTPayPalAccountNonce XCTAssertEqual(payPalAccountNonce.nonce, "a-nonce") XCTAssertEqual(payPalAccountNonce.type, "PayPal") XCTAssertEqual(payPalAccountNonce.email, "[email protected]") XCTAssertTrue(payPalAccountNonce.isDefault) XCTAssertNil(payPalAccountNonce.creditFinancing) } func testParsePayPalCreditFinancingAmount() { let payPalCreditFinancingAmount = BTJSON(value: [ "currency": "USD", "value": "123.45", ]) guard let amount = BTPayPalDriver.creditFinancingAmount(from: payPalCreditFinancingAmount) else { XCTFail("Expected amount") return } XCTAssertEqual(amount.currency, "USD") XCTAssertEqual(amount.value, "123.45") } func testParsePayPalCreditFinancing() { let payPalCreditFinancing = BTJSON(value: [ "cardAmountImmutable": false, "monthlyPayment": [ "currency": "USD", "value": "123.45", ], "payerAcceptance": false, "term": 3, "totalCost": [ "currency": "ABC", "value": "789.01", ], "totalInterest": [ "currency": "XYZ", "value": "456.78", ], ]) guard let creditFinancing = BTPayPalDriver.creditFinancing(from: payPalCreditFinancing) else { XCTFail("Expected credit financing") return } XCTAssertFalse(creditFinancing.cardAmountImmutable) guard let monthlyPayment = creditFinancing.monthlyPayment else { XCTFail("Expected monthly payment details") return } XCTAssertEqual(monthlyPayment.currency, "USD") XCTAssertEqual(monthlyPayment.value, "123.45") XCTAssertFalse(creditFinancing.payerAcceptance) XCTAssertEqual(creditFinancing.term, 3) XCTAssertNotNil(creditFinancing.totalCost) guard let totalCost = creditFinancing.totalCost else { XCTFail("Expected total cost details") return } XCTAssertEqual(totalCost.currency, "ABC") XCTAssertEqual(totalCost.value, "789.01") guard let totalInterest = creditFinancing.totalInterest else { XCTFail("Expected total interest details") return } XCTAssertEqual(totalInterest.currency, "XYZ") XCTAssertEqual(totalInterest.value, "456.78") } func testSharedParser_whenTypeIsPayPal_returnsPayPalAccountNonceWithCreditFinancingOffered() { let sharedParser = BTPaymentMethodNonceParser.shared() let payPalAccountJSON = BTJSON(value: [ "consumed": false, "description": "[email protected]", "details": [ "email": "[email protected]", "creditFinancingOffered": [ "cardAmountImmutable": true, "monthlyPayment": [ "currency": "USD", "value": "13.88", ], "payerAcceptance": true, "term": 18, "totalCost": [ "currency": "USD", "value": "250.00", ], "totalInterest": [ "currency": "USD", "value": "0.00", ], ], ], "isLocked": false, "nonce": "a-nonce", "securityQuestions": [], "type": "PayPalAccount", "default": true, ]) let payPalAccountNonce = sharedParser.parseJSON(payPalAccountJSON, withParsingBlockForType: "PayPalAccount") as! BTPayPalAccountNonce XCTAssertEqual(payPalAccountNonce.nonce, "a-nonce") XCTAssertEqual(payPalAccountNonce.type, "PayPal") XCTAssertEqual(payPalAccountNonce.email, "[email protected]") XCTAssertTrue(payPalAccountNonce.isDefault) guard let creditFinancing = payPalAccountNonce.creditFinancing else { XCTFail("Expected credit financing terms") return } XCTAssertTrue(creditFinancing.cardAmountImmutable) guard let monthlyPayment = creditFinancing.monthlyPayment else { XCTFail("Expected monthly payment details") return } XCTAssertEqual(monthlyPayment.currency, "USD") XCTAssertEqual(monthlyPayment.value, "13.88") XCTAssertTrue(creditFinancing.payerAcceptance) XCTAssertEqual(creditFinancing.term, 18) XCTAssertNotNil(creditFinancing.totalCost) guard let totalCost = creditFinancing.totalCost else { XCTFail("Expected total cost details") return } XCTAssertEqual(totalCost.currency, "USD") XCTAssertEqual(totalCost.value, "250.00") guard let totalInterest = creditFinancing.totalInterest else { XCTFail("Expected total interest details") return } XCTAssertEqual(totalInterest.currency, "USD") XCTAssertEqual(totalInterest.value, "0.00") } }
mit
7a13e8a14c65ba284a8e911e1e2e3be8
35.272727
141
0.579449
4.799519
false
false
false
false
dreamsxin/swift
test/IDE/complete_members_optional.swift
3
1952
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift // RUN: %target-swift-frontend -parse -verify -disable-objc-attr-requires-foundation-module %t_no_errors.swift // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_1 | FileCheck %s -check-prefix=OPTIONAL_MEMBERS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_2 | FileCheck %s -check-prefix=OPTIONAL_MEMBERS_2 @objc protocol HasOptionalMembers1 { @objc optional func optionalInstanceFunc() -> Int @objc optional static func optionalClassFunc() -> Int @objc optional var optionalInstanceProperty: Int { get } @objc optional static var optionalClassProperty: Int { get } } func sanityCheck1(_ a: HasOptionalMembers1) { func isOptionalInt(_ a: inout Int?) {} var result1 = a.optionalInstanceFunc?() isOptionalInt(&result1) var result2 = a.optionalInstanceProperty isOptionalInt(&result2) } // NO_ERRORS_UP_TO_HERE func optionalMembers1(_ a: HasOptionalMembers1) { a.#^OPTIONAL_MEMBERS_1^# } // OPTIONAL_MEMBERS_1: Begin completions, 2 items // OPTIONAL_MEMBERS_1-DAG: Decl[InstanceMethod]/CurrNominal: optionalInstanceFunc!()[#Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_1-DAG: Decl[InstanceVar]/CurrNominal: optionalInstanceProperty[#Int?#]{{; name=.+$}} // OPTIONAL_MEMBERS_1: End completions func optionalMembers2<T : HasOptionalMembers1>(_ a: T) { T.#^OPTIONAL_MEMBERS_2^# } // OPTIONAL_MEMBERS_2: Begin completions, 3 items // OPTIONAL_MEMBERS_2-DAG: Decl[InstanceMethod]/Super: optionalInstanceFunc!({#self: HasOptionalMembers1.Protocol#})[#() -> Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_2-DAG: Decl[StaticMethod]/Super: optionalClassFunc!()[#Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_2-DAG: Decl[StaticVar]/Super: optionalClassProperty[#Int?#]{{; name=.+$}} // OPTIONAL_MEMBERS_2: End completions
apache-2.0
7b66f6f7d4e0454910b6492592c69f2a
44.395349
157
0.713115
3.575092
false
false
false
false
benlangmuir/swift
test/SILGen/modify_accessor.swift
9
5036
// RUN: %target-swift-emit-silgen %s | %FileCheck %s func readwrite(_ : inout String) {} struct SimpleModify { var stored: String var modifiable: String { get {} // CHECK-LABEL: sil hidden [ossa] @$s15modify_accessor12SimpleModifyV10modifiableSSvM // CHECK-SAME: : $@yield_once @convention(method) (@inout SimpleModify) -> @yields @inout String { // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*SimpleModify // CHECK-NEXT: [[FIELD:%.*]] = struct_element_addr [[SELF]] : $*SimpleModify, #SimpleModify.stored // CHECK-NEXT: yield [[FIELD]] : $*String, resume bb1, unwind bb2 // CHECK: bb1: // CHECK-NEXT: end_access [[SELF]] : $*SimpleModify // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() // CHECK: bb2: // CHECK-NEXT: end_access [[SELF]] : $*SimpleModify // CHECK-NEXT: unwind _modify { yield &stored } } // CHECK-LABEL: sil hidden [ossa] @$s15modify_accessor12SimpleModifyV3set6stringySS_tF // CHECK: [[VALUE:%.*]] = copy_value %0 : $String // CHECK-NEXT: [[SELF:%.*]] = begin_access [modify] [unknown] %1 : $*SimpleModify // CHECK-NEXT: // function_ref // CHECK-NEXT: [[MODIFYFN:%.*]] = function_ref @$s15modify_accessor12SimpleModifyV10modifiableSSvM // CHECK-NEXT: ([[FIELD:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFYFN]]([[SELF]]) // CHECK-NEXT: assign [[VALUE]] to [[FIELD]] : $*String // CHECK-NEXT: end_apply [[TOKEN]] // CHECK-NEXT: end_access [[SELF]] : $*SimpleModify // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func set(string: String) { modifiable = string } // CHECK-LABEL: sil hidden [ossa] @$s15modify_accessor12SimpleModifyV0A0yyF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*SimpleModify // CHECK-NEXT: // function_ref // CHECK-NEXT: [[MODIFYFN:%.*]] = function_ref @$s15modify_accessor12SimpleModifyV10modifiableSSvM // CHECK-NEXT: ([[FIELD:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFYFN]]([[SELF]]) // CHECK-NEXT: // function_ref // CHECK-NEXT: [[READWRITE:%.*]] = function_ref @$s15modify_accessor9readwriteyySSzF // CHECK-NEXT: apply [[READWRITE]]([[FIELD]]) // CHECK-NEXT: end_apply [[TOKEN]] // CHECK-NEXT: end_access [[SELF]] : $*SimpleModify // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func modify() { readwrite(&modifiable) } } class SetterSynthesisFromModify { var stored: String = "test" var modifiable: String { get { return stored } // CHECK: sil hidden [transparent] [ossa] @$s15modify_accessor25SetterSynthesisFromModifyC10modifiableSSvs // CHECK: [[VALUE_BORROW:%.*]] = begin_borrow [lexical] %0 : $String // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[VALUE:%.*]] = copy_value [[VALUE_BORROW]] : $String // CHECK-NEXT: // function_ref // CHECK-NEXT: [[MODIFYFN:%.*]] = function_ref @$s15modify_accessor25SetterSynthesisFromModifyC10modifiableSSvM // CHECK-NEXT: ([[FIELD:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFYFN]](%1) // CHECK-NEXT: assign [[VALUE]] to [[FIELD]] : $*String // CHECK-NEXT: end_apply [[TOKEN]] // CHECK-NEXT: end_borrow [[VALUE_BORROW]] // CHECK-NEXT: destroy_value %0 : $String // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() _modify { yield &stored } } } struct ModifyAndSet { var stored: String var modifiable: String { get { return stored } _modify { yield &stored } set(value) { stored = value } } // CHECK-LABEL: sil hidden [ossa] @$s15modify_accessor12ModifyAndSetV3set6stringySS_tF // CHECK: [[VALUE:%.*]] = copy_value %0 : $String // CHECK-NEXT: [[SELF:%.*]] = begin_access [modify] [unknown] %1 : $*ModifyAndSet // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTERFN:%.*]] = function_ref @$s15modify_accessor12ModifyAndSetV10modifiableSSvs // CHECK-NEXT: apply [[SETTERFN]]([[VALUE]], [[SELF]]) // CHECK-NEXT: end_access [[SELF]] : $*ModifyAndSet // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func set(string: String) { modifiable = string } // CHECK-LABEL: sil hidden [ossa] @$s15modify_accessor12ModifyAndSetV0A0yyF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*ModifyAndSet // CHECK-NEXT: // function_ref // CHECK-NEXT: [[MODIFYFN:%.*]] = function_ref @$s15modify_accessor12ModifyAndSetV10modifiableSSvM // CHECK-NEXT: ([[FIELD:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFYFN]]([[SELF]]) // CHECK-NEXT: // function_ref // CHECK-NEXT: [[READWRITE:%.*]] = function_ref @$s15modify_accessor9readwriteyySSzF // CHECK-NEXT: apply [[READWRITE]]([[FIELD]]) // CHECK-NEXT: end_apply [[TOKEN]] // CHECK-NEXT: end_access [[SELF]] : $*ModifyAndSet // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func modify() { readwrite(&modifiable) } }
apache-2.0
d42c3c400af5f5672d53b4ff8ea5ece4
40.966667
114
0.608618
3.350632
false
false
false
false
FlameTinary/weiboSwift
weiboSwift/weiboSwift/Classes/Main/MainViewController.swift
1
3704
// // MainViewController.swift // weiboSwift // // Created by 田宇 on 16/4/25. // Copyright © 2016年 Tinary. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // tabBar.tintColor = UIColor.orangeColor() addChildViewController() } //在view即将显示的时候添加加号按钮 override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tabBar.addSubview(composeBtn) composeBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.bounds.height * 0.5) } //按钮点击方法 func composeBtnClick(){ presentViewController(composeViewController(), animated: true) { () -> Void in print("compose控制器") } } //添加所有子控制器 func addChildViewController() { guard let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) else {return} guard let data = NSData(contentsOfFile: path) else {return} do { let arr = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [[String : AnyObject]] for dict in arr { let vcName = dict["vcName"] as! String let vcImageName = dict["imageName"] as! String let vcTitle = dict["title"] as! String addChildViewController(vcName, imageName: vcImageName, titleName: vcTitle) } } catch { addChildViewController("HomeViewController", imageName: "tabbar_home", titleName: "首页") addChildViewController("DiscoverTableViewController", imageName: "tabbar_discover", titleName: "发现") addChildViewController("NoneViewController", imageName: "", titleName: "") addChildViewController("MessageTableViewController", imageName: "tabbar_message_center", titleName: "消息") addChildViewController("ProfileTableViewController", imageName: "tabbar_profile", titleName: "我") } } //添加子控制器 func addChildViewController(childControllerName: String, imageName: String, titleName: String) { //获取命名空间 let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String //根据字符串创建类 guard let vcClass: AnyClass = NSClassFromString(nameSpace + "." + childControllerName) else {return} //根据类创建对象 let vcCl = vcClass as! UIViewController.Type let vc = vcCl.init() vc.title = titleName vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") let nav = UINavigationController(rootViewController: vc) addChildViewController(nav) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - 懒加载 lazy var composeBtn : UIButton = { let plusBtn = UIButton(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button") plusBtn.addTarget(self, action: #selector(MainViewController.composeBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return plusBtn }() }
mit
9d4bce4a2be6c18093ee26f0f3c587c0
29.698276
146
0.605448
5.478462
false
false
false
false
delannoyk/SoundcloudSDK
sources/SoundcloudSDK/model/APIResponse.swift
1
2086
// // APIResponse.swift // Soundcloud // // Created by Kevin DELANNOY on 21/10/15. // Copyright © 2015 Kevin Delannoy. All rights reserved. // import Foundation public protocol APIResponse { associatedtype U var response: Result<U, SoundcloudError> { get } } public struct SimpleAPIResponse<T>: APIResponse { public typealias U = T public let response: Result<T, SoundcloudError> // MARK: Initialization init(result: Result<T, SoundcloudError>) { response = result } init(error: SoundcloudError) { response = .failure(error) } init(value: T) { response = .success(value) } } public struct PaginatedAPIResponse<T>: APIResponse { public typealias U = [T] public let response: Result<[T], SoundcloudError> private let nextPageURL: URL? private let parse: (JSONObject) -> Result<[T], SoundcloudError> // MARK: Initialization init(response: Result<[T], SoundcloudError>, nextPageURL: URL?, parse: @escaping (JSONObject) -> Result<[T], SoundcloudError>) { self.response = response self.nextPageURL = nextPageURL self.parse = parse } // MARK: Next page public var hasNextPage: Bool { return (nextPageURL != nil) } @discardableResult public func fetchNextPage(completion: @escaping (PaginatedAPIResponse<T>) -> Void) -> CancelableOperation? { if let nextPageURL = nextPageURL { let request = Request( url: nextPageURL, method: .get, parameters: nil, headers: SoundcloudClient.accessToken.map { ["Authorization": "OAuth \($0)" ] }, parse: { JSON -> Result<PaginatedAPIResponse, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: self.parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } return nil } }
mit
bf93ea6da64ad0fa147815a60c23589d
26.077922
112
0.604317
4.464668
false
false
false
false
GyrosWorkshop/WukongiOS
UI/Pages/ListenViewController.swift
1
23167
import UIKit import SafariServices class ListenViewController: UICollectionViewController { private var data = Data() private struct Data { var channel = "" var playingId = "" var preloadId = "" var time = 0.0 var reload = false var files: [Constant.Selector: String] = [:] var playing: [Constant.State: String] = [:] var running = false var elapsed = 0.0 var duration = 0.0 var lyrics: [String] = [] var members: [[String: Any]] = [] var playerIndex = -1 var playlist: [[String: Any]] = [] } private var cells: [IndexPath: UICollectionViewCell] = [:] init() { super.init(collectionViewLayout: UICollectionViewFlowLayout()) title = "Wukong" tabBarItem = UITabBarItem(title: "Listen", image: #imageLiteral(resourceName: "ListenUnselected"), selectedImage: #imageLiteral(resourceName: "ListenSelected")) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Join", style: .plain, target: self, action: #selector(channelButtonAction)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Shuffle", style: .plain, target: self, action: #selector(shuffleButtonAction)) } required convenience init?(coder aDecoder: NSCoder) { self.init() } override func viewDidLoad() { super.viewDidLoad() guard let collectionView = collectionView else { return } collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true collectionView.register(PlayingSongCell.self, forCellWithReuseIdentifier: String(describing: PlayingSongCell.self)) collectionView.register(CurrentLyricsCell.self, forCellWithReuseIdentifier: String(describing: CurrentLyricsCell.self)) collectionView.register(ChannelMembersCell.self, forCellWithReuseIdentifier: String(describing: ChannelMembersCell.self)) collectionView.register(PlaylistSongCell.self, forCellWithReuseIdentifier: String(describing: PlaylistSongCell.self)) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (context) in self.collectionViewLayout.invalidateLayout() }) } } extension ListenViewController: UICollectionViewDelegateFlowLayout { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return 3 case 1: return data.playlist.count default: return 0 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch indexPath.section { case 0: switch indexPath.item { case 0: let cell = cells[indexPath] ?? collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PlayingSongCell.self), for: indexPath) cells[indexPath] = cell (cell as? PlayingSongCell)?.setData(id: data.playingId, song: data.playing, artworkFile: data.files[.playingArtwork], running: data.running, elapsed: data.elapsed, duration: data.duration) return cell case 1: let cell = cells[indexPath] ?? collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CurrentLyricsCell.self), for: indexPath) cells[indexPath] = cell (cell as? CurrentLyricsCell)?.setData(lyrics: data.lyrics) return cell case 2: let cell = cells[indexPath] ?? collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: ChannelMembersCell.self), for: indexPath) cells[indexPath] = cell (cell as? ChannelMembersCell)?.setData(members: data.members, highlightedIndex: data.playerIndex) return cell default: return UICollectionViewCell() } case 1: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PlaylistSongCell.self), for: indexPath) (cell as? PlaylistSongCell)?.setData(song: data.playlist[indexPath.item], showIcon: false) return cell default: return UICollectionViewCell() } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let sectionInset = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section) let interitemSpacing = self.collectionView(collectionView, layout: collectionViewLayout, minimumInteritemSpacingForSectionAt: indexPath.section) let sectionWidth = collectionView.bounds.size.width - sectionInset.left - sectionInset.right switch indexPath.section { case 0: let columnCount = min(max(Int(sectionWidth / 300), 1), 2) let columnWidth = (sectionWidth - interitemSpacing * CGFloat(columnCount - 1)) / CGFloat(columnCount) switch columnCount { case 1: switch indexPath.item { case 0: return CGSize(width: columnWidth, height: 96) case 1: return CGSize(width: columnWidth, height: 30) case 2: return CGSize(width: columnWidth, height: 64) default: return CGSize.zero } case 2: switch indexPath.item { case 0: return CGSize(width: columnWidth, height: 96) case 1: return CGSize(width: columnWidth, height: 96) case 2: return CGSize(width: sectionWidth, height: 64) default: return CGSize.zero } default: return CGSize.zero } case 1: let columnCount = min(max(UInt(sectionWidth / 300), 1), 3) let columnWidth = (sectionWidth - interitemSpacing * CGFloat(columnCount - 1)) / CGFloat(columnCount) return CGSize(width: columnWidth, height: 32) default: return CGSize.zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { switch section { case 0: return UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) case 1: return UIEdgeInsets(top: 0, left: 12, bottom: 12, right: 12) default: return UIEdgeInsets.zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { switch section { case 0: return 12 case 1: return 8 default: return 0 } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { switch section { case 0: return 12 case 1: return 8 default: return 0 } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) switch indexPath.section { case 0: switch indexPath.item { case 0: sheet.title = data.playing[.title] if let url = URL(string: self.data.playing[.link] ?? "") { sheet.addAction(UIAlertAction(title: "Track Page", style: .default) { (action) in let viewController = SFSafariViewController(url: url) viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) }) } if let url = URL(string: self.data.playing[.mvLink] ?? "") { sheet.addAction(UIAlertAction(title: "Video Page", style: .default) { (action) in let viewController = SFSafariViewController(url: url) viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) }) } if let url = URL(string: self.data.files[.playingArtwork] ?? "") { sheet.addAction(UIAlertAction(title: "Artwork File", style: .default) { (action) in let viewController = SFSafariViewController(url: url) viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) }) } if let url = URL(string: self.data.files[.playingFile] ?? "") { sheet.addAction(UIAlertAction(title: "Audio File", style: .default) { (action) in let viewController = SFSafariViewController(url: url) viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) }) } sheet.addAction(UIAlertAction(title: "Downvote", style: .default) { (action) in WukongClient.sharedInstance.dispatchAction([.Player, .downvote], []) }) default: break } case 1: let item = data.playlist[indexPath.item] sheet.title = item[Constant.State.title.rawValue] as? String if let url = URL(string: item[Constant.State.link.rawValue] as? String ?? "") { sheet.addAction(UIAlertAction(title: "Track Page", style: .default) { (action) in let viewController = SFSafariViewController(url: url) viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) }) } if let url = URL(string: item[Constant.State.mvLink.rawValue] as? String ?? "") { sheet.addAction(UIAlertAction(title: "Video Page", style: .default) { (action) in let viewController = SFSafariViewController(url: url) viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) }) } if let id = item[Constant.State.id.rawValue] as? String { sheet.addAction(UIAlertAction(title: "Upnext", style: .default) { (action) in WukongClient.sharedInstance.dispatchAction([.Song, .move], [id, 0]) }) sheet.addAction(UIAlertAction(title: "Delete", style: .destructive) { (action) in WukongClient.sharedInstance.dispatchAction([.Song, .remove], [id]) }) } default: break } guard sheet.actions.count > 0 else { return } sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel)) sheet.popoverPresentationController?.sourceView = collectionView sheet.popoverPresentationController?.sourceRect = collectionView.cellForItem(at: indexPath)?.frame ?? collectionView.bounds sheet.popoverPresentationController?.permittedArrowDirections = [.up, .down] present(sheet, animated: true) } @objc func channelButtonAction() { let alert = UIAlertController(title: "Join Channel", message: nil, preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = self.data.channel } alert.addAction(UIAlertAction(title: "OK", style: .default) { (action) in guard let channel = alert.textFields?.first?.text, !channel.isEmpty else { return } UserDefaults.appDefaults.set(channel, forKey: Constant.Defaults.channel) WukongClient.sharedInstance.dispatchAction([.Channel, .name], [channel]) }) alert.addAction(UIAlertAction(title: "Cancel", style: .default)) present(alert, animated: true) } @objc func shuffleButtonAction() { WukongClient.sharedInstance.dispatchAction([.Song, .shuffle], []) } } extension ListenViewController: AppComponent { func appDidLoad() { data = Data() let client = WukongClient.sharedInstance client.subscribeChange { var channelChanged = false defer { if channelChanged { if let item = self.navigationItem.leftBarButtonItem { let channel = self.data.channel item.title = channel.isEmpty ? "Join" : "#\(channel)" self.navigationItem.leftBarButtonItem = nil self.navigationItem.leftBarButtonItem = item } } } var trackChanged = false defer { if trackChanged { let playingId = self.data.playingId let reload = self.data.reload if !playingId.isEmpty { let dataLoader = DataLoader.sharedInstance let audioPlayer = AudioPlayer.sharedInstance let title = self.data.playing[.title] let album = self.data.playing[.album] let artist = self.data.playing[.artist] audioPlayer.update(title: title, album: album, artist: artist, artwork: nil) if let url = URL(string: self.data.files[.playingArtwork] ?? "") { dataLoader.load(key: "\(playingId).\(url.pathExtension)", url: url, force: reload) { (data) in guard let data = data else { return } audioPlayer.update(title: title, album: album, artist: artist, artwork: UIImage(data: data)) } } if let url = URL(string: self.data.files[.playingFile] ?? "") { dataLoader.load(key: "\(playingId).\(url.pathExtension)", url: url, force: reload) { (data) in guard let data = data else { return } var running = false var elapsed = 0.0 var duration = 0.0 audioPlayer.play(data: data, time: Date(timeIntervalSince1970: self.data.time), { (nextRunning, nextElapsed, nextDuration, ended) in if running != nextRunning { audioPlayer.update() client.dispatchAction([.Player, .running], [nextRunning]) } if elapsed != nextElapsed { client.dispatchAction([.Player, .elapsed], [nextElapsed]) } if duration != nextDuration { client.dispatchAction([.Player, .duration], [nextDuration]) } if ended { client.dispatchAction([.Player, .ended], []) } running = nextRunning elapsed = nextElapsed duration = nextDuration }) } } } if reload { client.dispatchAction([.Player, .reload], [false]) } } } var preloadChanged = false defer { if preloadChanged { let preloadId = self.data.preloadId if !preloadId.isEmpty { let dataLoader = DataLoader.sharedInstance if let url = URL(string: self.data.files[.preloadArtwork] ?? "") { dataLoader.load(key: "\(preloadId).\(url.pathExtension)", url: url) } if let url = URL(string: self.data.files[.preloadFile] ?? "") { dataLoader.load(key: "\(preloadId).\(url.pathExtension)", url: url) } } } } var playingChanged = false defer { if playingChanged { UIView.performWithoutAnimation { self.collectionView?.reloadItems(at: [IndexPath(item: 0, section: 0)]) } } } var lyricsChanged = false defer { if lyricsChanged { UIView.performWithoutAnimation { self.collectionView?.reloadItems(at: [IndexPath(item: 1, section: 0)]) } } } var membersChanged = false defer { if membersChanged { UIView.performWithoutAnimation { self.collectionView?.reloadItems(at: [IndexPath(item: 2, section: 0)]) } } } var playlistChanged = false defer { if playlistChanged { self.collectionView?.reloadSections(IndexSet(integer: 1)) } } if let channel = client.getState([.channel, .name]) as String? { channelChanged = self.data.channel != channel self.data.channel = channel } if let playingId = client.getState([.song, .playing, .id]) as String?, let preloadId = client.getState([.song, .preload, .id]) as String?, let time = client.getState([.song, .playing, .time]) as Double?, let reload = client.getState([.player, .reload]) as Bool? { trackChanged = reload || self.data.playingId != playingId || abs(self.data.time - time) > 10 preloadChanged = self.data.preloadId != preloadId self.data.playingId = playingId self.data.preloadId = preloadId self.data.time = time self.data.reload = reload } ([.playingArtwork, .playingFile, .preloadArtwork, .preloadFile] as [Constant.Selector]).forEach { (selector) in guard let value = client.querySelector(selector) as Any? else { return } switch value { case let string as String: self.data.files[selector] = string case let object as [String: Any]: self.data.files[selector] = object[Constant.State.url.rawValue] as? String ?? "" default: self.data.files[selector] = "" } } if let playing = client.getState([.song, .playing]) as [String: Any]? { ([.title, .album, .artist, .link, .mvLink] as [Constant.State]).forEach { (field) in guard let value = playing[field.rawValue] as? String else { return } playingChanged = playingChanged || self.data.playing[field] != value self.data.playing[field] = value } } if let playing = client.querySelector(.playingFile) as [String: Any]? { let format = playing[Constant.State.format.rawValue] as? String ?? "unknown" let quality = playing[Constant.State.quality.rawValue] as? [String: Any] ?? [:] let qualityDescription = quality[Constant.State.description.rawValue] as? String ?? "" playingChanged = playingChanged || self.data.playing[.format] != format playingChanged = playingChanged || self.data.playing[.quality] != qualityDescription self.data.playing[.format] = format self.data.playing[.quality] = qualityDescription } if let running = client.getState([.player, .running]) as Bool?, let elapsed = client.getState([.player, .elapsed]) as Double?, let duration = client.getState([.player, .duration]) as Double? { playingChanged = playingChanged || self.data.running != running playingChanged = playingChanged || self.data.elapsed != elapsed playingChanged = playingChanged || self.data.duration != duration self.data.running = running self.data.elapsed = elapsed self.data.duration = duration } if let lyrics = client.querySelector(.currentLyrics) as [String]? { lyricsChanged = self.data.lyrics.elementsEqual(lyrics) self.data.lyrics = lyrics } if let members = client.getState([.channel, .members]) as [[String: Any]]? { membersChanged = !self.data.members.elementsEqual(members) { let id0 = $0[Constant.State.id.rawValue] as? String let id1 = $1[Constant.State.id.rawValue] as? String return id0 == id1 } self.data.members = members } if let playerIndex = client.querySelector(.playerIndex) as Int? { membersChanged = membersChanged || self.data.playerIndex != playerIndex self.data.playerIndex = playerIndex } if let playlist = client.getState([.song, .playlist]) as [[String: Any]]? { playlistChanged = !self.data.playlist.elementsEqual(playlist) { let id0 = $0[Constant.State.id.rawValue] as? String let id1 = $1[Constant.State.id.rawValue] as? String return id0 == id1 } self.data.playlist = playlist } } if let channel = UserDefaults.appDefaults.string(forKey: Constant.Defaults.channel), !channel.isEmpty { client.dispatchAction([.Channel, .name], [channel]) } } }
mit
ffae2e922322306efd201cdc816d4595
50.368071
204
0.56015
5.448495
false
false
false
false
kstaring/swift
test/type/types.swift
4
5983
// RUN: %target-parse-verify-swift var a : Int func test() { var y : a // expected-error {{use of undeclared type 'a'}} var z : y // expected-error {{use of undeclared type 'y'}} var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}} } var b : (Int) -> Int = { $0 } var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}} var d2 : () -> Int = { 4 } var d3 : () -> Float = { 4 } var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}} var e0 : [Int] e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>),}} var f0 : [Float] var f1 : [(Int,Int)] var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}} var h0 : Int? _ = h0 == nil // no-warning var h1 : Int?? _ = h1! == nil // no-warning var h2 : [Int?] var h3 : [Int]? var h3a : [[Int?]] var h3b : [Int?]? var h4 : ([Int])? var h5 : ([([[Int??]])?])? var h7 : (Int,Int)? var h8 : ((Int) -> Int)? var h9 : (Int?) -> Int? var h10 : Int?.Type?.Type var i = Int?(42) var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}} func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}} // <rdar://problem/15588967> Array type sugar default construction syntax doesn't work func test_array_construct<T>(_: T) { _ = [T]() // 'T' is a local name _ = [Int]() // 'Int is a global name' _ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name. _ = [UnsafeMutablePointer<Int?>]() // Nesting. _ = [([UnsafeMutablePointer<Int>])]() _ = [(String, Float)]() } extension Optional { init() { self = .none } } // <rdar://problem/15295763> default constructing an optional fails to typecheck func test_optional_construct<T>(_: T) { _ = T?() // Local name. _ = Int?() // Global name _ = (Int?)() // Parenthesized name. } // Test disambiguation of generic parameter lists in expression context. struct Gen<T> {} var y0 : Gen<Int?> var y1 : Gen<Int??> var y2 : Gen<[Int?]> var y3 : Gen<[Int]?> var y3a : Gen<[[Int?]]> var y3b : Gen<[Int?]?> var y4 : Gen<([Int])?> var y5 : Gen<([([[Int??]])?])?> var y7 : Gen<(Int,Int)?> var y8 : Gen<((Int) -> Int)?> var y8a : Gen<[([Int]?) -> Int]> var y9 : Gen<(Int?) -> Int?> var y10 : Gen<Int?.Type?.Type> var y11 : Gen<Gen<Int>?> var y12 : Gen<Gen<Int>?>? var y13 : Gen<Gen<Int?>?>? var y14 : Gen<Gen<Int?>>? var y15 : Gen<Gen<Gen<Int?>>?> var y16 : Gen<Gen<Gen<Int?>?>> var y17 : Gen<Gen<Gen<Int?>?>>? var z0 = Gen<Int?>() var z1 = Gen<Int??>() var z2 = Gen<[Int?]>() var z3 = Gen<[Int]?>() var z3a = Gen<[[Int?]]>() var z3b = Gen<[Int?]?>() var z4 = Gen<([Int])?>() var z5 = Gen<([([[Int??]])?])?>() var z7 = Gen<(Int,Int)?>() var z8 = Gen<((Int) -> Int)?>() var z8a = Gen<[([Int]?) -> Int]>() var z9 = Gen<(Int?) -> Int?>() var z10 = Gen<Int?.Type?.Type>() var z11 = Gen<Gen<Int>?>() var z12 = Gen<Gen<Int>?>?() var z13 = Gen<Gen<Int?>?>?() var z14 = Gen<Gen<Int?>>?() var z15 = Gen<Gen<Gen<Int?>>?>() var z16 = Gen<Gen<Gen<Int?>?>>() var z17 = Gen<Gen<Gen<Int?>?>>?() y0 = z0 y1 = z1 y2 = z2 y3 = z3 y3a = z3a y3b = z3b y4 = z4 y5 = z5 y7 = z7 y8 = z8 y8a = z8a y9 = z9 y10 = z10 y11 = z11 y12 = z12 y13 = z13 y14 = z14 y15 = z15 y16 = z16 y17 = z17 // Type repr formation. // <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr) let tupleTypeWithNames = (age:Int, count:Int)(4, 5) let dictWithTuple = [String: (age:Int, count:Int)]() // <rdar://problem/21684837> typeexpr not being formed for postfix ! let bb2 = [Int!](repeating: nil, count: 2) // <rdar://problem/21560309> inout allowed on function return type func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}} r21560309 { x in x } // <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties class r21949448 { var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}} } // SE-0066 - Standardize function type argument syntax to require parentheses let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}} let _ : inout Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{18-18=)}} func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}} func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{38-38=)}} func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}} func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}} class C { func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}} func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}} func foo3() { let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}} let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}} } }
apache-2.0
4c33a893f11ace9f6fc8ae762cf56790
33.385057
173
0.629784
3.077675
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/UltraDrawerView/Sources/Demo/ShapeViewController.swift
1
8442
import UIKit final class ShapeViewController: UIViewController { private enum Layout { static let topInsetPortrait: CGFloat = 36 static let topInsetLandscape: CGFloat = 20 static let middleInsetFromBottom: CGFloat = 280 static let headerHeight: CGFloat = 64 static let cornerRadius: CGFloat = 16 static let shadowRadius: CGFloat = 4 static let shadowOpacity: Float = 0.2 static let shadowOffset = CGSize.zero } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.9, alpha: 1.0) let headerView = ShapeHeaderView() headerView.translatesAutoresizingMaskIntoConstraints = false headerView.heightAnchor.constraint(equalToConstant: Layout.headerHeight).isActive = true tableView.backgroundColor = .white tableView.dataSource = self tableView.delegate = self tableView.register(ShapeCell.self, forCellReuseIdentifier: "\(ShapeCell.self)") if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = .never } drawerView = DrawerView(scrollView: tableView, headerView: headerView) drawerView.middlePosition = .fromBottom(Layout.middleInsetFromBottom) drawerView.cornerRadius = Layout.cornerRadius drawerView.containerView.backgroundColor = .white drawerView.layer.shadowRadius = Layout.shadowRadius drawerView.layer.shadowOpacity = Layout.shadowOpacity drawerView.layer.shadowOffset = Layout.shadowOffset view.addSubview(drawerView) setupButtons() setupLayout() drawerView.setState(.middle, animated: false) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) dismiss(animated: true) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if isFirstLayout { isFirstLayout = false updateLayoutWithCurrentOrientation() drawerView.setState(UIDevice.current.orientation.isLandscape ? .top : .middle, animated: false) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let prevState = drawerView.state updateLayoutWithCurrentOrientation() coordinator.animate(alongsideTransition: { [weak self] context in let newState: DrawerView.State = (prevState == .bottom) ? .bottom : .top self?.drawerView.setState(newState, animated: context.isAnimated) }) } @available(iOS 11.0, *) override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() tableView.contentInset.bottom = view.safeAreaInsets.bottom tableView.scrollIndicatorInsets.bottom = view.safeAreaInsets.bottom } // MARK: - Private private let tableView = UITableView() private var drawerView: DrawerView! private let cellInfos = ShapeCell.makeDefaultInfos() private var isFirstLayout = true private var portraitConstraints: [NSLayoutConstraint] = [] private var landscapeConstraints: [NSLayoutConstraint] = [] private func setupLayout() { drawerView.translatesAutoresizingMaskIntoConstraints = false portraitConstraints = [ drawerView.topAnchor.constraint(equalTo: view.topAnchor), drawerView.leftAnchor.constraint(equalTo: view.leftAnchor), drawerView.bottomAnchor.constraint(equalTo: view.bottomAnchor), drawerView.rightAnchor.constraint(equalTo: view.rightAnchor), ] let landscapeLeftAnchor: NSLayoutXAxisAnchor if #available(iOS 11.0, *) { landscapeLeftAnchor = view.safeAreaLayoutGuide.leftAnchor } else { landscapeLeftAnchor = view.leftAnchor } landscapeConstraints = [ drawerView.topAnchor.constraint(equalTo: view.topAnchor), drawerView.leftAnchor.constraint(equalTo: landscapeLeftAnchor, constant: 16), drawerView.bottomAnchor.constraint(equalTo: view.bottomAnchor), drawerView.widthAnchor.constraint(equalToConstant: 320), ] } private func updateLayoutWithCurrentOrientation() { let orientation = UIDevice.current.orientation if orientation.isLandscape { portraitConstraints.forEach { $0.isActive = false } landscapeConstraints.forEach { $0.isActive = true } drawerView.topPosition = .fromTop(Layout.topInsetLandscape) drawerView.availableStates = [.top, .bottom] } else if orientation.isPortrait { landscapeConstraints.forEach { $0.isActive = false } portraitConstraints.forEach { $0.isActive = true } drawerView.topPosition = .fromTop(Layout.topInsetPortrait) drawerView.availableStates = [.top, .middle, .bottom] } } } extension ShapeViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellInfos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "\(ShapeCell.self)", for: indexPath) if let cell = cell as? ShapeCell { cell.update(with: cellInfos[indexPath.row]) } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return ShapeCell.Layout.estimatedHeight } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } extension ShapeViewController { // MARK: - Buttons private func setupButtons() { func addButton(withTitle title: String, action: Selector, topPosition: CGFloat) { let button = UIButton(type: .system) view.addSubview(button) button.backgroundColor = .darkGray button.titleLabel?.font = .boldSystemFont(ofSize: UIFont.systemFontSize) button.tintColor = .white button.layer.cornerRadius = 8 button.layer.masksToBounds = true button.setTitle(title, for: .normal) button.addTarget(self, action: action, for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false let rightAnchor: NSLayoutXAxisAnchor let topAnchor: NSLayoutYAxisAnchor if #available(iOS 11.0, *) { rightAnchor = view.safeAreaLayoutGuide.rightAnchor topAnchor = view.safeAreaLayoutGuide.topAnchor } else { rightAnchor = view.rightAnchor topAnchor = view.topAnchor } button.rightAnchor.constraint(equalTo: rightAnchor, constant: -8).isActive = true button.widthAnchor.constraint(equalToConstant: 128).isActive = true button.topAnchor.constraint(equalTo: topAnchor, constant: topPosition).isActive = true } addButton(withTitle: "Hide", action: #selector(handleHideButton), topPosition: 32) addButton(withTitle: "Show", action: #selector(handleShowButton), topPosition: 64 + 32) addButton(withTitle: "Middle", action: #selector(handleMiddleButton), topPosition: 2 * 64 + 32) } @objc private func handleHideButton() { drawerView.setState(.bottom, animated: true) } @objc private func handleShowButton() { drawerView.setState(.top, animated: true) } @objc private func handleMiddleButton() { drawerView.setState(.middle, animated: true) } }
mit
18a030348ff262d65a229b8ff27b3415
37.372727
112
0.651504
5.553947
false
false
false
false
martinschilliger/SwissGrid
fastlane/SnapshotHelper.swift
1
9363
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication) { Snapshot.setupSnapshot(app) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotDetectUser case cannotFindHomeDirectory case cannotFindSimulatorHomeDirectory case cannotAccessSimulatorHomeDirectory(String) var debugDescription: String { switch self { case .cannotDetectUser: return "Couldn't find Snapshot configuration files - can't detect current user " case .cannotFindHomeDirectory: return "Couldn't find Snapshot configuration files - can't detect `Users` dir" case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case let .cannotAccessSimulatorHomeDirectory(simulatorHostHome): return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" } } } open class Snapshot: NSObject { static var app: XCUIApplication! static var cacheDirectory: URL! static var screenshotsDirectory: URL? { return cacheDirectory.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication) { do { let cacheDir = try pathPrefix() Snapshot.cacheDirectory = cacheDir Snapshot.app = app setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { print(error) } } class func setLanguage(_ app: XCUIApplication) { let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } class func setLaunchArguments(_ app: XCUIApplication) { let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.characters.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work sleep(1) // Waiting for the animation to be finished (kind of) #if os(OSX) XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else let screenshot = app.windows.firstMatch.screenshot() guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") do { try screenshot.pngRepresentation.write(to: path) } catch let error { print("Problem writing screenshot: \(name) to \(path)") print(error) } #endif } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif let networkLoadingIndicator = XCUIApplication().otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func pathPrefix() throws -> URL? { let homeDir: URL // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { throw SnapshotError.cannotDetectUser } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { throw SnapshotError.cannotFindHomeDirectory } homeDir = usersDir.appendingPathComponent(user) #else guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } guard let homeDirUrl = URL(string: simulatorHostHome) else { throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) } homeDir = URL(fileURLWithPath: homeDirUrl.path) #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasWhiteListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasWhiteListedIdentifier: Bool { let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return whiteListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { evaluatedObject, _ in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { let deviceWidth = XCUIApplication().frame.width let isStatusBar = NSPredicate { evaluatedObject, _ in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA ... numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.6]
mit
b99de8873f323906e96336808b38db15
37.212245
158
0.651891
5.420961
false
false
false
false
webninjamobile/marys-rosary
controllers/ModalPreviewViewController.swift
1
2418
// // ModalPreviewViewController.swift // PrayerBook // // Created by keithics on 8/27/15. // Copyright (c) 2015 Web Ninja Technologies. All rights reserved. // import UIKit import AVFoundation class ModalPreviewViewController: UIViewController { @IBOutlet weak var viewPlay: CircleProgress! @IBOutlet weak var labelTitle: UILabel! var mp3:AVAudioPlayer = AVAudioPlayer() var responseTime : Double = 0 var currentPrayer : String = "" var timer = NSTimer() var currentMp3 : String = "" override func viewDidLoad() { super.viewDidLoad() viewPlay.layer.cornerRadius = 100 viewPlay.lineWidth = CGFloat(10.0) viewPlay.fill = "#E63320" viewPlay.layer.backgroundColor = UIColor(rgba: "#e7993c").CGColor viewPlay.progressLabel.text = "\u{f144}" viewPlay.progressLabel.font = UIFont(name: "FontAwesome", size: CGFloat(140)) } @IBAction func tapHidden(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) self.mp3.stop() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let path = NSBundle.mainBundle().pathForResource(currentMp3, ofType: "mp3") mp3 = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!)) mp3.prepareToPlay() mp3.play() delay(Double(mp3.duration)) { self.updateCounter() self.viewPlay.animateLayerFill() self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true) } labelTitle.text = currentPrayer viewPlay.animateProgressView(0.0,to: 1.0,duration: CFTimeInterval(Double(responseTime) + Double(mp3.duration))) } func updateCounter(){ responseTime -= 0.1 let rounded = Double(round(1000*responseTime)/1000) labelTitle.text = "\(rounded)" if rounded <= 0 { timer.invalidate() labelTitle.text = currentPrayer delay(0.5) { self.dismissViewControllerAnimated(true, completion: nil) self.mp3.stop() } } } override func viewDidDisappear(animated: Bool) { self.mp3.stop() } }
gpl-2.0
9003b88a6d6da42c4fdceb5d5b10df75
27.785714
148
0.612076
4.553672
false
false
false
false
hulinSun/MyRx
MyRx/Pods/Moya/Source/Moya+Internal.swift
1
14348
import Foundation import Result /// Internal extension to keep the inner-workings outside the main Moya.swift file. public extension MoyaProvider { // Yup, we're disabling these. The function is complicated, but breaking it apart requires a large effort. // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length /// Performs normal requests. func requestNormal(_ target: Target, queue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable { let endpoint = self.endpoint(target) let stubBehavior = self.stubClosure(target) let cancellableToken = CancellableWrapper() // Allow plugins to modify response let pluginsWithCompletion: Moya.Completion = { result in let processedResult = self.plugins.reduce(result) { $1.process($0, target: target) } completion(processedResult) } if trackInflights { objc_sync_enter(self) var inflightCompletionBlocks = self.inflightRequests[endpoint] inflightCompletionBlocks?.append(pluginsWithCompletion) self.inflightRequests[endpoint] = inflightCompletionBlocks objc_sync_exit(self) if inflightCompletionBlocks != nil { return cancellableToken } else { objc_sync_enter(self) self.inflightRequests[endpoint] = [pluginsWithCompletion] objc_sync_exit(self) } } let performNetworking = { (requestResult: Result<URLRequest, Moya.Error>) in if cancellableToken.isCancelled { self.cancelCompletion(pluginsWithCompletion, target: target) return } var request: URLRequest! switch requestResult { case .success(let urlRequest): request = urlRequest case .failure(let error): pluginsWithCompletion(.failure(error)) return } // Allow plugins to modify request let preparedRequest = self.plugins.reduce(request) { $1.prepare($0, target: target) } switch stubBehavior { case .never: let networkCompletion: Moya.Completion = { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach { $0(result) } objc_sync_enter(self) self.inflightRequests.removeValue(forKey: endpoint) objc_sync_exit(self) } else { pluginsWithCompletion(result) } } switch target.task { case .request: cancellableToken.innerCancellable = self.sendRequest(target, request: preparedRequest, queue: queue, progress: progress, completion: networkCompletion) case .upload(.file(let file)): cancellableToken.innerCancellable = self.sendUploadFile(target, request: preparedRequest, queue: queue, file: file, progress: progress, completion: networkCompletion) case .upload(.multipart(let multipartBody)): guard !multipartBody.isEmpty && target.method.supportsMultipart else { fatalError("\(target) is not a multipart upload target.") } cancellableToken.innerCancellable = self.sendUploadMultipart(target, request: preparedRequest, queue: queue, multipartBody: multipartBody, progress: progress, completion: networkCompletion) case .download(.request(let destination)): cancellableToken.innerCancellable = self.sendDownloadRequest(target, request: preparedRequest, queue: queue, destination: destination, progress: progress, completion: networkCompletion) } default: cancellableToken.innerCancellable = self.stubRequest(target, request: preparedRequest, completion: { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach { $0(result) } objc_sync_enter(self) self.inflightRequests.removeValue(forKey: endpoint) objc_sync_exit(self) } else { pluginsWithCompletion(result) } }, endpoint: endpoint, stubBehavior: stubBehavior) } } requestClosure(endpoint, performNetworking) return cancellableToken } // swiftlint:enable cyclomatic_complexity // swiftlint:enable function_body_length func cancelCompletion(_ completion: Moya.Completion, target: Target) { let error = Moya.Error.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) plugins.forEach { $0.didReceive(.failure(error), target: target) } completion(.failure(error)) } /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. public final func createStubFunction(_ token: CancellableToken, forTarget target: Target, withCompletion completion: @escaping Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType], request: URLRequest) -> (() -> ()) { // swiftlint:disable:this function_parameter_count return { if token.isCancelled { self.cancelCompletion(completion, target: target) return } switch endpoint.sampleResponseClosure() { case .networkResponse(let statusCode, let data): let response = Moya.Response(statusCode: statusCode, data: data, request: request, response: nil) plugins.forEach { $0.didReceive(.success(response), target: target) } completion(.success(response)) case .response(let customResponse, let data): let response = Moya.Response(statusCode: customResponse.statusCode, data: data, request: request, response: customResponse) plugins.forEach { $0.didReceive(.success(response), target: target) } completion(.success(response)) case .networkError(let error): let error = Moya.Error.underlying(error) plugins.forEach { $0.didReceive(.failure(error), target: target) } completion(.failure(error)) } } } /// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`. final func notifyPluginsOfImpendingStub(for request: URLRequest, target: Target) { let alamoRequest = manager.request(request as URLRequestConvertible) plugins.forEach { $0.willSend(alamoRequest, target: target) } } } private extension MoyaProvider { func sendUploadMultipart(_ target: Target, request: URLRequest, queue: DispatchQueue?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: @escaping Moya.Completion) -> CancellableWrapper { let cancellable = CancellableWrapper() let multipartFormData: (RequestMultipartFormData) -> Void = { form in for bodyPart in multipartBody { switch bodyPart.provider { case .data(let data): self.append(data: data, bodyPart: bodyPart, to: form) case .file(let url): self.append(fileURL: url, bodyPart: bodyPart, to: form) case .stream(let stream, let length): self.append(stream: stream, length: length, bodyPart: bodyPart, to: form) } } if let parameters = target.parameters { parameters .flatMap { key, value in multipartQueryComponents(key, value) } .forEach { key, value in if let data = value.data(using: .utf8, allowLossyConversion: false) { form.append(data, withName: key) } } } } manager.upload(multipartFormData: multipartFormData, with: request) { result in switch result { case .success(let alamoRequest, _, _): if cancellable.isCancelled { self.cancelCompletion(completion, target: target) return } cancellable.innerCancellable = self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) case .failure(let error): completion(.failure(Moya.Error.underlying(error as NSError))) } } return cancellable } func sendUploadFile(_ target: Target, request: URLRequest, queue: DispatchQueue?, file: URL, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken { let uploadRequest = manager.upload(file, with: request) let alamoRequest = target.validate ? uploadRequest.validate() : uploadRequest return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } func sendDownloadRequest(_ target: Target, request: URLRequest, queue: DispatchQueue?, destination: @escaping DownloadDestination, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken { let downloadRequest = manager.download(request, to: destination) let alamoRequest = target.validate ? downloadRequest.validate() : downloadRequest return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } func sendRequest(_ target: Target, request: URLRequest, queue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken { let initialRequest = manager.request(request as URLRequestConvertible) let alamoRequest = target.validate ? initialRequest.validate() : initialRequest return sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } func sendAlamofireRequest<T>(_ alamoRequest: T, target: Target, queue: DispatchQueue?, progress progressCompletion: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken where T: Requestable, T: Request { // Give plugins the chance to alter the outgoing request let plugins = self.plugins plugins.forEach { $0.willSend(alamoRequest, target: target) } var progressAlamoRequest = alamoRequest let progressClosure: (Progress) -> Void = { progress in let sendProgress: () -> () = { progressCompletion?(ProgressResponse(progress: progress)) } if let queue = queue { queue.async(execute: sendProgress) } else { sendProgress() } } // Perform the actual request if let _ = progressCompletion { switch progressAlamoRequest { case let downloadRequest as DownloadRequest: if let downloadRequest = downloadRequest.downloadProgress(closure: progressClosure) as? T { progressAlamoRequest = downloadRequest } case let uploadRequest as UploadRequest: if let uploadRequest = uploadRequest.uploadProgress(closure: progressClosure) as? T { progressAlamoRequest = uploadRequest } default: break } } let completionHandler: RequestableCompletion = { response, request, data, error in let result = convertResponseToResult(response, request: request, data: data, error: error) // Inform all plugins about the response plugins.forEach { $0.didReceive(result, target: target) } progressCompletion?(ProgressResponse(response: result.value)) completion(result) } progressAlamoRequest = progressAlamoRequest.response(queue: queue, completionHandler: completionHandler) progressAlamoRequest.resume() return CancellableToken(request: progressAlamoRequest) } } // MARK: - RequestMultipartFormData appending private extension MoyaProvider { func append(data: Data, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { if let mimeType = bodyPart.mimeType { if let fileName = bodyPart.fileName { form.append(data, withName: bodyPart.name, fileName: fileName, mimeType: mimeType) } else { form.append(data, withName: bodyPart.name, mimeType: mimeType) } } else { form.append(data, withName: bodyPart.name) } } func append(fileURL url: URL, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { if let fileName = bodyPart.fileName, let mimeType = bodyPart.mimeType { form.append(url, withName: bodyPart.name, fileName: fileName, mimeType: mimeType) } else { form.append(url, withName: bodyPart.name) } } func append(stream: InputStream, length: UInt64, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { form.append(stream, withLength: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "") } } /// Encode parameters for multipart/form-data private func multipartQueryComponents(_ key: String, _ value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += multipartQueryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [Any] { for value in array { components += multipartQueryComponents("\(key)[]", value) } } else { components.append((key, "\(value)")) } return components }
mit
db3b61b71aec09eeb338dadf7a54b751
47.637288
286
0.624756
5.526965
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Networking/DataDownloader.swift
1
3006
// // DataDownloader.swift // Inbbbox // // Created by Lukasz Pikor on 18.03.2016. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import UIKit class DataDownloader: NSObject { fileprivate var data = NSMutableData() fileprivate var totalSize = Float(0) fileprivate var progress: ((Float) -> Void)? fileprivate var completion: ((Data) -> Void)? fileprivate var session: URLSession? var tasks = [URLSessionTask]() /// Fetches data from given URL and gives information about progress and completion of operation. /// Will not fetch if task with given url is already in progress. /// /// - parameter url: URL to fetch data from. /// - parameter progress: Block called every time when portion of data is fetched. /// Gives information about progress. /// - parameter completion: Block called when fetching is complete. It returns fetched data as parameter. func fetchData(_ url: URL, progress:@escaping (_ progress: Float) -> Void, completion:@escaping (_ data: Data) -> Void) { guard !isTaskWithUrlAlreadyInProgress(with: url) else { return } self.progress = progress self.completion = completion session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) if let task = session?.dataTask(with: url) { tasks.append(task) task.resume() } } /// Cancel all NSURLSessionDataTask that are in progress /// func cancelAllFetching() { tasks.forEach() { $0.cancel() } } } extension DataDownloader: URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { completionHandler(.allow) totalSize = Float(response.expectedContentLength) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { let percentOfProgress = Float(self.data.length) / totalSize guard percentOfProgress < 1 else { session.invalidateAndCancel() tasks.remove(ifContains: dataTask) return } self.data.append(data) progress?(percentOfProgress) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { tasks.remove(ifContains: task) guard error == nil else { return } completion?(self.data as Data) } } private extension DataDownloader { func isTaskWithUrlAlreadyInProgress(with url: URL) -> Bool { return tasks.contains() { task -> Bool in return task.currentRequest?.url?.absoluteString == url.absoluteString } } }
gpl-3.0
c09a29f3f4f0253c850273b36df8de8c
33.94186
125
0.631281
5.084602
false
false
false
false
HenvyLuk/BabyGuard
BabyGuard/BabyGuard/MVC/Controller/LoginViewController.swift
1
22027
// // LoginViewController.swift // BabyGuard // // Created by csh on 16/7/5. // Copyright © 2016年 csh. All rights reserved. // import UIKit typealias block = (Int)->() class LoginViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UIScrollViewDelegate,UIAlertViewDelegate, UITextFieldDelegate{ @IBOutlet weak var loading: UIActivityIndicatorView! @IBOutlet weak var pwd: UILabel! @IBOutlet weak var user: UILabel! @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! var userName = "" var passWord = "" @IBOutlet weak var toolBar: UIToolbar! @IBOutlet weak var areaPickView: UIPickerView! @IBOutlet weak var areaLabel: UIButton! @IBOutlet weak var tipsLabel: UILabel! var curReqID = NSNumber() var guid = String() var hud = MBProgressHUD() var areaArray: [NSDictionary] = [] var hostNames = [String]() //var isAutoLogin = Bool() var serviceArray = [Information]() var timer = NSTimer() var blur = FXBlurView() var timerInterval = CGFloat(0) var a = 0 var isAutoLogin = Bool() //1242 × 2208 @IBOutlet weak var loginView: UIButton! @IBOutlet weak var myScrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.setNavigationBarHidden(true, animated: true) self.loginView.layer.cornerRadius = 5 self.loading.hidesWhenStopped = true self.loading.hidden = true NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.loginFailNotice), name: "loginFailNotice", object: nil) //self.username.text = "ceshilhw" //self.username.text = "teacher3" //self.password.text = "1234" let urlString = Definition.listDomain() RequestCenter.defaultCenter().getHttpRequest(withUtl: urlString, success: self.listDomainSuc, cancel: {}, failure: self.listDomainFail) self.scrollView() self.addTimer() self.myScrollView.userInteractionEnabled = false self.addBlurView() //NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LoginViewController.test), userInfo: nil, repeats: true) // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) self.myScrollView.contentOffset.y = 100 self.isAutoLogin = false if Platform.isSimulator { var udid = XKeychainHelper.loadDataForKey(Definition.KEY_KC_UDID) as? String if udid == nil { udid = XKeychainHelper.generateUDID() ApplicationCenter.defaultCenter().udid = udid XKeychainHelper.saveData(udid, forKey: Definition.KEY_KC_UDID) print("udid:\(udid)") }else { ApplicationCenter.defaultCenter().udid = udid } }else { print("do nothing") } let userName = XKeychainHelper.loadDataForKey(Definition.KEY_KC_LAST_NAME) if userName != nil { let userInfoDic = XKeychainHelper.loadDataForKey(Definition.KEY_KC_PREFIX + String(userName)) as? NSDictionary if (userInfoDic != nil) { print(userInfoDic) let guid = userInfoDic![Definition.KEY_KC_GUID] as? String if guid != nil { self.guid = guid! }else{ self.guid = "" } let domain = userInfoDic![Definition.KEY_KC_DOMAIN] let userID = XKeychainHelper.loadDataForKey(Definition.KEY_URL_USER_ID) //let classID = ToolHelper.cacheInfoGet(Definition.KEY_CLASSID) ApplicationCenter.defaultCenter().wanDomain = domain as? String ApplicationCenter.defaultCenter().curUser?.userID = userID as! String //ApplicationCenter.defaultCenter().curClass?.identifier = classID self.isAutoLogin = true self.password.text = userInfoDic![Definition.KEY_KC_PASSWORD] as? String self.username.text = XKeychainHelper.loadDataForKey(Definition.KEY_KC_LAST_NAME) as? String if XKeychainHelper.loadDataForKey(Definition.KEY_KC_DOMAINNAME) as? String != nil { self.tipsLabel.text = XKeychainHelper.loadDataForKey(Definition.KEY_KC_DOMAINNAME) as? String } print(domain) print(userID) print(self.username.text) print(self.password.text) }else { self.guid = "" } } if isAutoLogin == true { } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func test() { //print("aaa") a += 1 print(a,self.myScrollView.contentOffset.y) } func addBlurView() { let cover = UIView.init(frame: CGRectMake(0, 0, self.view.frame.width, self.myScrollView.contentSize.height)) cover.alpha = 0.5 cover.backgroundColor = UIColor.blackColor() self.myScrollView.addSubview(cover) } func scrollView() { self.myScrollView.delegate = self for i in 1..<3 { let imageViewX = CGFloat(0) let imageViewY = CGFloat(i - 1) * (self.view.bounds.size.height) let imageViewW = self.view.bounds.size.width let imageViewH = self.view.bounds.size.height let myImageView = UIImageView.init(frame: CGRectMake(imageViewX, imageViewY, imageViewW, imageViewH)) let name = String(i) myImageView.image = UIImage(named: name) self.myScrollView.addSubview(myImageView) } self.myScrollView.contentSize = CGSizeMake(self.view.bounds.size.width, 2 * self.view.bounds.size.height) self.myScrollView.contentOffset.y = 100 } func addTimer() { let bottomOffset = CGPointMake(0, self.view.frame.size.height * 0.25 + 100) let scrollDurationInSeconds = CGFloat(15.0) let totalScrollAmount = CGFloat(bottomOffset.y) let timerInterval = scrollDurationInSeconds / totalScrollAmount self.timerInterval = timerInterval NSTimer.scheduledTimerWithTimeInterval(Double(timerInterval), target: self, selector: #selector(LoginViewController.cycleImage), userInfo: nil, repeats: true) //#selector(LoginViewController.cycleImage) } func cycleImage(withTimer timer: NSTimer) { var newScrollViewContentOffset = self.myScrollView.contentOffset newScrollViewContentOffset.y += 1 self.myScrollView.contentOffset = newScrollViewContentOffset if (newScrollViewContentOffset.y == self.view.bounds.height * 0.25 + 100) { timer.invalidate() NSTimer.scheduledTimerWithTimeInterval(Double(timerInterval), target: self, selector: #selector(LoginViewController.backCycleImage), userInfo: nil, repeats: true) } } func backCycleImage(withTimer timer: NSTimer) { var newScrollViewContentOffset = self.myScrollView.contentOffset newScrollViewContentOffset.y -= 1 self.myScrollView.contentOffset = newScrollViewContentOffset if (newScrollViewContentOffset.y == 0) { timer.invalidate() NSTimer.scheduledTimerWithTimeInterval(Double(timerInterval), target: self, selector: #selector(LoginViewController.cycleImage), userInfo: nil, repeats: true) } } func controlsMoving(withUp isUp: Bool) { let controls = [self.areaLabel,self.tipsLabel,self.loginView,self.username,self.password] UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { if isUp { for (_, value) in controls.enumerate() { value.frame = CGRectMake(value.frame.origin.x, value.frame.origin.y - 40, value.frame.width, value.frame.height) } }else { for (_, value) in controls.enumerate() { value.frame = CGRectMake(value.frame.origin.x, value.frame.origin.y + 40, value.frame.width, value.frame.height) } } }, completion: nil) } func textFieldDidBeginEditing(textField: UITextField) { print("bbbbb") self.controlsMoving(withUp: true) } func textFieldDidEndEditing(textField: UITextField) { print("eeeeee") self.controlsMoving(withUp: false) } @IBAction func areaClick(sender: AnyObject) { self.controlsMoving(withUp: true) let h = UIScreen.mainScreen().bounds.height UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.toolBar.frame = CGRectMake(0, h - self.areaPickView.frame.height - 44, self.toolBar.frame.width, 44) print(self.areaPickView.frame.height) self.areaPickView.frame = CGRectMake(0, h - self.areaPickView.frame.height, self.areaPickView.frame.width, self.areaPickView.frame.height) }) { (true) in self.tipsLabel.text = self.hostNames[0] } } func pickViewHide() { self.controlsMoving(withUp: false) let h = UIScreen.mainScreen().bounds.height UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.blur.removeFromSuperview() self.toolBar.frame = CGRectMake(0, h, self.toolBar.frame.width, 44) self.areaPickView.frame = CGRectMake(0, h + 44, self.areaPickView.frame.width, self.areaPickView.frame.height) }) { (true) in } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { //self.pickViewHide() if self.username.isFirstResponder() { self.username.resignFirstResponder() //self.controlsMoving(withUp: false) } if self.password.isFirstResponder() { self.password.resignFirstResponder() //self.controlsMoving(withUp: false) } } @IBAction func dismissPickerView(sender: AnyObject) { self.pickViewHide() } @IBAction func makeSureWithArea(sender: AnyObject) { self.pickViewHide() for (index, value) in self.areaArray.enumerate() { let name = value[Definition.KEY_DATA_HOST_NAME] as! String if name == self.tipsLabel.text { let dic = self.areaArray[index] ApplicationCenter.defaultCenter().wanDomain = dic[Definition.KEY_DATA_HOST_DOMAIN] as? String XKeychainHelper.saveData(name, forKey: Definition.KEY_KC_DOMAINNAME) } } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.hostNames.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.hostNames[row] } func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 150 } func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 30 } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { UIView.animateWithDuration(0.2) { self.tipsLabel.text = self.hostNames[row] } } func listDomainSuc(data: String) { hud.show(true) let content = XConnectionHelper.contentOfWanServerString(data) if (content != nil) { if ((content[Definition.KEY_SER_SUC]?.isEqual("true")) != nil) { let count = content[Definition.KEY_SER_COUNT] as? String if NSInteger(count!) > 0 { let dataArray = content[Definition.KEY_SER_DATA] as? NSArray for (_,value) in (dataArray?.enumerate())! { let hostname = value[Definition.KEY_DATA_HOST_NAME] as! String let hostDomain = value[Definition.KEY_DATA_HOST_DOMAIN] as! String let hostDic: Dictionary<String, String> = [Definition.KEY_DATA_HOST_NAME: hostname,Definition.KEY_DATA_HOST_DOMAIN: hostDomain] self.areaArray.append(hostDic) self.hostNames.append(hostname) } dispatch_async(dispatch_get_main_queue(), { self.hud.hide(true) self.areaPickView.reloadAllComponents() }) } } } } func listDomainFail(data: String) { } func login(withUsername userName: String, passWord: String) { if userName == "" { AlertHelper.showConfirmAlert("请输入用户名", delegate: nil, type: 0) return } if passWord == "" { AlertHelper.showConfirmAlert("请输入密码", delegate: nil, type: 0) return } if (self.tipsLabel.text == "请选择区域") { AlertHelper.showConfirmAlert("请先选择区域", delegate: nil, type: 0) return } var parameters = [NSObject : AnyObject]() //parameters["CheckID"] = Definition.PARA_CHECK_ID parameters["Para1"] = ApplicationCenter.defaultCenter().clientID parameters["Para2"] = userName parameters["Para3"] = passWord var loginStr = "" if Platform.isSimulator { // loginStr = Definition.loginUrl(withDomain: ApplicationCenter.defaultCenter().wanDomain!, userName: self.username.text!, passWord: self.password.text!, phoneSerial: ApplicationCenter.defaultCenter().udid!, verifyID: self.guid) loginStr = Definition.loginUrlGT(withDomain: ApplicationCenter.defaultCenter().wanDomain!, userName: userName, passWord: passWord, GTSerial: ApplicationCenter.defaultCenter().udid!, verifyID: self.guid) print("loginStr:\(loginStr)") }else { if ApplicationCenter.defaultCenter().udid == nil { loginStr = Definition.loginUrlGT(withDomain: ApplicationCenter.defaultCenter().wanDomain!, userName: userName, passWord: passWord, GTSerial: "NotGotClientID", verifyID: self.guid) }else { loginStr = Definition.loginUrlGT(withDomain: ApplicationCenter.defaultCenter().wanDomain!, userName: userName, passWord: passWord, GTSerial: ApplicationCenter.defaultCenter().udid!, verifyID: self.guid) } } RequestCenter.defaultCenter().postHttpRequest(withUrl: loginStr, parameters: nil, filePath: nil, progress: nil, success: self.loginGotSucResponse, cancel: {}, failure: self.loginGotFailResponse) } @IBAction func loginBtnAction() { //dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { self.login(withUsername: self.username.text!, passWord: self.password.text!) //}) } func loginGotSucResponse(data: String) { let content = XConnectionHelper.contentOfWanServerString(data) if (content != nil) { print("userInfo:\(content)") if (content[Definition.KEY_SER_SUC] as! String == "true") { if let dataDic = content[Definition.KEY_SER_DATA] as? NSDictionary{ let userInfo = UserInfo.userInfoFromServerData(dataDic) ApplicationCenter.defaultCenter().curUser = userInfo // 保存用户信息 let guid = dataDic[Definition.KEY_DATA_GUID] as! String let userInfoDic: Dictionary<String, String> = [Definition.KEY_KC_PASSWORD: self.password.text!, Definition.KEY_KC_GUID: guid ,Definition.KEY_KC_DOMAIN: ApplicationCenter.defaultCenter().wanDomain!] XKeychainHelper.saveData(userInfoDic, forKey: Definition.KEY_KC_PREFIX + self.username.text!) XKeychainHelper.saveData(self.username.text, forKey: Definition.KEY_KC_LAST_NAME) XKeychainHelper.saveData(userInfo.userID, forKey: Definition.KEY_URL_USER_ID) //XKeychainHelper.saveData(userInfo, forKey: Definition.KEY_KC_CURUSERINFO) let urlString = Definition.listSchoolServers(withDomain: ApplicationCenter.defaultCenter().wanDomain!, userID: dataDic[Definition.KEY_DATA_ID] as! String, schoolID: dataDic[Definition.KEY_SER_DEPT_SCHID] as! String) RequestCenter.defaultCenter().getHttpRequest(withUtl: urlString, success: self.listSchoolServerSuc, cancel: {}, failure: self.listSchoolServerFail) self.loading.hidden = false self.loading.startAnimating() self.loginView.userInteractionEnabled = false dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.loading.stopAnimating() self.loading.hidden = true self.loginView.userInteractionEnabled = true let listViewCon = ListViewController() self.navigationController?.pushViewController(listViewCon, animated: true) } } }else { self.loading.hidden = false self.loading.startAnimating() self.loginView.userInteractionEnabled = false dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.loading.stopAnimating() dispatch_async(dispatch_get_main_queue(), { self.loginFailNotice() dispatch_async(dispatch_get_main_queue(), { self.loginFailNotice() }) }) } } } } func loginFailNotice() { let positionAnimation = POPSpringAnimation(propertyNamed: "positionX") positionAnimation.velocity = 10000 positionAnimation.springBounciness = 20 self.loginView.layer.pop_addAnimation(positionAnimation, forKey: "positionAnimation") self.loading.hidden = true self.loginView.userInteractionEnabled = true print("a") } func listSchoolServerSuc(data: String) { let content = XConnectionHelper.contentOfWanServerString(data) if (content != nil) { print("SchoolServerInfo:\(content)") if ((content[Definition.KEY_SER_SUC]?.isEqual("true")) != nil) { if let dataArray = content[Definition.KEY_SER_DATA] as? NSArray { var urlStr = [String]() for (_,value) in dataArray.enumerate() { let schSerInfo = Information() schSerInfo.name = value[Definition.KEY_DATA_SER_NAME] as! String schSerInfo.identifier = value[Definition.KEY_DATA_SER_URL] as! String self.serviceArray.append(schSerInfo) urlStr.append(value[Definition.KEY_DATA_SER_URL] as! String) } ToolHelper.cacheInfoSet(Definition.KEY_SERVICEURL, value: urlStr[0]) ApplicationCenter.defaultCenter().lanDomain = urlStr[0] } } } } func listSchoolServerFail(data: String) { } func loginGotFailResponse(data: String) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { print("login deinit") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
2d6261e6aeb6111be5a3674630e573f7
38.360215
251
0.583072
4.984793
false
false
false
false
ta2yak/Hokusai
Classes/Hokusai.swift
1
15748
// // Hokusai.swift // Hokusai // // Created by Yuta Akizuki on 2015/07/07. // Copyright (c) 2015年 ytakak. All rights reserved. // import UIKit private struct HOKConsts { let animationDuration:NSTimeInterval = 0.8 let hokusaiTag = 9999 } // Action Types public enum HOKAcitonType { case None, Selector, Closure } // Color Types public enum HOKColorScheme { case Hokusai, Asagi, Matcha, Tsubaki, Inari, Karasu, Enshu func getColors() -> HOKColors { switch self { case .Asagi: return HOKColors( backGroundColor: UIColorHex(0x0bada8), buttonColor: UIColorHex(0x08827e), cancelButtonColor: UIColorHex(0x6dcecb), fontColor: UIColorHex(0xffffff) ) case .Matcha: return HOKColors( backGroundColor: UIColorHex(0x314631), buttonColor: UIColorHex(0x618c61), cancelButtonColor: UIColorHex(0x496949), fontColor: UIColorHex(0xffffff) ) case .Tsubaki: return HOKColors( backGroundColor: UIColorHex(0xe5384c), buttonColor: UIColorHex(0xac2a39), cancelButtonColor: UIColorHex(0xc75764), fontColor: UIColorHex(0xffffff) ) case .Inari: return HOKColors( backGroundColor: UIColorHex(0xdd4d05), buttonColor: UIColorHex(0xa63a04), cancelButtonColor: UIColorHex(0xb24312), fontColor: UIColorHex(0x231e1c) ) case .Karasu: return HOKColors( backGroundColor: UIColorHex(0x180614), buttonColor: UIColorHex(0x3d303d), cancelButtonColor: UIColorHex(0x261d26), fontColor: UIColorHex(0x9b9981) ) case .Enshu: return HOKColors( backGroundColor: UIColorHex(0xccccbe), buttonColor: UIColorHex(0xffffff), cancelButtonColor: UIColorHex(0xe5e5d8), fontColor: UIColorHex(0x9b9981) ) default: // Hokusai return HOKColors( backGroundColor: UIColorHex(0x00AFF0), buttonColor: UIColorHex(0x197EAD), cancelButtonColor: UIColorHex(0x1D94CA), fontColor: UIColorHex(0xffffff) ) } } private func UIColorHex(hex: UInt) -> UIColor { return UIColor( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } final public class HOKColors: NSObject { var backgroundColor: UIColor var buttonColor: UIColor var cancelButtonColor: UIColor var fontColor: UIColor init(backGroundColor: UIColor, buttonColor: UIColor, cancelButtonColor: UIColor, fontColor: UIColor) { self.backgroundColor = backGroundColor self.buttonColor = buttonColor self.cancelButtonColor = cancelButtonColor self.fontColor = fontColor } } final public class HOKButton: UIButton { var target:AnyObject! var selector:Selector! var action:(()->Void)! var actionType = HOKAcitonType.None var isCancelButton = false // Font let kDefaultFont = "AvenirNext-DemiBold" let kFontSize:CGFloat = 16.0 func setColor(colors: HOKColors) { self.setTitleColor(colors.fontColor, forState: .Normal) self.backgroundColor = (isCancelButton) ? colors.cancelButtonColor : colors.buttonColor } func setFontName(fontName: String?) { var name:String name = kDefaultFont if !(fontName?.isEmpty != nil) { if let fontName = fontName { name = fontName } } self.titleLabel?.font = UIFont(name: name, size:kFontSize) } } final public class HOKMenuView: UIView { var colorScheme = HOKColorScheme.Hokusai public let kDamping: CGFloat = 0.7 public let kInitialSpringVelocity: CGFloat = 0.8 private var displayLink: CADisplayLink? private let shapeLayer = CAShapeLayer() private var bendableOffset = UIOffsetZero override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } override public func layoutSubviews() { super.layoutSubviews() shapeLayer.frame.origin = frame.origin shapeLayer.bounds.origin = frame.origin } func setShapeLayer(colors: HOKColors) { self.backgroundColor = UIColor.clearColor() shapeLayer.fillColor = colors.backgroundColor.CGColor self.layer.insertSublayer(shapeLayer, atIndex: 0) } func positionAnimationWillStart() { if displayLink == nil { displayLink = CADisplayLink(target: self, selector: "tick:") displayLink!.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } let newPosition = layer.frame.origin shapeLayer.bounds = CGRect(origin: CGPointZero, size: self.bounds.size) } func updatePath() { let width = CGRectGetWidth(shapeLayer.bounds) let height = CGRectGetHeight(shapeLayer.bounds) let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: 0)) path.addQuadCurveToPoint(CGPoint(x: width, y: 0), controlPoint:CGPoint(x: width * 0.5, y: 0 + bendableOffset.vertical)) path.addQuadCurveToPoint(CGPoint(x: width, y: height + 100.0), controlPoint:CGPoint(x: width + bendableOffset.horizontal, y: height * 0.5)) path.addQuadCurveToPoint(CGPoint(x: 0, y: height + 100.0), controlPoint: CGPoint(x: width * 0.5, y: height + 100.0)) path.addQuadCurveToPoint(CGPoint(x: 0, y: 0), controlPoint: CGPoint(x: bendableOffset.horizontal, y: height * 0.5)) path.closePath() shapeLayer.path = path.CGPath } func tick(displayLink: CADisplayLink) { if let presentationLayer = layer.presentationLayer() as? CALayer { var verticalOffset = self.layer.frame.origin.y - presentationLayer.frame.origin.y // On dismissing, the offset should not be offend on the buttons. if verticalOffset > 0 { verticalOffset *= 0.2 } bendableOffset = UIOffset( horizontal: 0.0, vertical: verticalOffset ) updatePath() if verticalOffset == 0 { self.displayLink!.invalidate() self.displayLink = nil } } } } final public class Hokusai: UIViewController, UIGestureRecognizerDelegate { // Views private var menuView = HOKMenuView() private var buttons = [HOKButton]() private var instance:Hokusai! = nil private var kButtonWidth:CGFloat = 250 private let kButtonHeight:CGFloat = 48.0 private let kButtonInterval:CGFloat = 16.0 private var bgColor = UIColor(white: 1.0, alpha: 0.7) // Variables users can change public var colorScheme = HOKColorScheme.Hokusai public var cancelButtonTitle = "Cancel" public var fontName = "" public var colors:HOKColors! = nil required public init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } required public init() { super.init(nibName:nil, bundle:nil) view.frame = UIScreen.mainScreen().bounds view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] view.backgroundColor = UIColor.clearColor() menuView.frame = view.frame view.addSubview(menuView) kButtonWidth = view.frame.width * 0.8 // Gesture Recognizer for tapping outside the menu let tapGesture = UITapGestureRecognizer(target: self, action: Selector("dismiss")) tapGesture.numberOfTapsRequired = 1 tapGesture.delegate = self self.view.addGestureRecognizer(tapGesture) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onOrientationChange:", name: UIDeviceOrientationDidChangeNotification, object: nil) } func onOrientationChange(notification: NSNotification){ kButtonWidth = view.frame.width * 0.8 let menuHeight = CGFloat(buttons.count + 2) * kButtonInterval + CGFloat(buttons.count) * kButtonHeight menuView.frame = CGRect( x: 0, y: view.frame.height - menuHeight, width: view.frame.width, height: menuHeight ) menuView.shapeLayer.frame = menuView.frame menuView.shapeLayer.bounds.origin = menuView.frame.origin menuView.shapeLayer.layoutIfNeeded() menuView.layoutIfNeeded() for var i = 0; i < buttons.count; i++ { let btn = buttons[i] btn.frame = CGRect(x: 0.0, y: 0.0, width: kButtonWidth, height: kButtonHeight) btn.center = CGPoint(x: view.center.x, y: -kButtonHeight * 0.25 + (kButtonHeight + kButtonInterval) * CGFloat(i + 1)) } self.view.layoutIfNeeded() } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if touch.view != gestureRecognizer.view { return false } return true } // Add a button with a closure public func addButton(title:String, action:()->Void) -> HOKButton { let btn = addButton(title) btn.action = action btn.actionType = HOKAcitonType.Closure btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside) return btn } // Add a button with a selector public func addButton(title:String, target:AnyObject, selector:Selector) -> HOKButton { let btn = addButton(title) btn.target = target btn.selector = selector btn.actionType = HOKAcitonType.Selector btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside) return btn } // Add a cancel button with a selector public func addCancelButton(title:String) -> HOKButton { let btn = addButton(title) btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside) btn.isCancelButton = true return btn } // Add a button just with the title private func addButton(title:String) -> HOKButton { let btn = HOKButton() btn.layer.masksToBounds = true btn.setTitle(title, forState: .Normal) menuView.addSubview(btn) buttons.append(btn) return btn } // Show the menu public func show() { if let rv = UIApplication.sharedApplication().keyWindow { if rv.viewWithTag(HOKConsts().hokusaiTag) == nil { view.tag = HOKConsts().hokusaiTag.hashValue rv.addSubview(view) } } else { print("Hokusai:: You have to call show() after the controller has appeared.") return } // This is needed to retain this instance. instance = self let colors = (self.colors == nil) ? colorScheme.getColors() : self.colors // Set a background color of Menuview menuView.setShapeLayer(colors) // Add a cancel button self.addCancelButton("Done") // Decide the menu size let menuHeight = CGFloat(buttons.count + 2) * kButtonInterval + CGFloat(buttons.count) * kButtonHeight menuView.frame = CGRect( x: 0, y: view.frame.height - menuHeight, width: view.frame.width, height: menuHeight ) // Locate buttons for var i = 0; i < buttons.count; i++ { let btn = buttons[i] btn.frame = CGRect(x: 0.0, y: 0.0, width: kButtonWidth, height: kButtonHeight) btn.center = CGPoint(x: view.center.x, y: -kButtonHeight * 0.25 + (kButtonHeight + kButtonInterval) * CGFloat(i + 1)) btn.layer.cornerRadius = kButtonHeight * 0.5 btn.setFontName(fontName) btn.setColor(colors) } // Animations animationWillStart() // Debug if (buttons.count == 0) { print("Hokusai:: The menu has no item yet.") } else if (buttons.count > 6) { print("Hokusai:: The menu has lots of items.") } } // Add an animation on showing the menu private func animationWillStart() { // Background self.view.backgroundColor = UIColor.clearColor() UIView.animateWithDuration(HOKConsts().animationDuration * 0.4, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.view.backgroundColor = self.bgColor }, completion: nil ) // Menuview menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height), size: menuView.frame.size) UIView.animateWithDuration(HOKConsts().animationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.6, options: [.BeginFromCurrentState, .AllowUserInteraction, .OverrideInheritedOptions], animations: { self.menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height-self.menuView.frame.height), size: self.menuView.frame.size) self.menuView.layoutIfNeeded() }, completion: {(finished) in }) menuView.positionAnimationWillStart() } // Dismiss the menuview public func dismiss() { // Background and Menuview UIView.animateWithDuration(HOKConsts().animationDuration, delay: 0.0, usingSpringWithDamping: 100.0, initialSpringVelocity: 0.6, options: [.BeginFromCurrentState, .AllowUserInteraction, .OverrideInheritedOptions, .CurveEaseOut], animations: { self.view.backgroundColor = UIColor.clearColor() self.menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height), size: self.menuView.frame.size) }, completion: {(finished) in self.view.removeFromSuperview() }) menuView.positionAnimationWillStart() } // When the buttons are tapped, this method is called. func buttonTapped(btn:HOKButton) { if btn.actionType == HOKAcitonType.Closure { btn.action() } else if btn.actionType == HOKAcitonType.Selector { let control = UIControl() control.sendAction(btn.selector, to:btn.target, forEvent:nil) } else { print("Unknow action type for button") } dismiss() } }
mit
dfcaa3e21794ac852352514ee6f43713
34.624434
157
0.596024
4.862878
false
false
false
false
emilwojtaszek/collection-view-layout-examples
ExampleApp/DecorationLayout.swift
1
3527
// // DecorationLayout.swift // ExampleApp // // Created by Emil Wojtaszek on 12/03/2017. // Copyright © 2017 AppUnite Sp. z o.o. All rights reserved. // import UIKit class DecorationLayout: UICollectionViewFlowLayout { /// struct of layout constants private struct Constants { struct Footer { static let kind = "footer" static let height: CGFloat = 100.0 static let indexPath = IndexPath(item: 1, section: 0) } } /// generated additional layout attributed private var footerLayoutAttributes: UICollectionViewLayoutAttributes? required public override init() { super.init() self.registerDecorationView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.registerDecorationView() } /// MARK: - Preparation override func prepare() { super.prepare() // on each bounds change regenerate footer attributes prepareFooterViewAttributes() } fileprivate func prepareFooterViewAttributes() { guard let collectionView = collectionView else { return } // create attributes for footer decoration view footerLayoutAttributes = UICollectionViewLayoutAttributes( forDecorationViewOfKind: Constants.Footer.kind, with: Constants.Footer.indexPath ) // put it below other content footerLayoutAttributes!.zIndex = -1 // calculate size (put at the end of content and stick to bottom edge) let contentSize = self.collectionViewContentSize let height = max(0, collectionView.contentOffset.y + collectionView.frame.height - collectionView.contentInset.bottom - contentSize.height) let size = CGSize(width: collectionView.frame.width, height: max(Constants.Footer.height, height)) let origin = CGPoint(x: 0.0, y: contentSize.height) let factor = min(max(height / Constants.Footer.height, 0.0), 1.0) // assign all attributes footerLayoutAttributes!.frame = CGRect(origin: origin, size: size) footerLayoutAttributes!.alpha = factor footerLayoutAttributes!.transform = CGAffineTransform(scaleX: factor, y: factor) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // inherited attributes from UICollectionViewFlowLayout implementation var attributes = super.layoutAttributesForElements(in: rect) ?? [] guard let footerAttributes = footerLayoutAttributes else { return attributes } // append to list of visible attributes when intersect with visible rect if rect.intersects(footerAttributes.frame) { attributes.append(footerAttributes) } return attributes } override public func layoutAttributesForDecorationView( ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return footerLayoutAttributes } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } /// MARK: - Private private func registerDecorationView() { /// decorations view in contrast to cells and supplementary view do no represents any data /// and are registered directly in layout self.register(EmojiDecorationView.self, forDecorationViewOfKind: Constants.Footer.kind) } }
mit
22734adf5bf979b16dd18672c1a0cf15
33.568627
147
0.673284
5.475155
false
false
false
false
BellAppLab/Keyboard
Sources/Keyboard/UIViewController+Autolayout+Keyboard.swift
1
4524
import ObjectiveC import UIKit //MARK: - ORIGINAL CONSTANTS //MARK: - Assotiation Keys private extension AssociationKeys { static var originalConstants = "com.bellapplab.originalConstants.key" } //MARK: - UIViewController + Original Constants @nonobjc internal extension UIViewController { fileprivate(set) var originalConstants: [String: CGFloat]? { get { guard handlesKeyboard, let nsDictionary = objc_getAssociatedObject(self, &AssociationKeys.originalConstants) as? NSDictionary else { return nil } var result = [String: CGFloat]() nsDictionary.forEach { if let key = $0.key as? String, let constant = ($0.value as? NSNumber)?.doubleValue { result[key] = CGFloat(constant) } } return result } set { let nsDictionary: NSDictionary? let dictionary = newValue?.mapValues { NSNumber(floatLiteral: Double($0)) } if handlesKeyboard, dictionary != nil { nsDictionary = NSDictionary(dictionary: dictionary!) } else { nsDictionary = nil } objc_setAssociatedObject(self, &AssociationKeys.originalConstants, nsDictionary, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } //MARK: - KEYBOARD CONSTRAINTS //MARK: - Assotiation Keys private extension AssociationKeys { static var keyboardConstraints = "com.bellapplab.keyboardConstraints.key" } //MARK: - UIViewController + Keyboard Constraints @nonobjc public extension UIViewController { internal var hasKeyboardConstraints: Bool { return handlesKeyboard && keyboardConstraints?.isEmpty ?? true == false } internal func setKeyboardConstraintsToOriginal() { guard hasKeyboardConstraints else { return } keyboardConstraints?.forEach { $0.constant = originalConstants![$0.identifier!]! } view.layoutIfNeeded() } internal func setKeyboardConstraints(intersection: CGRect) { guard hasKeyboardConstraints, intersection != .zero else { return } keyboardConstraints?.forEach { if $0.isCenterY { $0.constant = originalConstants![$0.identifier!]! - intersection.height } else { $0.constant = originalConstants![$0.identifier!]! + intersection.height } } } /// The collection of `NSLayoutConstraint`s that should be updated when the keyboard changes. /// - note: This should only be used if you are using autolayout. @IBOutlet var keyboardConstraints: [NSLayoutConstraint]? { get { if let nsArray = objc_getAssociatedObject(self, &AssociationKeys.keyboardConstraints) as? NSArray { #if swift(>=4.0) return nsArray.compactMap { $0 as? NSLayoutConstraint } #else return nsArray.flatMap { $0 as? NSLayoutConstraint } #endif } return nil } set { Keyboard.yo() if newValue == nil { originalConstants = nil } else { var constants: [String: CGFloat] = [:] let token = "__bl__" (0..<newValue!.count).forEach { i in let constraint = newValue![i] if constraint.identifier?.contains(token) ?? false == false { constraint.identifier = "\(constraint.identifier ?? "")\(token)\(i)" } constants[constraint.identifier!] = constraint.constant } originalConstants = constants } objc_setAssociatedObject(self, &AssociationKeys.keyboardConstraints, newValue != nil ? NSArray(array: newValue!) : nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } //MARK: - Aux fileprivate extension NSLayoutConstraint { var isCenterY: Bool { return firstAttribute == .centerY || firstAttribute == .centerYWithinMargins || secondAttribute == .centerY || secondAttribute == .centerYWithinMargins } }
mit
d578f5750cea8e5ac1addce01629732b
33.8
118
0.564545
5.483636
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/TextField/Validators/TextMatchValidator/CollectionTextMatchValidator.swift
1
2151
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxRelay import RxSwift /// Generalized version of text matcher, resolves a stream from multiple text sources into a boolean /// that is `true` if and only if all the values are equal public final class CollectionTextMatchValidator: TextMatchValidatorAPI { // MARK: - Exposed Properties /// An observable that streams the validation state for the streams public var validationState: Observable<TextValidationState> { validationStateRelay.asObservable() } // MARK: - Injected Properties private let collection: [TextSource] // MARK: - Accessors private let validationStateRelay = BehaviorRelay<TextValidationState>(value: .valid) private let disposeBag = DisposeBag() // MARK: - Setup public init(_ collection: TextSource..., options: Options = [], invalidReason: String) { self.collection = collection Observable .combineLatest(collection.map(\.valueRelay)) .map { array -> Bool in if array.areAllElementsEqual { return true // If there is an empty string in the array and it should be validated } else if array.containsEmpty { return !options.contains(.validateEmpty) } else { return false } } .map { $0 ? .valid : .invalid(reason: invalidReason) } .bindAndCatch(to: validationStateRelay) .disposed(by: disposeBag) } } // MARK: - Validation Options extension CollectionTextMatchValidator { /// Options according to which the text streams are validated public struct Options: OptionSet { public let rawValue: Int public init(rawValue: Self.RawValue) { self.rawValue = rawValue } /// Validate all even though one of the text sources is empty public static let validateEmpty = Options(rawValue: 1 << 0) } } extension Array where Element == String { public var containsEmpty: Bool { contains("") } }
lgpl-3.0
e5fce756fb5aba2f0ab8403b07858918
30.15942
100
0.632093
5.143541
false
false
false
false
jovito-royeca/ManaKit
Sources/Classes/SetTableViewCell.swift
1
6523
// // SetTableViewCell.swift // ManaKit // // Created by Jovito Royeca on 01/01/2019. // import UIKit public protocol SetTableViewCellDelegate: NSObjectProtocol { func languageAction(cell: UITableViewCell, code: String) } public class SetTableViewCell: UITableViewCell { public static let reuseIdentifier = "SetCell" public static let cellHeight = CGFloat(114) // MARK: - Outlets @IBOutlet public weak var logoLabel: UILabel! @IBOutlet public weak var nameLabel: UILabel! @IBOutlet public weak var codeLabel: UILabel! @IBOutlet public weak var releaseDateLabel: UILabel! @IBOutlet public weak var numberLabel: UILabel! @IBOutlet public weak var enButton: UIButton! @IBOutlet public weak var esButton: UIButton! @IBOutlet public weak var frButton: UIButton! @IBOutlet public weak var deButton: UIButton! @IBOutlet public weak var itButton: UIButton! @IBOutlet public weak var ptButton: UIButton! @IBOutlet public weak var jaButton: UIButton! @IBOutlet public weak var koButton: UIButton! @IBOutlet public weak var ruButton: UIButton! @IBOutlet public weak var zhsButton: UIButton! @IBOutlet public weak var zhtButton: UIButton! @IBOutlet public weak var blankButton: UIButton! // MARK: - Actions @IBAction public func languageAction(_ sender: UIButton) { var code = "" if sender == enButton { code = "en" } else if sender == esButton { code = "es" } else if sender == frButton { code = "fr" } else if sender == deButton { code = "de" } else if sender == itButton { code = "it" } else if sender == ptButton { code = "pt" } else if sender == jaButton { code = "ja" } else if sender == koButton { code = "ko" } else if sender == ruButton { code = "ru" } else if sender == zhsButton { code = "zhs" } else if sender == zhtButton { code = "zht" } delegate?.languageAction(cell: self, code: code) } // MARK: - Variables public var set: MGSet! { didSet { logoLabel.text = set.keyruneUnicode2String() nameLabel.text = set.name codeLabel.text = set.code releaseDateLabel.text = set.releaseDate ?? " " numberLabel.text = "\(set.cardCount) cards" enButton.isEnabled = false esButton.isEnabled = false frButton.isEnabled = false deButton.isEnabled = false itButton.isEnabled = false ptButton.isEnabled = false jaButton.isEnabled = false koButton.isEnabled = false ruButton.isEnabled = false zhsButton.isEnabled = false zhtButton.isEnabled = false for l in set.languages ?? NSSet() { if let language = l as? MGLanguage { if language.code == "en" { enButton.isEnabled = true } else if language.code == "es" { esButton.isEnabled = true } else if language.code == "fr" { frButton.isEnabled = true } else if language.code == "de" { deButton.isEnabled = true } else if language.code == "it" { itButton.isEnabled = true } else if language.code == "pt" { ptButton.isEnabled = true } else if language.code == "ja" { jaButton.isEnabled = true } else if language.code == "ko" { koButton.isEnabled = true } else if language.code == "ru" { ruButton.isEnabled = true } else if language.code == "zhs" { zhsButton.isEnabled = true } else if language.code == "zht" { zhtButton.isEnabled = true } } } } } public var delegate: SetTableViewCellDelegate? // MARK: - Overrides override public func awakeFromNib() { super.awakeFromNib() // Initialization code // enButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // enButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // esButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // esButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // frButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // frButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // deButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // deButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // itButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // itButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // ptButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // ptButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // jaButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // jaButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // koButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // koButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // ruButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // ruButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // zhsButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // zhsButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // zhtButton.setBackgroundColor(LookAndFeel.GlobalTintColor, for: .normal) // zhtButton.setBackgroundColor(UIColor.lightGray, for: .disabled) // blankButton.setBackgroundColor(UIColor.lightGray, for: .disabled) } override public func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
c00b775a363594762aa142626a421896
37.827381
81
0.58424
4.672636
false
false
false
false
elpassion/el-space-ios
ELSpace/Commons/Extensions/Double_FromString.swift
1
649
import Foundation extension Double { init?(from string: String?) { guard let string = string else { return nil } if let double = Double(fromCommaSeparatedString: string) { self = double } else if let double = Double(string) { self = double } else { return nil } } private init?(fromCommaSeparatedString string: String) { let formatter = NumberFormatter() formatter.decimalSeparator = "," if let number = formatter.number(from: string) { self = number.doubleValue } else { return nil } } }
gpl-3.0
226912b18d0779348821058f5925a212
23.961538
66
0.5547
4.879699
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Jetpack/Classes/ViewRelated/Login Error/View Models/JetpackNoSitesErrorViewModel.swift
1
2331
import Foundation struct JetpackNoSitesErrorViewModel: JetpackErrorViewModel { let image: UIImage? = UIImage(named: "jetpack-empty-state-illustration") var title: String? = Constants.title var description: FormattedStringProvider = FormattedStringProvider(string: Constants.description) var primaryButtonTitle: String? = Constants.primaryButtonTitle var secondaryButtonTitle: String? = Constants.secondaryButtonTitle func didTapPrimaryButton(in viewController: UIViewController?) { guard let url = URL(string: Constants.helpURLString) else { return } let controller = WebViewControllerFactory.controller(url: url) let navController = UINavigationController(rootViewController: controller) viewController?.present(navController, animated: true) } func didTapSecondaryButton(in viewController: UIViewController?) { AccountHelper.logOutDefaultWordPressComAccount() } private struct Constants { static let title = NSLocalizedString("No Jetpack sites found", comment: "Title when users have no Jetpack sites.") static let description = NSLocalizedString("If you already have a site, you’ll need to install the free Jetpack plugin and connect it to your WordPress.com account.", comment: "Message explaining that they will need to install Jetpack on one of their sites.") static let primaryButtonTitle = NSLocalizedString("See Instructions", comment: "Action button linking to instructions for installing Jetpack." + "Presented when logging in with a site address that does not have a valid Jetpack installation") static let secondaryButtonTitle = NSLocalizedString("Try With Another Account", comment: "Action button that will restart the login flow." + "Presented when logging in with a site address that does not have a valid Jetpack installation") static let helpURLString = "https://jetpack.com/support/getting-started-with-jetpack/" } }
gpl-2.0
91d198857c129decfb275e21b738dbde
53.162791
174
0.644483
6.210667
false
false
false
false
BridgeTheGap/KRMathInputView
KRMathInputView/Classes/Model/Ink.swift
1
2127
// // Ink.swift // TestScript // // Created by Joshua Park on 08/02/2017. // Copyright © 2017 Knowre. All rights reserved. // import UIKit @objc public protocol InkType { var path: UIBezierPath { get } var frame: CGRect { get } } @objc public protocol CharacterInkType: InkType { var character: String { get } } @objc public protocol RemovingInkType: InkType { var indexes: Set<Int> { get } } @objc public protocol ObjCConvertible { var objCType: NSObject { get } } public typealias ObjCInk = InkType & ObjCConvertible public class StrokeInk: NSObject, ObjCInk { public let path: UIBezierPath public var frame: CGRect { return path.bounds } public var objCType: NSObject { return NSArray(array: path.points.map { NSValue(cgPoint: $0) }) } public init(path: UIBezierPath) { self.path = path } } @objc public class CharacterInkValue: NSObject { @objc public let character: NSString @objc public let frame: NSValue init(character: String, frame: CGRect) { self.character = NSString(string: character) self.frame = NSValue(cgRect: frame) } init(string: NSString, frame: NSValue) { self.character = string self.frame = frame } } public class CharacterInk: NSObject, ObjCInk, CharacterInkType, RemovingInkType { public let character: String public let path: UIBezierPath public var frame: CGRect { return path.bounds } public var objCType: NSObject { return CharacterInkValue(character: character, frame: frame) } public let indexes: Set<Int> init(character: String, path: UIBezierPath, indexes: Set<Int>) { self.character = character self.path = path self.indexes = indexes } } internal class RemovedInk: NSObject, RemovingInkType { internal let indexes: Set<Int> internal let path: UIBezierPath var frame: CGRect { return path.bounds } init(indexes: Set<Int>, path: UIBezierPath) { self.indexes = indexes self.path = path } }
mit
d2b1f0c0f9168c5817e5b9007d9723e6
21.617021
81
0.647225
4.136187
false
false
false
false
brettg/Signal-iOS
Signal/src/views/ContactCell.swift
1
4882
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import UIKit import Contacts @available(iOS 9.0, *) class ContactCell: UITableViewCell { static let nib = UINib(nibName:"ContactCell", bundle: nil) @IBOutlet weak var contactTextLabel: UILabel! @IBOutlet weak var contactDetailTextLabel: UILabel! @IBOutlet weak var contactImageView: UIImageView! @IBOutlet weak var contactContainerView: UIView! var contact: Contact? override func awakeFromNib() { super.awakeFromNib() // Initialization code selectionStyle = UITableViewCellSelectionStyle.none contactContainerView.layer.masksToBounds = true contactContainerView.layer.cornerRadius = contactContainerView.frame.size.width/2 NotificationCenter.default.addObserver(self, selector: #selector(self.didChangePreferredContentSize), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil) } override func prepareForReuse() { accessoryType = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) accessoryType = selected ? .checkmark : .none } func didChangePreferredContentSize() { contactTextLabel.font = UIFont.preferredFont(forTextStyle: .body) contactDetailTextLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) } func updateContactsinUI(_ contact: Contact, subtitleType: SubtitleCellValue, contactsManager: OWSContactsManager) { self.contact = contact if contactTextLabel != nil { contactTextLabel.attributedText = contact.cnContact?.formattedFullName(font:contactTextLabel.font) } updateSubtitleBasedonType(subtitleType, contact: contact) if contact.image == nil { let contactIdForDeterminingBackgroundColor: String if let signalId = contact.parsedPhoneNumbers.first?.toE164() { contactIdForDeterminingBackgroundColor = signalId } else { contactIdForDeterminingBackgroundColor = contact.fullName } let avatarBuilder = OWSContactAvatarBuilder(contactId:contactIdForDeterminingBackgroundColor, name:contact.fullName, contactsManager:contactsManager) self.contactImageView?.image = avatarBuilder.buildDefaultImage() } else { self.contactImageView?.image = contact.image } } func updateSubtitleBasedonType(_ subtitleType: SubtitleCellValue, contact: Contact) { switch subtitleType { case SubtitleCellValue.phoneNumber: if contact.userTextPhoneNumbers.count > 0 { self.contactDetailTextLabel.text = "\(contact.userTextPhoneNumbers[0])" } else { self.contactDetailTextLabel.text = NSLocalizedString("CONTACT_PICKER_NO_PHONE_NUMBERS_AVAILABLE", comment: "table cell subtitle when contact card has no known phone number") } case SubtitleCellValue.email: if contact.emails.count > 0 { self.contactDetailTextLabel.text = "\(contact.emails[0])" } else { self.contactDetailTextLabel.text = NSLocalizedString("CONTACT_PICKER_NO_EMAILS_AVAILABLE", comment: "table cell subtitle when contact card has no email") } } } } @available(iOS 9.0, *) fileprivate extension CNContact { /** * Bold the sorting portion of the name. e.g. if we sort by family name, bold the family name. */ func formattedFullName(font: UIFont) -> NSAttributedString? { let keyToHighlight = ContactSortOrder == .familyName ? CNContactFamilyNameKey : CNContactGivenNameKey let boldDescriptor = font.fontDescriptor.withSymbolicTraits(.traitBold) let boldAttributes = [ NSFontAttributeName: UIFont(descriptor:boldDescriptor!, size: 0) ] if let attributedName = CNContactFormatter.attributedString(from: self, style: .fullName, defaultAttributes: nil) { let highlightedName = attributedName.mutableCopy() as! NSMutableAttributedString highlightedName.enumerateAttributes(in: NSMakeRange(0, highlightedName.length), options: [], using: { (attrs, range, _) in if let property = attrs[CNContactPropertyAttribute] as? String, property == keyToHighlight { highlightedName.addAttributes(boldAttributes, range: range) } }) return highlightedName } if let emailAddress = (self.emailAddresses.first?.value as String?) { return NSAttributedString(string: emailAddress, attributes: boldAttributes) } return nil } }
gpl-3.0
8f9a0d6fd170ad1d8782df2b4854d487
39.683333
189
0.666325
5.335519
false
false
false
false
SandcastleApps/partyup
PartyPlay.playground/Contents.swift
1
1427
//: Playground - noun: a place where people can play //import UIKit //import QuartzCore //class ProgressArc: UIView //{ // override init(frame: CGRect) { // super.init(frame: frame) // // let shapeLayer = layer as! CAShapeLayer // shapeLayer.path = UIBezierPath(arcCenter: self.center, radius: self.frame.size.width / 2 * 0.83, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true).CGPath // shapeLayer.fillColor = UIColor.clearColor().CGColor // shapeLayer.strokeColor = UIColor.redColor().CGColor // shapeLayer.lineWidth = 4 // shapeLayer.strokeStart = 0 // shapeLayer.strokeEnd = 0.83 // } // // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // // let shapeLayer = layer as! CAShapeLayer // shapeLayer.path = UIBezierPath(arcCenter: self.center, radius: self.frame.size.height / 2, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true).CGPath // // shapeLayer.strokeStart = 0 // shapeLayer.strokeEnd = 0 // } // // override class func layerClass() -> AnyClass { // return CAShapeLayer.self // } // // func setProgress(progress: Float) { // let shapeLayer = layer as! CAShapeLayer // shapeLayer.strokeStart = 0.0 // shapeLayer.strokeEnd = CGFloat(progress) // } //} // //var viewport = ProgressArc(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) //viewport.setProgress(0.5) //viewport.tintColor = UIColor.redColor()
mit
ade491c950ed0da57b3d3eb495300866
30.711111
189
0.689559
3.28046
false
false
false
false
joalbright/Relax
APIs/Itunes/ItunesSearch.swift
1
4194
// // ItunesSearch.swift // Relax // // Created by Jo Albright on 2/10/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit //["results": <__NSArrayM 0x170054850>( // { // amgArtistId = 168791; // artistId = 5468295; // artistName = "Daft Punk"; // artistViewUrl = "https://itunes.apple.com/us/artist/daft-punk/id5468295?uo=4"; // artworkUrl100 = "http://is5.mzstatic.com/image/thumb/Music2/v4/0c/8c/4a/0c8c4a84-465f-ee54-d999-eb0743d224ef/source/100x100bb.jpg"; // artworkUrl60 = "http://is5.mzstatic.com/image/thumb/Music2/v4/0c/8c/4a/0c8c4a84-465f-ee54-d999-eb0743d224ef/source/60x60bb.jpg"; // collectionCensoredName = "Random Access Memories"; // collectionExplicitness = notExplicit; // collectionId = 617154241; // collectionName = "Random Access Memories"; // collectionPrice = "11.99"; // collectionType = Album; // collectionViewUrl = "https://itunes.apple.com/us/album/random-access-memories/id617154241?uo=4"; // copyright = "\U2117 2013 Daft Life Limited under exclusive license to Columbia Records, a Division of Sony Music Entertainment"; // country = USA; // currency = USD; // primaryGenreName = Pop; // releaseDate = "2013-05-17T07:00:00Z"; // trackCount = 14; // wrapperType = collection; // }, // { // artistId = 587765573; // artistName = "Chris Hawk"; // artistViewUrl = "https://itunes.apple.com/us/artist/chris-hawk/id587765573?uo=4"; // artworkUrl100 = "http://is1.mzstatic.com/image/thumb/Music4/v4/03/48/ca/0348ca9e-48af-25a1-3fa5-4d4ebe7ff8cf/source/100x100bb.jpg"; // artworkUrl60 = "http://is1.mzstatic.com/image/thumb/Music4/v4/03/48/ca/0348ca9e-48af-25a1-3fa5-4d4ebe7ff8cf/source/60x60bb.jpg"; // collectionCensoredName = "Random Daft Guitars (An Unplugged Daft Punk Tribute) - Single"; // collectionExplicitness = notExplicit; // collectionId = 703297612; // collectionName = "Random Daft Guitars (An Unplugged Daft Punk Tribute) - Single"; // collectionPrice = "3.87"; // collectionType = Album; // collectionViewUrl = "https://itunes.apple.com/us/album/random-daft-guitars-unplugged/id703297612?uo=4"; // copyright = "\U2117 2013 No\U00ebl Akchot\U00e9"; // country = USA; // currency = USD; // primaryGenreName = House; // releaseDate = "2013-09-09T07:00:00Z"; // trackCount = 3; // wrapperType = collection; // } // ) // , "resultCount": 50] class ItunesSearch: RelaxObject { var results: [ItunesMedia] = [] var resultCount: Int? required init(_ info: ParsedInfo) { super.init(info) results <-- info["results"] resultCount <-- info["resultCount"] } } class ItunesMedia: RelaxObject { var artistName: String? var collectionName: String? // amgArtistId = 168791; // artistId = 5468295; // artistName = "Daft Punk" // artistViewUrl = "https://itunes.apple.com/us/artist/daft-punk/id5468295?uo=4"; // artworkUrl100 = "http://is5.mzstatic.com/image/thumb/Music2/v4/0c/8c/4a/0c8c4a84-465f-ee54-d999-eb0743d224ef/source/100x100bb.jpg"; // artworkUrl60 = "http://is5.mzstatic.com/image/thumb/Music2/v4/0c/8c/4a/0c8c4a84-465f-ee54-d999-eb0743d224ef/source/60x60bb.jpg"; // collectionCensoredName = "Random Access Memories"; // collectionExplicitness = notExplicit; // collectionId = 617154241; // collectionName = "Random Access Memories"; // collectionPrice = "11.99"; // collectionType = Album; // collectionViewUrl = "https://itunes.apple.com/us/album/random-access-memories/id617154241?uo=4"; // copyright = "\U2117 2013 Daft Life Limited under exclusive license to Columbia Records, a Division of Sony Music Entertainment"; // country = USA; // currency = USD; // primaryGenreName = Pop; // releaseDate = "2013-05-17T07:00:00Z"; // trackCount = 14; // wrapperType = collection; required init(_ info: ParsedInfo) { super.init(info) artistName <-- info["artistName"] collectionName <-- info["collectionName"] } }
mit
2fcf359c1eb45f8068a0ead373468104
38.186916
141
0.652039
2.9801
false
false
false
false
haawa799/WaniKani-Kanji-Strokes
Pods/WaniKit/Pod/Classes/WaniKit operations/LevelProgression/ParseLevelProgressionOperation.swift
1
1106
// // ParseLevelProgressionOperation.swift // Pods // // Created by Andriy K. on 12/10/15. // // import UIKit public typealias LevelProgressionResponse = (userInfo: UserInfo?, levelProgression: LevelProgressionInfo?) public typealias LevelProgressionRecieveBlock = (Result<LevelProgressionResponse, NSError>) -> Void public class ParseLevelProgressionOperation: ParseOperation<LevelProgressionResponse> { override init(cacheFile: NSURL, handler: ResponseHandler) { super.init(cacheFile: cacheFile, handler: handler) name = "Parse LevelProgression" } override func parsedValue(rootDictionary: NSDictionary?) -> LevelProgressionResponse? { var user: UserInfo? var levelProgress: LevelProgressionInfo? if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary { user = UserInfo(dict: userInfo) } if let levelProgInfo = rootDictionary?[WaniKitConstants.ResponseKeys.RequestedInfoKey] as? NSDictionary { levelProgress = LevelProgressionInfo(dict: levelProgInfo) } return (user, levelProgress) } }
mit
5174e38a708b1cc2cd8329854af4d9e6
30.628571
109
0.753165
4.441767
false
false
false
false
adamontherun/Study-iOS-With-Adam-Live
AppExtensionBirdWatcher/BirdWatcher/ViewController.swift
1
1519
//😘 it is 8/24/17 import UIKit import BirdKit import MobileCoreServices class ViewController: UIViewController { @IBOutlet weak var birdNameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() BirdCallGenerator.makeBirdCall() } @IBAction func handleShareActionTapped(_ sender: Any) { let activityViewController = UIActivityViewController(activityItems: [birdNameLabel.text!], applicationActivities: nil) present(activityViewController, animated: true, completion: nil) activityViewController.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in guard let returnedItems = returnedItems, returnedItems.count > 0, let textItem = returnedItems.first as? NSExtensionItem, let textItemProvider = textItem.attachments?.first as? NSItemProvider, textItemProvider.hasItemConformingToTypeIdentifier(kUTTypeText as String) else { return } textItemProvider.loadItem(forTypeIdentifier: kUTTypeText as String, options: nil, completionHandler: { (string, error) in guard error == nil, let newText = string as? String else { return } DispatchQueue.main.async { self.birdNameLabel.text = newText } }) } } }
mit
a46a50c1d3d1d395cdb172bca60efaec
32.688889
133
0.605541
6.088353
false
false
false
false
i-schuetz/rest_client_ios
clojushop_client_ios/DataStoreLocal.swift
1
3741
// // DataStoreLocal.swift // clojushop_client_ios // // Created by ischuetz on 09/06/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import Foundation import CoreData class DataStoreLocal { var context: NSManagedObjectContext! var model: NSManagedObjectModel! init() { model = NSManagedObjectModel.mergedModelFromBundles(nil) let psc:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) let path:String = self.itemArchivePath() let storeUrl:NSURL = NSURL(fileURLWithPath: path)! var error:NSError? if psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeUrl, options: nil, error: &error) == nil { NSException(name: "Open failed", reason: error!.localizedDescription, userInfo: nil).raise() } context = NSManagedObjectContext() context.persistentStoreCoordinator = psc context.undoManager = nil } func itemArchivePath() -> String { let documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentDirectory:String = documentDirectories[0] as String return documentDirectory.stringByAppendingPathComponent("store.data") } func saveChanges() { var error:NSError? let success = context.save(&error) if (!success) { println("Error saving: " + error!.localizedDescription) } } func getProducts(start: Int, size: Int, successHandler: (products:[AnyObject]) -> (), failureHandler: () -> ()) { let request:NSFetchRequest = NSFetchRequest() let entityDescription:NSEntityDescription = model.entitiesByName["ProductCD"] as NSEntityDescription request.entity = entityDescription let sortDescription:NSSortDescriptor = NSSortDescriptor(key: "ordering", ascending: true) request.sortDescriptors = [sortDescription] var error:NSError? if let result = context.executeFetchRequest(request, error: &error) { successHandler(products: result) } else { println("Fetch failed, reason: " + error!.localizedDescription) failureHandler() } } func clearProducts() { let request:NSFetchRequest = NSFetchRequest() request.entity = NSEntityDescription.entityForName("ProductCD", inManagedObjectContext: context) if let result = context.executeFetchRequest(request, error: nil) { for productCD in result { context.deleteObject(productCD as NSManagedObject) } } } func saveProducts(products:[Product]) { for i:Int in 0..<products.count { let product:Product = products[i] let ordering:Double = Double(i + 1) self.saveProduct(product, ordering: ordering) } self.saveChanges() } func saveProduct(product:Product, ordering: Double) { // let price:Double = 1.0 // let price:Double = product.price let productCD:ProductCD = NSEntityDescription.insertNewObjectForEntityForName("ProductCD", inManagedObjectContext: context) as ProductCD productCD.id = product.id; productCD.name = product.name; productCD.descr = product.descr; productCD.price = product.price; productCD.currency = product.currency; productCD.seller = product.seller; productCD.img_pl = product.imgList; productCD.img_pd = product.imgDetails; productCD.ordering = ordering; } }
apache-2.0
17cd50956812c95e68072a9f49e0aaf9
33.638889
144
0.642074
5.18144
false
false
false
false
xedin/swift
test/decl/protocol/req/unsatisfiable.swift
14
1954
// RUN: %target-typecheck-verify-swift -swift-version 4 protocol P { associatedtype A associatedtype B func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A == Self.B' on 'Self'}} // expected-note@-1 {{protocol requires function 'f' with type '<T> (T) -> ()'; do you want to add a stub?}} } extension P { func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B { } // expected-note@-1 {{candidate would match if 'X' was the same type as 'X.B' (aka 'Int')}} } struct X : P { // expected-error {{type 'X' does not conform to protocol 'P'}} typealias A = X typealias B = Int } protocol P2 { associatedtype A func f<T: P2>(_: T) where T.A == Self.A, T.A: P2 // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A: P2' on 'Self'}} } class C { } protocol P3 { associatedtype A func f<T: P3>(_: T) where T.A == Self.A, T.A: C // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A: C' on 'Self'}} func g<T: P3>(_: T) where T.A: C, T.A == Self.A // expected-error{{instance method requirement 'g' cannot add constraint 'Self.A: C' on 'Self'}} } protocol Base { associatedtype Assoc } protocol Sub1: Base { associatedtype SubAssoc: Assoc // expected-error@-1 {{type 'Self.SubAssoc' constrained to non-protocol, non-class type 'Self.Assoc'}} } // FIXME: This error is incorrect in what it states. protocol Sub2: Base { associatedtype SubAssoc where SubAssoc: Assoc // expected-error {{type 'Self.SubAssoc' constrained to non-protocol, non-class type 'Self.Assoc'}} } struct S {} // FIX-ME: One of these errors is redundant. protocol P4 { associatedtype X : S // expected-error@-1 {{type 'Self.X' constrained to non-protocol, non-class type 'S'}} } protocol P5 { associatedtype Y where Y : S // expected-error {{type 'Self.Y' constrained to non-protocol, non-class type 'S'}} }
apache-2.0
4fd68ccdb2db96733cbb88327217aae0
31.566667
159
0.662231
3.203279
false
false
false
false
LeeMZC/MZCWB
MZCWB/MZCWB/Classes/login- 登录相关/Controller/MZCLoginTabBarViewController.swift
1
1115
// // MZCLoginTabBarViewController.swift // MZCWB // // Created by 马纵驰 on 16/7/26. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import QorumLogs class MZCLoginTabBarViewController: MZCBaseTabBarViewController { override func viewDidLoad() { QL1("") super.viewDidLoad() setupLoginUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:login登录界面 private func setupLoginUI(){ let homeViewController = MZCLoginViewController(type: MZCViewControllerType.MZCHome) let messageViewController = MZCLoginViewController(type: MZCViewControllerType.MZCMessage) let plazaViewController = MZCLoginViewController(type: MZCViewControllerType.MZCPlaza) let meViewController = MZCLoginViewController(type: MZCViewControllerType.MZCMe) let vcArr = [homeViewController,messageViewController,plazaViewController,meViewController] add4ChildViewController(vcArr) } }
artistic-2.0
56e188afd4e7ead1d0c684375a72888c
28.513514
99
0.717033
4.493827
false
false
false
false
zevwings/ZVRefreshing
ZVRefreshing/Footer/BackFooter/ZVRefreshBackFlatFooter.swift
1
2818
// // ZRefreshBackStateNormalFooter.swift // ZVRefreshing // // Created by zevwings on 16/4/1. // Copyright © 2016年 zevwings. All rights reserved. // import UIKit import ZVActivityIndicatorView public class ZVRefreshBackFlatFooter: ZVRefreshBackStateFooter { // MARK: - Property public private(set) var activityIndicator : ActivityIndicatorView? // MARK: didSet override public var pullingPercent: CGFloat { didSet { activityIndicator?.progress = pullingPercent } } // MARK: - Subviews override public func prepare() { super.prepare() if activityIndicator == nil { activityIndicator = ActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) activityIndicator?.tintColor = .lightGray activityIndicator?.hidesWhenStopped = false addSubview(activityIndicator!) } } override public func placeSubViews() { super.placeSubViews() if let activityIndicator = activityIndicator, activityIndicator.constraints.isEmpty { var activityIndicatorCenterX = frame.width * 0.5 if let stateLabel = stateLabel, !stateLabel.isHidden { let leftPadding = stateLabel.textWidth * 0.5 + labelInsetLeft + activityIndicator.frame.width * 0.5 activityIndicatorCenterX -= leftPadding } let activityIndicatorCenterY = frame.height * 0.5 activityIndicator.center = CGPoint(x: activityIndicatorCenterX, y: activityIndicatorCenterY) } } // MARK: - State Update open override func refreshStateUpdate( _ state: ZVRefreshControl.RefreshState, oldState: ZVRefreshControl.RefreshState ) { super.refreshStateUpdate(state, oldState: oldState) switch state { case .idle: if oldState == .refreshing { UIView.animate(withDuration: AnimationDuration.fast, animations: { self.activityIndicator?.alpha = 0.0 }, completion: { _ in self.activityIndicator?.alpha = 1.0 self.activityIndicator?.stopAnimating() }) } else { activityIndicator?.stopAnimating() } case .noMoreData: activityIndicator?.stopAnimating() case .refreshing: activityIndicator?.startAnimating() default: break } } } // MARK: - System Override extension ZVRefreshBackFlatFooter { override open var tintColor: UIColor! { didSet { activityIndicator?.tintColor = tintColor } } }
mit
1a92cbd419807043f681cb2edac68915
28.946809
104
0.590053
5.508806
false
false
false
false
rugheid/Swift-MathEagle
MathEagle/Functions/SequenceFunctions.swift
1
4107
// // SequenceFunctions.swift // MathEagle // // Created by Rugen Heidbuchel on 08/06/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Accelerate // MARK: Sum /** Returns the sum of all elements in the sequence. - parameter seq: The sequence to sum. - returns: The sum of all elements in the sequence. When the sequence is empty zero is returned. */ public func sum <S: Sequence> (_ seq: S) -> S.Iterator.Element where S.Iterator.Element: Addable & ExpressibleByIntegerLiteral { return seq.reduce(0){ $0 + $1 } } /** Returns the sum of all elements in the array. - parameter seq: The array to sum. - returns: The sum of all elements in the array. When the array is empty zero is returned. */ public func sum(_ seq: [Float]) -> Float { var result: Float = 0 vDSP_sve(seq, 1, &result, vDSP_Length(seq.count)) return result } /** Returns the sum of all elements in the vector. - parameter vector: The vector to sum. - returns: The sum of all elements in the vector. When the vector is empty zero is returned. */ public func sum(_ vector: Vector<Float>) -> Float { return sum(vector.elements) } /** Returns the sum of all elements in the array. - parameter seq: The array to sum. - returns: The sum of all elements in the array. When the array is empty zero is returned. */ public func sum(_ seq: [Double]) -> Double { var result: Double = 0 vDSP_sveD(seq, 1, &result, vDSP_Length(seq.count)) return result } /** Returns the sum of all elements in the vector. - parameter vector: The vector to sum. - returns: The sum of all elements in the vector. When the vector is empty zero is returned. */ public func sum(_ vector: Vector<Double>) -> Double { return sum(vector.elements) } // MARK: Product /** Returns the product of all elements in the sequence. - parameter seq: The sequence to take the product of. */ public func product <S: Sequence> (_ seq: S) -> S.Iterator.Element where S.Iterator.Element: Multiplicable & ExpressibleByIntegerLiteral { return seq.reduce(1){ $0 * $1 } } // MARK: Min /** Returns the minimal element in the given sequence. - parameter seq: The sequence to get the minimum of. - returns: The minimum value of the given sequence. :exception: Throws an exception when the given sequence is empty. */ public func min <S: Sequence> (_ seq: S) -> S.Iterator.Element where S.Iterator.Element: Comparable & ExpressibleByIntegerLiteral { var generator = seq.makeIterator() if let initial = generator.next() { return seq.reduce(initial){ $0 < $1 ? $0 : $1 } } else { NSException(name: NSExceptionName(rawValue: "Empty array"), reason: "Can't compute minimum of an empty array.", userInfo: nil).raise() return 0 } } /** Returns the minimal element in the given sequence. - parameter seq: The sequence to get the minimum of. - returns: The minimum value of the given sequence. :exception: Throws an exception when the given sequence is empty. */ public func min(_ seq: [Float]) -> Float { if seq.count == 0 { NSException(name: NSExceptionName(rawValue: "Empty array"), reason: "Can't compute minimum of an empty array.", userInfo: nil).raise() } var result: Float = 0 vDSP_minv(seq, 1, &result, vDSP_Length(seq.count)) return result } /** Returns the minimal element in the given vector. - parameter vector: The vector to get the minimum of. - returns: The minimum value of the given vector. :exception: Throws an exception when the given vector is empty. */ public func min(_ vector: Vector<Float>) -> Float { return min(vector.elements) } // MARK: Max /** Returns the maximal element in the given sequence. - parameter seq: The sequence to get the maximum of. */ public func max <S: Sequence> (_ seq: S) -> S.Iterator.Element where S.Iterator.Element: Comparable & ExpressibleByIntegerLiteral { var generator = seq.makeIterator() let initial = generator.next()! return seq.reduce(initial){ $0 > $1 ? $0 : $1 } }
mit
861cfae6a160a8bdc027ae5c08ce7792
22.739884
142
0.678354
3.77135
false
false
false
false
pwlkania/MotionKit
MotionKit/MotionKit.swift
1
15996
// // MotionKit.swift // MotionKit // // Created by Haroon on 14/02/2015. // Launched under the Creative Commons License. You're free to use MotionKit. // // The original Github repository is https://github.com/MHaroonBaig/MotionKit // The official blog post and documentation is https://medium.com/@PyBaig/motionkit-the-missing-ios-coremotion-wrapper-written-in-swift-99fcb83355d0 // // Modified by Yang Liu <[email protected]> on 21/09/2016 // import Foundation import CoreMotion //_______________________________________________________________________________________________________________ // this helps retrieve values from the sensors. @objc protocol MotionKitDelegate { @objc optional func retrieveAccelerometerValues (_ x: Double, y:Double, z:Double, absoluteValue: Double) @objc optional func retrieveGyroscopeValues (_ x: Double, y:Double, z:Double, absoluteValue: Double) @objc optional func retrieveDeviceMotionObject (_ deviceMotion: CMDeviceMotion) @objc optional func retrieveMagnetometerValues (_ x: Double, y:Double, z:Double, absoluteValue: Double) @objc optional func getAccelerationValFromDeviceMotion (_ x: Double, y:Double, z:Double) @objc optional func getGravityAccelerationValFromDeviceMotion (_ x: Double, y:Double, z:Double) @objc optional func getRotationRateFromDeviceMotion (_ x: Double, y:Double, z:Double) @objc optional func getMagneticFieldFromDeviceMotion (_ x: Double, y:Double, z:Double) @objc optional func getAttitudeFromDeviceMotion (_ attitude: CMAttitude) } @objc(MotionKit) open class MotionKit :NSObject{ let manager = CMMotionManager() var delegate: MotionKitDelegate? /* * init:void: * * Discussion: * Initialises the MotionKit class and throw a Log with a timestamp. */ public override init(){ print("MotionKit has been initialised successfully") } /* * getAccelerometerValues:interval:values: * * Discussion: * Starts accelerometer updates, providing data to the given handler through the given queue. * Note that when the updates are stopped, all operations in the * given NSOperationQueue will be cancelled. You can access the retrieved values either by a * Trailing Closure or through a Delgate. */ open func getAccelerometerValues (_ interval: TimeInterval = 0.1, values: ((_ x: Double, _ y: Double, _ z: Double) -> ())? ){ var valX: Double! var valY: Double! var valZ: Double! if manager.isAccelerometerAvailable { manager.accelerometerUpdateInterval = interval manager.startAccelerometerUpdates(to: OperationQueue(), withHandler: { (data, error) in if let error = error { print("Error: %@", error) } valX = data!.acceleration.x valY = data!.acceleration.y valZ = data!.acceleration.z if values != nil { values!(valX, valY, valZ) } let valA = Double(valX * valX + valY * valY) let valB = valZ * valZ let absoluteVal = sqrt(valA + valB) self.delegate?.retrieveAccelerometerValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal) }) } else { print("The Accelerometer is not available") } } /* * getGyroValues:interval:values: * * Discussion: * Starts gyro updates, providing data to the given handler through the given queue. * Note that when the updates are stopped, all operations in the * given NSOperationQueue will be cancelled. You can access the retrieved values either by a * Trailing Closure or through a Delegate. */ open func getGyroValues (_ interval: TimeInterval = 0.1, values: ((_ x: Double, _ y: Double, _ z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.isGyroAvailable{ manager.gyroUpdateInterval = interval manager.startGyroUpdates(to: OperationQueue(), withHandler: { (data, error) in if let error = error { print("Error: %@", error) } valX = data!.rotationRate.x valY = data!.rotationRate.y valZ = data!.rotationRate.z if values != nil { values!(valX, valY, valZ) } let valA = Double(valX * valX + valY * valY) let valB = valZ * valZ let absoluteVal = sqrt(valA + valB) self.delegate?.retrieveGyroscopeValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal) }) } else { print("The Gyroscope is not available") } } /* * getMagnetometerValues:interval:values: * * Discussion: * Starts magnetometer updates, providing data to the given handler through the given queue. * You can access the retrieved values either by a Trailing Closure or through a Delegate. */ @available(iOS, introduced: 5.0) open func getMagnetometerValues (_ interval: TimeInterval = 0.1, values: ((_ x: Double, _ y:Double, _ z:Double) -> ())? ){ var valX: Double! var valY: Double! var valZ: Double! if manager.isMagnetometerAvailable { manager.magnetometerUpdateInterval = interval manager.startMagnetometerUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } valX = data!.magneticField.x valY = data!.magneticField.y valZ = data!.magneticField.z if values != nil { values!(valX, valY, valZ) } let valA = Double(valX * valX + valY * valY) let valB = valZ * valZ let absoluteVal = sqrt(valA + valB) self.delegate?.retrieveMagnetometerValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal) } } else { print("Magnetometer is not available") } } /* MARK :- DEVICE MOTION APPROACH STARTS HERE */ /* * getDeviceMotionValues:interval:values: * * Discussion: * Starts device motion updates, providing data to the given handler through the given queue. * Uses the default reference frame for the device. Examine CMMotionManager's * attitudeReferenceFrame to determine this. You can access the retrieved values either by a * Trailing Closure or through a Delegate. */ open func getDeviceMotionObject (_ interval: TimeInterval = 0.1, values: ((_ deviceMotion: CMDeviceMotion) -> ())? ) { if manager.isDeviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } if values != nil { values!(data!) } self.delegate?.retrieveDeviceMotionObject!(data!) } } else { print("Device Motion is not available") } } /* * getAccelerationFromDeviceMotion:interval:values: * You can retrieve the processed user accelaration data from the device motion from this method. */ open func getAccelerationFromDeviceMotion (_ interval: TimeInterval = 0.1, values: ((_ x:Double, _ y:Double, _ z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.isDeviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } valX = data!.userAcceleration.x valY = data!.userAcceleration.y valZ = data!.userAcceleration.z if values != nil { values!(valX, valY, valZ) } self.delegate?.getAccelerationValFromDeviceMotion!(valX, y: valY, z: valZ) } } else { print("Device Motion is unavailable") } } /* * getGravityAccelerationFromDeviceMotion:interval:values: * You can retrieve the processed gravitational accelaration data from the device motion from this * method. */ open func getGravityAccelerationFromDeviceMotion (_ interval: TimeInterval = 0.1, values: ((_ x:Double, _ y:Double, _ z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.isDeviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } valX = data!.gravity.x valY = data!.gravity.y valZ = data!.gravity.z if values != nil { values!(valX, valY, valZ) } // let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ) self.delegate?.getGravityAccelerationValFromDeviceMotion!(valX, y: valY, z: valZ) } } else { print("Device Motion is not available") } } /* * getAttitudeFromDeviceMotion:interval:values: * You can retrieve the processed attitude data from the device motion from this * method. */ open func getAttitudeFromDeviceMotion (_ interval: TimeInterval = 0.1, values: ((_ attitude: CMAttitude) -> ())? ) { if manager.isDeviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } if values != nil { values!(data!.attitude) } self.delegate?.getAttitudeFromDeviceMotion!(data!.attitude) } } else { print("Device Motion is not available") } } /* * getRotationRateFromDeviceMotion:interval:values: * You can retrieve the processed rotation data from the device motion from this * method. */ open func getRotationRateFromDeviceMotion (_ interval: TimeInterval = 0.1, values: ((_ x:Double, _ y:Double, _ z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.isDeviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } valX = data!.rotationRate.x valY = data!.rotationRate.y valZ = data!.rotationRate.z if values != nil { values!(valX, valY, valZ) } // let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ) self.delegate?.getRotationRateFromDeviceMotion!(valX, y: valY, z: valZ) } } else { print("Device Motion is not available") } } /* * getMagneticFieldFromDeviceMotion:interval:values: * You can retrieve the processed magnetic field data from the device motion from this * method. */ open func getMagneticFieldFromDeviceMotion (_ interval: TimeInterval = 0.1, values: ((_ x:Double, _ y:Double, _ z:Double, _ accuracy: Int32) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! var valAccuracy: Int32! if manager.isDeviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdates(to: OperationQueue()){ (data, error) in if let error = error { print("Error: %@", error) } valX = data!.magneticField.field.x valY = data!.magneticField.field.y valZ = data!.magneticField.field.z valAccuracy = data!.magneticField.accuracy.rawValue if values != nil { values!(valX, valY, valZ, valAccuracy) } self.delegate?.getMagneticFieldFromDeviceMotion!(valX, y: valY, z: valZ) } } else { print("Device Motion is not available") } } /* MARK :- DEVICE MOTION APPROACH ENDS HERE */ /* * From the methods hereafter, the sensor values could be retrieved at * a particular instant, whenever needed, through a trailing closure. */ /* MARK :- INSTANTANIOUS METHODS START HERE */ open func getAccelerationAtCurrentInstant (_ values: @escaping (_ x:Double, _ y:Double, _ z:Double) -> ()){ self.getAccelerationFromDeviceMotion(0.5) { (x, y, z) -> () in values(x, y, z) self.stopDeviceMotionUpdates() } } open func getGravitationalAccelerationAtCurrentInstant (_ values: @escaping (_ x:Double, _ y:Double, _ z:Double) -> ()){ self.getGravityAccelerationFromDeviceMotion(0.5) { (x, y, z) -> () in values(x, y, z) self.stopDeviceMotionUpdates() } } open func getAttitudeAtCurrentInstant (_ values: @escaping (_ attitude: CMAttitude) -> ()){ self.getAttitudeFromDeviceMotion(0.5) { (attitude) -> () in values(attitude) self.stopDeviceMotionUpdates() } } open func getMageticFieldAtCurrentInstant (_ values: @escaping (_ x:Double, _ y:Double, _ z:Double) -> ()){ self.getMagneticFieldFromDeviceMotion(0.5) { (x, y, z, accuracy) -> () in values(x, y, z) self.stopDeviceMotionUpdates() } } open func getGyroValuesAtCurrentInstant (_ values: @escaping (_ x:Double, _ y:Double, _ z:Double) -> ()){ self.getRotationRateFromDeviceMotion(0.5) { (x, y, z) -> () in values(x, y, z) self.stopDeviceMotionUpdates() } } /* MARK :- INSTANTANIOUS METHODS END HERE */ /* * stopAccelerometerUpdates * * Discussion: * Stop accelerometer updates. */ open func stopAccelerometerUpdates(){ self.manager.stopAccelerometerUpdates() print("Accelaration Updates Status - Stopped") } /* * stopGyroUpdates * * Discussion: * Stops gyro updates. */ open func stopGyroUpdates(){ self.manager.stopGyroUpdates() print("Gyroscope Updates Status - Stopped") } /* * stopDeviceMotionUpdates * * Discussion: * Stops device motion updates. */ open func stopDeviceMotionUpdates() { self.manager.stopDeviceMotionUpdates() print("Device Motion Updates Status - Stopped") } /* * stopMagnetometerUpdates * * Discussion: * Stops magnetometer updates. */ @available(iOS, introduced: 5.0) open func stopmagnetometerUpdates() { self.manager.stopMagnetometerUpdates() print("Magnetometer Updates Status - Stopped") } }
mit
c950442ab459411b6cd64238583f9651
33.773913
156
0.567829
4.828252
false
false
false
false
presence-insights/pi-clientsdk-ios
IBMPIGeofence/PIGeofencePreferences.swift
1
3838
/** * IBMPIGeofence * PIGeofencePreferences.swift * * Performs all communication to the PI Rest API. * * © Copyright 2016 IBM Corp. * * Licensed under the Presence Insights Client iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 CocoaLumberjack private let kLastDownloadDate = "com.ibm.pi.LastDownloadDate" private let kLastDownloadErrorDate = "com.ibm.pi.lastDownloadErrorDate" private let kErrorDownloadCountKey = "com.ibm.pi.downloads.errorCount" private let kLastSyncDate = "com.ibm.pi.downloads.lastSyncDate" private let kMaxDownloadRetry = "com.ibm.pi.downloads.maxDownloadRetry" struct PIGeofencePreferences { static var lastDownloadDate:NSDate? { set { if let newValue = newValue { PIUnprotectedPreferences.sharedInstance.setObject(newValue, forKey: kLastDownloadDate) } else { PIUnprotectedPreferences.sharedInstance.removeObjectForKey(kLastDownloadDate) } } get { return PIUnprotectedPreferences.sharedInstance.objectForKey(kLastDownloadDate) as? NSDate } } static var lastDownloadErrorDate:NSDate? { set { if let newValue = newValue { PIUnprotectedPreferences.sharedInstance.setObject(newValue, forKey: kLastDownloadErrorDate) } else { PIUnprotectedPreferences.sharedInstance.removeObjectForKey(kLastDownloadErrorDate) } } get { return PIUnprotectedPreferences.sharedInstance.objectForKey(kLastDownloadErrorDate) as? NSDate } } static var downloadErrorCount:Int? { set { if let newValue = newValue { PIUnprotectedPreferences.sharedInstance.setInteger(newValue, forKey: kErrorDownloadCountKey) } else { PIUnprotectedPreferences.sharedInstance.removeObjectForKey(kErrorDownloadCountKey) } } get { return PIUnprotectedPreferences.sharedInstance.integerForKey(kErrorDownloadCountKey) } } static func resetDownloadErrors() { downloadErrorCount = nil // We stop retrying lastDownloadErrorDate = nil lastDownloadDate = NSDate() synchronize() } static func downloadError() { guard downloadErrorCount < maxDownloadRetry else { DDLogError("Too many errors for the download, wait until tomorrow") resetDownloadErrors() return } // Reset the lastDownloadDate so we can try again when // a significant change is triggered lastDownloadDate = nil lastDownloadErrorDate = NSDate() downloadErrorCount = (downloadErrorCount ?? 0) + 1 synchronize() } static var lastSyncDate:NSDate? { set { if let newValue = newValue { PIUnprotectedPreferences.sharedInstance.setObject(newValue, forKey: kLastSyncDate) } else { PIUnprotectedPreferences.sharedInstance.removeObjectForKey(kLastSyncDate) } synchronize() } get { return PIUnprotectedPreferences.sharedInstance.objectForKey(kLastSyncDate) as? NSDate } } static func synchronize() { PIUnprotectedPreferences.sharedInstance.synchronize() } static var maxDownloadRetry:Int { set { PIUnprotectedPreferences.sharedInstance.setInteger(newValue, forKey: kMaxDownloadRetry) synchronize() } get { let max = PIUnprotectedPreferences.sharedInstance.integerForKey(kMaxDownloadRetry) ?? 0 if max > 0 { return max } else { return 10 } } } static func reset() { self.lastDownloadDate = nil self.lastDownloadErrorDate = nil self.downloadErrorCount = nil self.lastSyncDate = nil synchronize() } }
epl-1.0
31628c00ee5dbf364621eaf14cd335d8
28.075758
97
0.761793
3.864048
false
false
false
false
russbishop/swift
stdlib/public/SDK/Foundation/IndexSet.swift
1
33262
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module public func ==(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool { return lhs.value == rhs.value && rhs.rangeIndex == rhs.rangeIndex } public func <(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool { return lhs.value < rhs.value && rhs.rangeIndex <= rhs.rangeIndex } public func <=(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool { return lhs.value <= rhs.value && rhs.rangeIndex <= rhs.rangeIndex } public func >(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool { return lhs.value > rhs.value && rhs.rangeIndex >= rhs.rangeIndex } public func >=(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool { return lhs.value >= rhs.value && rhs.rangeIndex >= rhs.rangeIndex } public func ==(lhs: IndexSet.RangeView, rhs: IndexSet.RangeView) -> Bool { return lhs.startIndex == rhs.startIndex && lhs.endIndex == rhs.endIndex && lhs.indexSet == rhs.indexSet } // We currently cannot use this mechanism because NSIndexSet is not abstract; it has its own ivars and therefore subclassing it using the same trick as NSData, etc. does not work. /* private final class _SwiftNSIndexSet : _SwiftNativeNSIndexSet, _SwiftNativeFoundationType { public typealias ImmutableType = NSIndexSet public typealias MutableType = NSMutableIndexSet var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType> init(immutableObject: AnyObject) { // Take ownership. __wrapped = .Immutable( Unmanaged.passRetained( _unsafeReferenceCast(immutableObject, to: ImmutableType.self))) super.init() } init(mutableObject: AnyObject) { // Take ownership. __wrapped = .Mutable( Unmanaged.passRetained( _unsafeReferenceCast(mutableObject, to: MutableType.self))) super.init() } public required init(unmanagedImmutableObject: Unmanaged<ImmutableType>) { // Take ownership. __wrapped = .Immutable(unmanagedImmutableObject) super.init() } public required init(unmanagedMutableObject: Unmanaged<MutableType>) { // Take ownership. __wrapped = .Mutable(unmanagedMutableObject) super.init() } deinit { releaseWrappedObject() } } */ /// Manages a `Set` of integer values, which are commonly used as an index type in Cocoa API. /// /// The range of valid integer values is 0..<INT_MAX-1. Anything outside this range is an error. public struct IndexSet : ReferenceConvertible, Equatable, BidirectionalCollection, SetAlgebra { /// An view of the contents of an IndexSet, organized by range. /// /// For example, if an IndexSet is composed of: /// `[1..<5]` and `[7..<10]` and `[13]` /// then calling `next()` on this view's iterator will produce 3 ranges before returning nil. public struct RangeView : Equatable, BidirectionalCollection { public typealias Index = Int public let startIndex : Index public let endIndex : Index private var indexSet : IndexSet // Range of element values private var intersectingRange : Range<IndexSet.Element>? private init(indexSet : IndexSet, intersecting range : Range<IndexSet.Element>?) { self.indexSet = indexSet self.intersectingRange = range if let r = range { if r.lowerBound == r.upperBound { startIndex = 0 endIndex = 0 } else { let minIndex = indexSet._indexOfRange(containing: r.lowerBound) let maxIndex = indexSet._indexOfRange(containing: r.upperBound) switch (minIndex, maxIndex) { case (nil, nil): startIndex = 0 endIndex = 0 case (nil, .some(let max)): // Start is before our first range startIndex = 0 endIndex = max + 1 case (.some(let min), nil): // End is after our last range startIndex = min endIndex = indexSet._rangeCount case (.some(let min), .some(let max)): startIndex = min endIndex = max + 1 } } } else { startIndex = 0 endIndex = indexSet._rangeCount } } public func makeIterator() -> IndexingIterator<RangeView> { return IndexingIterator(_elements: self) } public subscript(index : Index) -> CountableRange<IndexSet.Element> { let indexSetRange = indexSet._range(at: index) if let intersectingRange = intersectingRange { return Swift.max(intersectingRange.lowerBound, indexSetRange.lowerBound)..<Swift.min(intersectingRange.upperBound, indexSetRange.upperBound) } else { return indexSetRange.lowerBound..<indexSetRange.upperBound } } public subscript(bounds: Range<Index>) -> BidirectionalSlice<RangeView> { return BidirectionalSlice(base: self, bounds: bounds) } public func index(after i: Index) -> Index { return i + 1 } public func index(before i: Index) -> Index { return i - 1 } } /// The mechanism for getting to the integers stored in an IndexSet. public struct Index : CustomStringConvertible, Comparable { private let indexSet : IndexSet private var value : IndexSet.Element private var extent : Range<IndexSet.Element> private var rangeIndex : Int private let rangeCount : Int private init(firstIn indexSet : IndexSet) { self.indexSet = indexSet self.rangeCount = indexSet._rangeCount self.rangeIndex = 0 self.extent = indexSet._range(at: 0) self.value = extent.lowerBound } private init(lastIn indexSet : IndexSet) { self.indexSet = indexSet let rangeCount = indexSet._rangeCount self.rangeIndex = rangeCount - 1 if rangeCount > 0 { self.extent = indexSet._range(at: rangeCount - 1) self.value = extent.upperBound // "1 past the end" position is the last range, 1 + the end of that range's extent } else { self.extent = 0..<0 self.value = 0 } self.rangeCount = rangeCount } private init(indexSet: IndexSet, index: Int) { self.indexSet = indexSet self.rangeCount = self.indexSet._rangeCount self.value = index if let rangeIndex = self.indexSet._indexOfRange(containing: index) { self.extent = self.indexSet._range(at: rangeIndex) self.rangeIndex = rangeIndex } else { self.extent = 0..<0 self.rangeIndex = 0 } } // First or last value in a specified range private init(indexSet: IndexSet, rangeIndex: Int, rangeCount: Int, first : Bool) { self.indexSet = indexSet let extent = indexSet._range(at: rangeIndex) if first { self.value = extent.lowerBound } else { self.value = extent.upperBound-1 } self.extent = extent self.rangeCount = rangeCount self.rangeIndex = rangeIndex } private init(indexSet: IndexSet, value: Int, extent: Range<Int>, rangeIndex: Int, rangeCount: Int) { self.indexSet = indexSet self.value = value self.extent = extent self.rangeCount = rangeCount self.rangeIndex = rangeIndex } private func successor() -> Index { if value + 1 == extent.upperBound { // Move to the next range if rangeIndex + 1 == rangeCount { // We have no more to go; return a 'past the end' index return Index(indexSet: indexSet, value: value + 1, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount) } else { return Index(indexSet: indexSet, rangeIndex: rangeIndex + 1, rangeCount: rangeCount, first: true) } } else { // Move to the next value in this range return Index(indexSet: indexSet, value: value + 1, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount) } } private mutating func _successorInPlace() { if value + 1 == extent.upperBound { // Move to the next range if rangeIndex + 1 == rangeCount { // We have no more to go; return a 'past the end' index value += 1 } else { rangeIndex += 1 extent = indexSet._range(at: rangeIndex) value = extent.lowerBound } } else { // Move to the next value in this range value += 1 } } private func predecessor() -> Index { if value == extent.lowerBound { // Move to the next range if rangeIndex == 0 { // We have no more to go return Index(indexSet: indexSet, value: value, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount) } else { return Index(indexSet: indexSet, rangeIndex: rangeIndex - 1, rangeCount: rangeCount, first: false) } } else { // Move to the previous value in this range return Index(indexSet: indexSet, value: value - 1, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount) } } public var description: String { return "index \(value) in a range of \(extent) [range #\(rangeIndex + 1)/\(rangeCount)]" } private mutating func _predecessorInPlace() { if value == extent.lowerBound { // Move to the next range if rangeIndex == 0 { // We have no more to go } else { rangeIndex -= 1 extent = indexSet._range(at: rangeIndex) value = extent.upperBound - 1 } } else { // Move to the previous value in this range value -= 1 } } } public typealias ReferenceType = NSIndexSet public typealias Element = Int private var _handle: _MutablePairHandle<NSIndexSet, NSMutableIndexSet> /// Initialize an `IndexSet` with a range of integers. public init(integersIn range: Range<Element>) { _handle = _MutablePairHandle(NSIndexSet(indexesIn: _toNSRange(range)), copying: false) } /// Initialize an `IndexSet` with a single integer. public init(integer: Element) { _handle = _MutablePairHandle(NSIndexSet(index: integer), copying: false) } /// Initialize an empty `IndexSet`. public init() { _handle = _MutablePairHandle(NSIndexSet(), copying: false) } public var hashValue : Int { return _handle.map { $0.hash } } /// Returns the number of integers in `self`. public var count: Int { return _handle.map { $0.count } } public func makeIterator() -> IndexingIterator<IndexSet> { return IndexingIterator(_elements: self) } /// Returns a `Range`-based view of `self`. /// /// - parameter range: A subrange of `self` to view. The default value is `nil`, which means that the entire `IndexSet` is used. public func rangeView(of range : Range<Element>? = nil) -> RangeView { return RangeView(indexSet: self, intersecting: range) } private func _indexOfRange(containing integer : Element) -> RangeView.Index? { let result = _handle.map { __NSIndexSetIndexOfRangeContainingIndex($0, UInt(integer)) } if result == UInt(NSNotFound) { return nil } else { return Int(result) } } private func _range(at index: RangeView.Index) -> Range<Element> { return _handle.map { var location : UInt = 0 var length : UInt = 0 __NSIndexSetRangeAtIndex($0, UInt(index), &location, &length) return Int(location)..<Int(location)+Int(length) } } private var _rangeCount : Int { return _handle.map { Int(__NSIndexSetRangeCount($0)) } } public var startIndex: Index { // TODO: We should cache this result // If this winds up being NSNotFound, that's ok because then endIndex is also NSNotFound, and empty collections have startIndex == endIndex return Index(firstIn: self) } public var endIndex: Index { // TODO: We should cache this result return Index(lastIn: self) } public subscript(index : Index) -> Element { return index.value } public subscript(bounds: Range<Index>) -> BidirectionalSlice<IndexSet> { return BidirectionalSlice(base: self, bounds: bounds) } // We adopt the default implementation of subscript(range: Range<Index>) from MutableCollection private func _toOptional(_ x : Int) -> Int? { if x == NSNotFound { return nil } else { return x } } /// Returns the first integer in `self`, or nil if `self` is empty. public var first: Element? { return _handle.map { _toOptional($0.firstIndex) } } /// Returns the last integer in `self`, or nil if `self` is empty. public var last: Element? { return _handle.map { _toOptional($0.lastIndex) } } /// Returns an integer contained in `self` which is greater than `integer`. public func integerGreaterThan(_ integer: Element) -> Element { return _handle.map { $0.indexGreaterThanIndex(integer) } } /// Returns an integer contained in `self` which is less than `integer`. public func integerLessThan(_ integer: Element) -> Element { return _handle.map { $0.indexLessThanIndex(integer) } } /// Returns an integer contained in `self` which is greater than or equal to `integer`. public func integerGreaterThanOrEqualTo(_ integer: Element) -> Element { return _handle.map { $0.indexGreaterThanOrEqual(to: integer) } } /// Returns an integer contained in `self` which is less than or equal to `integer`. public func integerLessThanOrEqualTo(_ integer: Element) -> Element { return _handle.map { $0.indexLessThanOrEqual(to: integer) } } /// Return a `Range<IndexSet.Index>` which can be used to subscript the index set. /// /// The resulting range is the range of the intersection of the integers in `range` with the index set. /// /// - parameter range: The range of integers to include. public func indexRange(in range: Range<Element>) -> Range<Index> { if range.isEmpty { let i = Index(indexSet: self, index: 0) return i..<i } if range.lowerBound > last || (range.upperBound - 1) < first { let i = Index(indexSet: self, index: 0) return i..<i } let resultFirst = Index(indexSet: self, index: integerGreaterThanOrEqualTo(range.lowerBound)) let resultLast = Index(indexSet: self, index: integerLessThanOrEqualTo(range.upperBound - 1)) return resultFirst..<resultLast.successor() } /// Returns the count of integers in `self` that intersect `range`. public func count(in range: Range<Element>) -> Int { return _handle.map { $0.countOfIndexes(in: _toNSRange(range)) } } /// Returns `true` if `self` contains `integer`. public func contains(_ integer: Element) -> Bool { return _handle.map { $0.contains(integer) } } /// Returns `true` if `self` contains all of the integers in `range`. public func contains(integersIn range: Range<Element>) -> Bool { return _handle.map { $0.contains(in: _toNSRange(range)) } } /// Returns `true` if `self` contains any of the integers in `indexSet`. public func contains(integersIn indexSet: IndexSet) -> Bool { return _handle.map { $0.contains(indexSet) } } /// Returns `true` if `self` intersects any of the integers in `range`. public func intersects(integersIn range: Range<Element>) -> Bool { return _handle.map { $0.intersects(in: _toNSRange(range)) } } // MARK: - // Indexable public func index(after i: Index) -> Index { return i.successor() } public func formIndex(after i: inout Index) { i._successorInPlace() } public func index(before i: Index) -> Index { return i.predecessor() } public func formIndex(before i: inout Index) { i._predecessorInPlace() } // MARK: - // MARK: SetAlgebra /// Union the `IndexSet` with `other`. public mutating func formUnion(_ other: IndexSet) { self = self.union(other) } /// Union the `IndexSet` with `other`. public func union(_ other: IndexSet) -> IndexSet { // This algorithm is naïve but it works. We could avoid calling insert in some cases. var result = IndexSet() for r in self.rangeView() { result.insert(integersIn: Range(r)) } for r in other.rangeView() { result.insert(integersIn: Range(r)) } return result } /// Exclusive or the `IndexSet` with `other`. public func symmetricDifference(_ other: IndexSet) -> IndexSet { var result = IndexSet() var boundaryIterator = IndexSetBoundaryIterator(self, other) var flag = false var start = 0 while let i = boundaryIterator.next() { if !flag { // Starting a range; if the edge is contained or not depends on the xor of this particular value. let startInclusive = self.contains(i) != other.contains(i) start = startInclusive ? i : i + 1 flag = true } else { // Ending a range; if the edge is contained or not depends on the xor of this particular value. let endInclusive = self.contains(i) != other.contains(i) let end = endInclusive ? i + 1 : i if start < end { // Otherwise, we had an empty range result.insert(integersIn: start..<end) } flag = false } // We never have to worry about having flag set to false after exiting this loop because the iterator will always return an even number of results; ranges come in pairs, and we always alternate flag } return result } /// Exclusive or the `IndexSet` with `other`. public mutating func formSymmetricDifference(_ other: IndexSet) { self = self.symmetricDifference(other) } /// Intersect the `IndexSet` with `other`. public func intersection(_ other: IndexSet) -> IndexSet { var result = IndexSet() var boundaryIterator = IndexSetBoundaryIterator(self, other) var flag = false var start = 0 while let i = boundaryIterator.next() { if !flag { // If both sets contain then start a range. if self.contains(i) && other.contains(i) { flag = true start = i } } else { // If both sets contain then end a range. if self.contains(i) && other.contains(i) { flag = false result.insert(integersIn: start..<(i + 1)) } } } return result } /// Intersect the `IndexSet` with `other`. public mutating func formIntersection(_ other: IndexSet) { self = self.intersection(other) } /// Insert an integer into the `IndexSet`. @discardableResult public mutating func insert(_ integer: Element) -> (inserted: Bool, memberAfterInsert: Element) { _applyMutation { $0.add(integer) } // TODO: figure out how to return the truth here return (true, integer) } /// Insert an integer into the `IndexSet`. @discardableResult public mutating func update(with integer: Element) -> Element? { _applyMutation { $0.add(integer) } // TODO: figure out how to return the truth here return integer } /// Remove an integer from the `IndexSet`. @discardableResult public mutating func remove(_ integer: Element) -> Element? { // TODO: Add method to NSIndexSet to do this in one call let result : Element? = contains(integer) ? integer : nil _applyMutation { $0.remove(integer) } return result } // MARK: - /// Remove all values from the `IndexSet`. public mutating func removeAll() { _applyMutation { $0.removeAllIndexes() } } /// Insert a range of integers into the `IndexSet`. public mutating func insert(integersIn range: Range<Element>) { _applyMutation { $0.add(in: _toNSRange(range)) } } /// Remove a range of integers from the `IndexSet`. public mutating func remove(integersIn range: Range<Element>) { _applyMutation { $0.remove(in: _toNSRange(range)) } } /// Returns `true` if self contains no values. public var isEmpty : Bool { return self.count == 0 } /// Returns an IndexSet filtered according to the result of `includeInteger`. /// /// - parameter range: A range of integers. For each integer in the range that intersects the integers in the IndexSet, then the `includeInteger predicate will be invoked. Pass `nil` (the default) to use the entire range. /// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not. public func filteredIndexSet(in range : Range<Element>? = nil, includeInteger: @noescape (Element) throws -> Bool) rethrows -> IndexSet { let r : NSRange = range != nil ? _toNSRange(range!) : NSMakeRange(0, NSNotFound - 1) return try _handle.map { var error : ErrorProtocol? = nil let result = $0.indexes(in: r, options: [], passingTest: { (i, stop) -> Bool in do { let include = try includeInteger(i) return include } catch let e { error = e stop.pointee = true return false } }) as IndexSet if let e = error { throw e } else { return result } } } /// For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta]. public mutating func shift(startingAt integer: Element, by delta: IndexSet.IndexDistance) { _applyMutation { $0.shiftIndexesStarting(at: integer, by: delta) } } public var description: String { return _handle.map { $0.description } } public var debugDescription: String { return _handle.map { $0.debugDescription } } // Temporary boxing function, until we can get a native Swift type for NSIndexSet @inline(__always) mutating func _applyMutation<ReturnType>(_ whatToDo : @noescape (NSMutableIndexSet) throws -> ReturnType) rethrows -> ReturnType { // This check is done twice because: <rdar://problem/24939065> Value kept live for too long causing uniqueness check to fail var unique = true switch _handle._pointer { case .Default(_): break case .Mutable(_): unique = isUniquelyReferencedNonObjC(&_handle) } switch _handle._pointer { case .Default(let i): // We need to become mutable; by creating a new box we also become unique let copy = i.mutableCopy() as! NSMutableIndexSet // Be sure to set the _handle before calling out; otherwise references to the struct in the closure may be looking at the old _handle _handle = _MutablePairHandle(copy, copying: false) let result = try whatToDo(copy) return result case .Mutable(let m): // Only create a new box if we are not uniquely referenced if !unique { let copy = m.mutableCopy() as! NSMutableIndexSet _handle = _MutablePairHandle(copy, copying: false) let result = try whatToDo(copy) return result } else { return try whatToDo(m) } } } // MARK: - Bridging Support private var reference: NSIndexSet { return _handle.reference } private init(reference: NSIndexSet) { _handle = _MutablePairHandle(reference) } } /// Iterate two index sets on the boundaries of their ranges. This is where all of the interesting stuff happens for exclusive or, intersect, etc. private struct IndexSetBoundaryIterator : IteratorProtocol { private typealias Element = IndexSet.Element private var i1 : IndexSet.RangeView.Iterator private var i2 : IndexSet.RangeView.Iterator private var i1Range : CountableRange<Element>? private var i2Range : CountableRange<Element>? private var i1UsedFirst : Bool private var i2UsedFirst : Bool private init(_ is1 : IndexSet, _ is2 : IndexSet) { i1 = is1.rangeView().makeIterator() i2 = is2.rangeView().makeIterator() i1Range = i1.next() i2Range = i2.next() // A sort of cheap iterator on [i1Range.first, i1Range.last] i1UsedFirst = false i2UsedFirst = false } private mutating func next() -> Element? { if i1Range == nil && i2Range == nil { return nil } let nextIn1 : Element if let r = i1Range { nextIn1 = i1UsedFirst ? r.last! : r.first! } else { nextIn1 = Int.max } let nextIn2 : Element if let r = i2Range { nextIn2 = i2UsedFirst ? r.last! : r.first! } else { nextIn2 = Int.max } var result : Element if nextIn1 <= nextIn2 { // 1 has the next element, or they are the same. We need to iterate both the value from is1 and is2 in the == case. result = nextIn1 if i1UsedFirst { i1Range = i1.next() } i1UsedFirst = !i1UsedFirst } else { // 2 has the next element result = nextIn2 if i2UsedFirst { i2Range = i2.next() } i2UsedFirst = !i2UsedFirst } return result } } public func ==(lhs: IndexSet, rhs: IndexSet) -> Bool { return lhs._handle.map { $0.isEqual(to: rhs) } } private func _toNSRange(_ r : Range<IndexSet.Element>) -> NSRange { return NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound) } extension IndexSet : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSIndexSet.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSIndexSet { return reference } public static func _forceBridgeFromObjectiveC(_ x: NSIndexSet, result: inout IndexSet?) { result = IndexSet(reference: x) } public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexSet, result: inout IndexSet?) -> Bool { result = IndexSet(reference: x) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexSet?) -> IndexSet { return IndexSet(reference: source!) } } @_silgen_name("__NSIndexSetRangeCount") internal func __NSIndexSetRangeCount(_ indexSet: NSIndexSet) -> UInt @_silgen_name("__NSIndexSetRangeAtIndex") internal func __NSIndexSetRangeAtIndex(_ indexSet: NSIndexSet, _ index: UInt, _ location : UnsafeMutablePointer<UInt>, _ length : UnsafeMutablePointer<UInt>) @_silgen_name("__NSIndexSetIndexOfRangeContainingIndex") internal func __NSIndexSetIndexOfRangeContainingIndex(_ indexSet: NSIndexSet, _ index: UInt) -> UInt // MARK: Protocol // TODO: This protocol should be replaced with a native Swift object like the other Foundation bridged types. However, NSIndexSet does not have an abstract zero-storage base class like NSCharacterSet, NSData, and NSAttributedString. Therefore the same trick of laying it out with Swift ref counting does not work.and /// Holds either the immutable or mutable version of a Foundation type. /// /// In many cases, the immutable type has optimizations which make it preferred when we know we do not need mutation. private enum _MutablePair<ImmutableType, MutableType> { case Default(ImmutableType) case Mutable(MutableType) } /// A class type which acts as a handle (pointer-to-pointer) to a Foundation reference type which has both an immutable and mutable class (e.g., NSData, NSMutableData). /// /// a.k.a. Box private final class _MutablePairHandle<ImmutableType : NSObject, MutableType : NSObject where ImmutableType : NSMutableCopying, MutableType : NSMutableCopying> { private var _pointer: _MutablePair<ImmutableType, MutableType> /// Initialize with an immutable reference instance. /// /// - parameter immutable: The thing to stash. /// - parameter copying: Should be true unless you just created the instance (or called copy) and want to transfer ownership to this handle. init(_ immutable : ImmutableType, copying : Bool = true) { if copying { self._pointer = _MutablePair.Default(immutable.copy() as! ImmutableType) } else { self._pointer = _MutablePair.Default(immutable) } } /// Initialize with a mutable reference instance. /// /// - parameter mutable: The thing to stash. /// - parameter copying: Should be true unless you just created the instance (or called copy) and want to transfer ownership to this handle. init(_ mutable : MutableType, copying : Bool = true) { if copying { self._pointer = _MutablePair.Mutable(mutable.mutableCopy() as! MutableType) } else { self._pointer = _MutablePair.Mutable(mutable) } } /// Apply a closure to the reference type, regardless if it is mutable or immutable. @inline(__always) func map<ReturnType>(_ whatToDo : @noescape (ImmutableType) throws -> ReturnType) rethrows -> ReturnType { switch _pointer { case .Default(let i): return try whatToDo(i) case .Mutable(let m): // TODO: It should be possible to reflect the constraint that MutableType is a subtype of ImmutableType in the generics for the class, but I haven't figured out how yet. For now, cheat and unsafe bit cast. return try whatToDo(unsafeBitCast(m, to: ImmutableType.self)) } } var reference : ImmutableType { switch _pointer { case .Default(let i): return i case .Mutable(let m): // TODO: It should be possible to reflect the constraint that MutableType is a subtype of ImmutableType in the generics for the class, but I haven't figured out how yet. For now, cheat and unsafe bit cast. return unsafeBitCast(m, to: ImmutableType.self) } } }
apache-2.0
dbca6cdf9bd8ba275097c08e2973334a
37.056064
316
0.587054
4.910822
false
false
false
false
freeletics/FLTextView
FLTextView/FLTextView.swift
1
8195
// // FLTextView.swift // FLTextView // // Created by Danilo Bürger on 07.04.15. // Copyright (c) 2015 Freeletics GmbH (https://www.freeletics.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 @objc(FLTextView) open class FLTextView: UITextView { // MARK: - Private Properties private let placeholderView = UITextView(frame: CGRect.zero) // MARK: - Placeholder Properties /// This property applies to the entire placeholder string. /// The default placeholder color is 70% gray. /// /// If you want to apply the color to only a portion of the placeholder, /// you must create a new attributed string with the desired style information /// and assign it to the attributedPlaceholder property. @IBInspectable public var placeholderTextColor: UIColor? { get { return placeholderView.textColor } set { placeholderView.textColor = newValue } } /// The string that is displayed when there is no other text in the text view. @IBInspectable public var placeholder: String? { get { return placeholderView.text } set { placeholderView.text = newValue setNeedsLayout() } } /// This property controls when the placeholder should hide. /// Setting it to `true` will hide the placeholder right after the text view /// becomes first responder. Setting it to `false` will hide the placeholder /// only when the user starts typing in the text view. /// Default value is `false` @IBInspectable public var hidesPlaceholderWhenEditingBegins: Bool = false /// The styled string that is displayed when there is no other text in the text view. public var attributedPlaceholder: NSAttributedString? { get { return placeholderView.attributedText } set { placeholderView.attributedText = newValue setNeedsLayout() } } /// Returns true if the placeholder is currently showing. public var isShowingPlaceholder: Bool { return placeholderView.superview != nil } // MARK: - Observed Properties override open var text: String! { didSet { showPlaceholderViewIfNeeded() } } override open var attributedText: NSAttributedString! { didSet { showPlaceholderViewIfNeeded() } } override open var font: UIFont? { didSet { placeholderView.font = font } } override open var textAlignment: NSTextAlignment { didSet { placeholderView.textAlignment = textAlignment } } override open var textContainerInset: UIEdgeInsets { didSet { placeholderView.textContainerInset = textContainerInset } } // MARK: - Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupPlaceholderView() } override public init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setupPlaceholderView() } deinit { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self) } // MARK: - Notification func textDidChange(notification: NSNotification) { showPlaceholderViewIfNeeded() } func textViewDidBeginEditing(notification: NSNotification) { if hidesPlaceholderWhenEditingBegins && isShowingPlaceholder { placeholderView.removeFromSuperview() invalidateIntrinsicContentSize() setContentOffset(CGPoint.zero, animated: false) } } func textViewDidEndEditing(notification: NSNotification) { if hidesPlaceholderWhenEditingBegins { if !isShowingPlaceholder && (text == nil || text.isEmpty) { addSubview(placeholderView) invalidateIntrinsicContentSize() setContentOffset(CGPoint.zero, animated: false) } } } // MARK: - UIView open override func layoutSubviews() { super.layoutSubviews() resizePlaceholderView() } open override var intrinsicContentSize: CGSize { if isShowingPlaceholder { return placeholderSize() } return super.intrinsicContentSize } // MARK: - Placeholder private func setupPlaceholderView() { placeholderView.isOpaque = false placeholderView.backgroundColor = UIColor.clear placeholderView.textColor = UIColor(white: 0.7, alpha: 1.0) placeholderView.isEditable = false placeholderView.isScrollEnabled = true placeholderView.isUserInteractionEnabled = false placeholderView.isAccessibilityElement = false placeholderView.isSelectable = false showPlaceholderViewIfNeeded() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(textDidChange(notification:)), name: NSNotification.Name.UITextViewTextDidChange, object: self) notificationCenter.addObserver(self, selector: #selector(textViewDidBeginEditing(notification:)), name: NSNotification.Name.UITextViewTextDidBeginEditing, object: self) notificationCenter.addObserver(self, selector: #selector(textViewDidEndEditing(notification:)), name: NSNotification.Name.UITextViewTextDidEndEditing, object: self) } private func showPlaceholderViewIfNeeded() { if !hidesPlaceholderWhenEditingBegins { if text != nil && !text.isEmpty { if isShowingPlaceholder { placeholderView.removeFromSuperview() invalidateIntrinsicContentSize() setContentOffset(CGPoint.zero, animated: false) } } else { if !isShowingPlaceholder { addSubview(placeholderView) invalidateIntrinsicContentSize() setContentOffset(CGPoint.zero, animated: false) } } } } private func resizePlaceholderView() { if isShowingPlaceholder { let size = placeholderSize() let frame = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) if !placeholderView.frame.equalTo(frame) { placeholderView.frame = frame invalidateIntrinsicContentSize() } contentInset = UIEdgeInsetsMake(0.0, 0.0, size.height - contentSize.height, 0.0) } else { contentInset = UIEdgeInsets.zero } } private func placeholderSize() -> CGSize { var maxSize = self.bounds.size maxSize.height = CGFloat.greatestFiniteMagnitude return placeholderView.sizeThatFits(maxSize) } }
mit
04170309c65f64e83636ef62225314fe
33.720339
176
0.641811
5.64714
false
false
false
false
ricky840/FastCampusManualLayoutTest
FastCampusRickyManualLayoutTest/FastCampusManualLayoutTest.swift
1
1094
// // FastCampusManualLayoutTest.swift // FastCampusRickyManualLayoutTest // // Created by Ricky on 3/29/17. // Copyright © 2017 Ricky Yu. All rights reserved. // import UIKit extension UIView { public var width: CGFloat { get { return self.frame.size.width } set { self.frame.size.width = newValue } } public var height: CGFloat { get { return self.frame.size.height } set { self.frame.size.height = newValue } } public var top: CGFloat { get { return self.frame.origin.y } set { self.frame.origin.y = newValue } } public var left: CGFloat { get { return self.frame.origin.x } set { self.frame.origin.x = newValue } } public var right: CGFloat { get { return self.frame.origin.x + self.width } set { self.left = newValue - self.width } } public var bottom: CGFloat { get { return self.top + self.height } set { self.frame.origin.y = newValue - self.frame.size.height } } }
mit
562c7b9516c925558633ab7119d7ba3f
15.313433
61
0.569991
3.595395
false
false
false
false
peferron/algo
EPI/Searching/Find the missing IP address/swift/main.swift
1
1372
// swiftlint:disable variable_name public func findMissingNumber(_ numbers: [UInt8]) -> UInt8? { var missing: UInt8 = 0 // We process from the most significant bit (7th bit) down to the least significant bit (0th // bit). This makes this algorithm return the lowest missing number, which can be a nice // property to have. for i: UInt8 in (0..<8).reversed() { // Consider only the numbers that have the same 0...i bits as missing. let mask = i == 7 ? 0 : UInt8.max << i // Count how many numbers have their ith bit set to 0 and 1. var zeroCount = 0 var oneCount = 0 for number in numbers where number & mask == missing & mask { if (number >> i) & 1 == 1 { oneCount += 1 } else { zeroCount += 1 } } let combinationCount = 1 << Int(i) if zeroCount < combinationCount { // There is a missing number with its ith bit set to 0. // `missing` is initialized with 0s by default, so do nothing! } else if oneCount < combinationCount { // There is a missing number with its ith bit set to 1. missing |= (1 << i) } else { // All combinations are taken; there is no missing number. return nil } } return missing }
mit
26d1f06d3654e6863d54c286ad976c2d
34.179487
96
0.559038
4.341772
false
false
false
false
sharath-cliqz/browser-ios
Storage/Site.swift
2
2186
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared public protocol Identifiable: Equatable { var id: Int? { get set } } public func ==<T>(lhs: T, rhs: T) -> Bool where T: Identifiable { return lhs.id == rhs.id } public enum IconType: Int { public func isPreferredTo (_ other: IconType) -> Bool { return rank > other.rank } fileprivate var rank: Int { switch self { case .appleIconPrecomposed: return 5 case .appleIcon: return 4 case .icon: return 3 case .local: return 2 case .guess: return 1 case .noneFound: return 0 } } case icon = 0 case appleIcon = 1 case appleIconPrecomposed = 2 case guess = 3 case local = 4 case noneFound = 5 } open class Favicon: Identifiable { open var id: Int? = nil open let url: String open let date: Date open var width: Int? open var height: Int? open let type: IconType public init(url: String, date: Date = Date(), type: IconType) { self.url = url self.date = date self.type = type } } // TODO: Site shouldn't have all of these optional decorators. Include those in the // cursor results, perhaps as a tuple. open class Site: Identifiable { open var id: Int? = nil var guid: String? = nil open var tileURL: URL { return URL(string: url)?.domainURL() ?? URL(string: "about:blank")! } open let url: String open let title: String // Sites may have multiple favicons. We'll return the largest. open var icon: Favicon? open var latestVisit: Visit? open let bookmarked: Bool? public convenience init(url: String, title: String) { self.init(url: url, title: title, bookmarked: false) } public init(url: String, title: String, bookmarked: Bool?) { self.url = url self.title = title self.bookmarked = bookmarked } }
mpl-2.0
049c54c8a871af6613a9b4044a105125
23.840909
83
0.601098
3.989051
false
false
false
false
yukiasai/Shoyu
ShoyuExample/TableViewController.swift
1
5060
// // TableViewController.swift // Shoyu // // Created by asai.yuki on 2015/12/12. // Copyright © 2015年 yukiasai. All rights reserved. // import UIKit class TableViewController: UIViewController { @IBOutlet weak var tableView: TableView! let members = [ Member(firstName: "Hamada", lastName: "Hiro"), Member(firstName: "Hamada", lastName: "Tadashi"), Member(firstName: "Tamago", lastName: "GoGo"), Member(firstName: "", lastName: "Wasabi"), Member(firstName: "Lemon", lastName: "Honey"), Member(firstName: "", lastName: "Fred"), ] override func viewDidLoad() { super.viewDidLoad() tableView.source = Source().createSection { (section: Section<HeaderTableViewCell, FooterTableViewCell>) in section.createHeader { header in header.reuseIdentifier = "Header" header.height = 32 header.configureView = { headerCell, _ in headerCell.contentView.backgroundColor = UIColor.blue } } section.createFooter { footer in footer.createView = { [weak self] _ in return self?.createViewForFooterCell() } footer.configureView = { footerCell, _ in footerCell.contentView.backgroundColor = UIColor.orange } footer.titleFor = { _ -> String? in return "footer" } footer.heightFor = { _ -> CGFloat? in return 32 } } section.createRows(for: members) { (member: Member, row: Row<DefaultTableViewCell>) in row.height = 52 row.configureCell = configureMemberCell(member: member) row.didSelect = didSelectMember(member: member) } section.createRows(for: 5) { (index: UInt, row: Row<DefaultTableViewCell>) -> Void in row.heightFor = { _ -> CGFloat? in return 44 } row.canRemove = { _ -> Bool in return true } row.canMove = { _ -> Bool in return false } row.canMoveTo = { event -> Bool in return event.sourceIndexPath.section == event.destinationIndexPath.section } row.willRemove = { _ -> UITableViewRowAnimation? in return .left } row.didRemove = { event in print(event.row) } row.configureCell = configureCountCell(index: index) } } tableView.reloadData() tableView.source?.didMoveRow = { print(String(describing: $0) + " " + String(describing: $1)) } tableView.setEditing(true, animated: true) } private func configureMemberCell<T: DefaultTableViewCell>(member: Member) -> (T, Row<T>.RowInformation) -> Void { return { cell, _ in cell.setupWith(viewModel: DefaultTableViewCellModel(name: member)) } } private func didSelectMember<T>(member: Member) -> (Row<T>.RowInformation) -> Void { return { [weak self] _ in self?.memberSelected(member: member) } } private func configureCountCell<T: DefaultTableViewCell>(index: UInt) -> (T, Row<T>.RowInformation) -> Void { return { cell, _ in cell.nameLabel.text = String(index) } } private func memberSelected(member: Member) { print("Member selected: " + member.fullName) } deinit { print("TableViewController deinit") } private func createViewForFooterCell() -> FooterTableViewCell { let cell = FooterTableViewCell() let label = UILabel(frame: CGRect(x: 5, y: 5, width: 0, height: 0)) label.text = "Custom view footer" label.sizeToFit() cell.contentView.addSubview(label) return cell } } class DefaultTableViewCell: UITableViewCell { @IBOutlet var nameLabel: UILabel! func setupWith(viewModel: DefaultTableViewCellModel) { nameLabel.text = viewModel.fullName } deinit { print("DefaultTableViewCellModel deinit") } } class HeaderTableViewCell: UITableViewCell { } class FooterTableViewCell: UITableViewCell { } struct DefaultTableViewCellModel { var name: NameProtocol var fullName: String { return name.fullName } } class TableView: UITableView { deinit { print("TableView deinit") } } protocol NameProtocol { var firstName: String { get } var lastName: String { get } var fullName: String { get } } struct Member: NameProtocol { var firstName: String var lastName: String var fullName: String { return lastName + " " + firstName } }
mit
da812fa0040b5b1fef39a812b6fd5d93
29.835366
117
0.552897
4.890716
false
false
false
false
southfox/jfwindguru
JFWindguru/Classes/Model/SpotForecast.swift
1
2450
// // SpotForecast.swift // Xoshem-watch // // Created by Javier Fuchs on 10/7/15. // Copyright © 2015 Fuchs. All rights reserved. // import Foundation /* * SpotForecast * * Discussion: * Represents a model information of the stot or location when the forecast is obtained. * By inheritance the common attributes are parsed and filled in SpotInfo and Spot. * Contains the complete forecast (inside a single instance of ForecastModel) * * { * "id_spot": "64141", * "spotname": "Bariloche", * "country": "Argentina", * "id_country": 32, * "lat": -41.1281, * "lon": -71.348, * "alt": 770, * "tz": "America/Argentina/Mendoza", * "gmt_hour_offset": -3, * "sunrise": "07:11", * "sunset": "19:54", * "models": [ * "3" * ], * "tides": "0", * "forecast": { ... } * } * * */ public class SpotForecast: SpotInfo { var currentModel: String? = nil var forecasts = Array<ForecastModel>() required public convenience init?(map: [String:Any]) { self.init() mapping(map: map) } public override func mapping(map: [String:Any]) { super.mapping(map: map) guard let forecastDict = map["forecast"] as? [String: Any] else { return } for (k,v) in forecastDict { let tmpDictionary = ["model" : k , "info" : v] let forecastModel = ForecastModel(map: tmpDictionary) forecasts.append(forecastModel) currentModel = k } } override public var description : String { var aux : String = super.description aux += "\(type(of:self)): " if let currentModel = currentModel { aux += "currentModel \(currentModel), " } for model in models { for forecast in forecasts { if let fmodel = forecast.model, fmodel == model { aux += "Forecast model: \(fmodel)\n\(forecast.description)\n" } } } return aux } } extension SpotForecast { public func getForecast() -> Forecast? { guard let currentModel = currentModel else { return nil } for forecastModel in forecasts { if forecastModel.model == currentModel { return forecastModel.info } } return nil } }
mit
3d955d04d7295378ebe568ff76583778
24.247423
91
0.537362
3.856693
false
false
false
false
FandyLiu/FDDemoCollection
Swift/Apply/Apply/ApplyTableViewCellFactory.swift
1
2744
// // ApplyTableViewCellFactory.swift // Apply // // Created by QianTuFD on 2017/3/31. // Copyright © 2017年 fandy. All rights reserved. // import UIKit enum ApplyTableViewCellType { case common(CommonTableViewCellType) case image(ImageTableViewCellType) case button(ButtonTableViewCellType) } class ApplyTableViewCellFactory { class func registerApplyTableViewCell(_ tableView: UITableView) { register(tableView, cellClass: CommonTableViewCell.self) register(tableView, cellClass: ImageTableViewCell.self) register(tableView, cellClass: ButtonTableViewCell.self) } class func dequeueReusableCell(withTableView tableView: UITableView, indexPath: IndexPath, cellItems: [ApplyTableViewCellType], cellContentDict: [IndexPath]) -> ApplyTableViewCell? { switch cellItems[indexPath.row] { case let .common(type): let cell = dequeueReusableCell(withTableView: tableView, cellClass: CommonTableViewCell.self) cell?.myType = type return cell case let .image(type): let cell = dequeueReusableCell(withTableView: tableView, cellClass: ImageTableViewCell.self) cell?.myType = type return cell case let .button(type): let cell = dequeueReusableCell(withTableView: tableView, cellClass: ButtonTableViewCell.self) cell?.myType = type return cell } } class func dequeueReusableCell(withTableView tableView: UITableView, type: ApplyTableViewCellType) -> ApplyTableViewCell? { switch type { case let .common(type): let cell = dequeueReusableCell(withTableView: tableView, cellClass: CommonTableViewCell.self) cell?.myType = type return cell case let .image(type): let cell = dequeueReusableCell(withTableView: tableView, cellClass: ImageTableViewCell.self) cell?.myType = type return cell case let .button(type): let cell = dequeueReusableCell(withTableView: tableView, cellClass: ButtonTableViewCell.self) cell?.myType = type return cell } } fileprivate class func register<T: ApplyTableViewCell>(_ tableView: UITableView, cellClass: T.Type) where T: ApplyTableViewCellProtocol { tableView.register(cellClass, forCellReuseIdentifier: cellClass.indentifier) } fileprivate class func dequeueReusableCell<Cell: ApplyTableViewCell>(withTableView tableView: UITableView, cellClass: Cell.Type) -> Cell? where Cell: ApplyTableViewCellProtocol { return tableView.dequeueReusableCell(withIdentifier: cellClass.indentifier) as? Cell } }
mit
ccf9ebed067630ec5d08b22efb863e67
36.547945
186
0.686976
5.332685
false
false
false
false
jlso/EMProgressBar
Example/Example/ViewController.swift
1
1244
// // ViewController.swift // Example // // Created by Jeonglim So on 2015. 11. 24.. // Copyright © 2015년 estmob. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var progressBar:EMProgressBar! override func viewDidLoad() { super.viewDidLoad() let progressBar = EMProgressBar() progressBar.trackTintColor = UIColor.blackColor() progressBar.progressTintColor = UIColor.whiteColor() progressBar.contentInset = UIEdgeInsetsMake(2, 2, 2, 2) progressBar.progress = 0.5 self.view.addSubview(progressBar) progressBar.translatesAutoresizingMaskIntoConstraints = false var newConstraints = [NSLayoutConstraint]() newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[progressBar]-10-|", options: [], metrics: nil, views: ["progressBar":progressBar]) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-30-[progressBar(==24)]", options: [], metrics: nil, views: ["progressBar":progressBar]) NSLayoutConstraint.activateConstraints(newConstraints) } @IBAction func onValueChanged(sender:UISlider) { progressBar.progress = sender.value } }
mit
cd46ab1bddf9a232a736bc60f77a5145
36.606061
165
0.701048
5.236287
false
false
false
false
MichaelWangCH/vapor-example
Sources/App/Models/Blog.swift
1
873
import Vapor import Foundation import Fluent struct Blog: Model { var id: Node? var title: String var description: String? var exists: Bool = false init(title: String, description: String?) { self.id = UUID().uuidString.makeNode() self.title = title self.description = description } init(node: Node, in context: Context) throws { id = try node.extract("id") title = try node.extract("title") description = try node.extract("description") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "title": title, "description": description ]) } } extension Blog: Preparation { static func prepare(_ database: Database) throws { } static func revert(_ database: Database) throws { } }
mit
ca6430f3a3b89af030a276518b8e9eb1
21.384615
54
0.592211
4.343284
false
false
false
false
rambler-ios/RamblerConferences
Carthage/Checkouts/rides-ios-sdk/Carthage/Checkouts/ObjectMapper/ObjectMapperTests/ClassClusterTests.swift
2
2299
// // ClassClusterTests.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-09-18. // Copyright © 2015 hearst. All rights reserved. // import Foundation import XCTest import ObjectMapper class ClassClusterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testClassClusters() { let carName = "Honda" let JSON = ["name": carName, "type": "car"] if let vehicle = Mapper<Vehicle>().map(JSON){ XCTAssertNotNil(vehicle) XCTAssertNotNil(vehicle as? Car) XCTAssertEqual((vehicle as? Car)?.name, carName) } } func testClassClustersFromJSONString() { let carName = "Honda" let JSON = "{\"name\": \"\(carName)\", \"type\": \"car\"}" if let vehicle = Mapper<Vehicle>().map(JSON){ XCTAssertNotNil(vehicle) XCTAssertNotNil(vehicle as? Car) XCTAssertEqual((vehicle as? Car)?.name, carName) } } func testClassClusterArray() { let carName = "Honda" let JSON = [["name": carName, "type": "car"], ["type": "bus"], ["type": "vehicle"]] if let vehicles = Mapper<Vehicle>().mapArray(JSON){ XCTAssertNotNil(vehicles) XCTAssertTrue(vehicles.count == 3) XCTAssertNotNil(vehicles[0] as? Car) XCTAssertNotNil(vehicles[1] as? Bus) XCTAssertNotNil(vehicles[2]) XCTAssertEqual((vehicles[0] as? Car)?.name, carName) } } } class Vehicle: StaticMappable { var type: String? class func objectForMapping(map: Map) -> BaseMappable? { if let type: String = map["type"].value() { switch type { case "car": return Car() case "bus": return Bus() default: return Vehicle() } } return nil } init(){ } func mapping(map: Map) { type <- map["type"] } } class Car: Vehicle { var name: String? override class func objectForMapping(map: Map) -> BaseMappable? { return nil } override func mapping(map: Map) { super.mapping(map) name <- map["name"] } } class Bus: Vehicle { override func mapping(map: Map) { super.mapping(map) } }
mit
c2e45fc748d05024da9adade34819071
20.082569
111
0.640992
3.481818
false
true
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXReceipt/PXReceiptComponent.swift
1
547
import UIKit class PXReceiptComponent: PXComponentizable { var props: PXReceiptProps init(props: PXReceiptProps) { self.props = props } func render() -> UIView { return PXReceiptRenderer().render(self) } } class PXReceiptProps { var dateLabelString: String? var receiptDescriptionString: String? init(dateLabelString: String? = nil, receiptDescriptionString: String? = nil) { self.dateLabelString = dateLabelString self.receiptDescriptionString = receiptDescriptionString } }
mit
fdcdf64297a21a2d4752b3f9fc6ac86d
25.047619
83
0.698355
4.376
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/Localize/Localizator.swift
1
5174
import Foundation class Localizator { static let sharedInstance = Localizator() private var language: String = NSLocale.preferredLanguages[0] private var customTrans: [PXCustomTranslationKey: String]? } // MARK: Privates. extension Localizator { private func localizableDictionary() -> NSDictionary? { let languageBundle = Bundle(path: getLocalizedPath()) let languageID = getParentLanguageID() if let path = languageBundle?.path(forResource: "Localizable_\(languageID)", ofType: "plist") { return NSDictionary(contentsOfFile: path) } return NSDictionary() } private func parentLocalizableDictionary() -> NSDictionary? { let languageBundle = Bundle(path: getParentLocalizedPath()) let languageID = getParentLanguageID() if let path = languageBundle?.path(forResource: "Localizable_\(languageID)", ofType: "plist") { return NSDictionary(contentsOfFile: path) } else if let path = languageBundle?.path(forResource: "Localizable_es", ofType: "plist") { return NSDictionary(contentsOfFile: path) } fatalError("Localizable file NOT found") } } // MARK: Getters/ Setters extension Localizator { func setLanguage(language: PXLanguages) { if language == PXLanguages.PORTUGUESE { self.language = PXLanguages.PORTUGUESE_BRAZIL.rawValue } else { self.language = language.rawValue } self.customTrans = nil } func setLanguage(string: String) { if string == PXLanguages.PORTUGUESE.rawValue { self.language = PXLanguages.PORTUGUESE_BRAZIL.rawValue } else { self.language = string } self.customTrans = nil } func getLanguage() -> String { return language } // MoneyIn Custom verb support. func setLanguage(_ string: String, _ customTranslations: [PXCustomTranslationKey: String]) { self.language = string self.customTrans = customTranslations } func addCustomTranslation(_ key: PXCustomTranslationKey, _ translation: String) { if customTrans == nil { customTrans = [PXCustomTranslationKey: String]() } printDebug("Added custom translation: \(translation) for key: \(key.description)") customTrans?[key] = translation } } // MARK: Localization Paths extension Localizator { func getLocalizedID() -> String { let bundle = MercadoPagoBundle.bundle() let currentLanguage = getLanguage() let currentLanguageSeparated = currentLanguage.components(separatedBy: "-").first if bundle.path(forResource: currentLanguage, ofType: "lproj") != nil { return currentLanguage } else if let language = currentLanguageSeparated, bundle.path(forResource: language, ofType: "lproj") != nil { return language } else { return "es" } } private func getParentLanguageID() -> String { return getLanguage().components(separatedBy: "-").first ?? "es" } func getLocalizedPath() -> String { let bundle = MercadoPagoBundle.bundle() let pathID = getLocalizedID() return bundle.path(forResource: pathID, ofType: "lproj")! } private func getParentLocalizedPath() -> String { let bundle = MercadoPagoBundle.bundle() let pathID = getParentLanguageID() if let parentPath = bundle.path(forResource: pathID, ofType: "lproj") { return parentPath } return bundle.path(forResource: "es", ofType: "lproj")! } func localize(string: String) -> String { guard let localizedStringDictionary = localizableDictionary()?.value(forKey: string) as? NSDictionary, let localizedString = localizedStringDictionary.value(forKey: "value") as? String else { let parentLocalizableDictionary = self.parentLocalizableDictionary()?.value(forKey: string) as? NSDictionary if let parentLocalizedString = parentLocalizableDictionary?.value(forKey: "value") as? String { return parentLocalizedString } #if DEBUG assertionFailure("Missing translation for: \(string)") #endif return string } return localizedString } func getCustomTrans(_ targetKey: String) -> String? { if let cVerbs = customTrans { for (key, value) in cVerbs where key.getValue == targetKey { return value } } return nil } } // MARK: localized capability for Strings. extension String { var localized: String { if let customTrans = Localizator.sharedInstance.getCustomTrans(self) { return customTrans } var bundle: Bundle? = MercadoPagoBundle.bundle() if bundle == nil { bundle = Bundle.main } if let languageBundle = Bundle(path: Localizator.sharedInstance.getLocalizedPath()) { return languageBundle.localizedString(forKey: self, value: "", table: nil) } return self } }
mit
35a1744e48ae3ca38534f030cd8bb9c3
33.724832
199
0.635292
4.965451
false
false
false
false
wl879/SwiftyCss
SwiftyCss/SwiftyCss/CAStyle/Property.swift
1
20664
// Created by Wang Liang on 2017/4/8. // Copyright © 2017年 Wang Liang. All rights reserved. import UIKit import SwiftyNode import SwiftyBox extension CAStyler { static func hasFollower(property: [String: String]) -> Bool { if property["float"] != nil || property["autoSize"] != nil { return true } if property["right"] != nil || property["bottom"] != nil { return true } for k in ["top", "left", "width", "heigth", "position"] { if property[k]?.hasSuffix("%") == true || property[k]?.hasPrefix("[") == true { return true } } return false } static func clearProperty(layer: CALayer, styler: CAStyler?, name: String, isNone: Bool) { switch name { case "action": layer.actions = isNone ? nonActions : nil case "disable": styler?.disable = false case "hidden": layer.isHidden = false case "opacity": layer.opacity = 1 case "transform": layer.transform = CATransform3DMakeTranslation(0, 0, 0) case "mask", "overflow": layer.masksToBounds = false case "rasterize": layer.shouldRasterize = false case "radius": layer.cornerRadius = 0 case "backgroundColor", "background": layer.backgroundColor = .clear case "shadow": layer.shadowColor = nil layer.shadowOpacity = 0 case "width", "height": if styler?.hooks.isEmpty == false { styler!.setStatus( .checkHookChild ) } case "margin", "marginTop", "marginRight", "marginBottom", "marginLeft": if styler != nil { styler!.margin = name == "margin" ? (0, 0, 0, 0) : parseMargin(styler!, name: name, value: "0") layer.superlayer?.cssStyler.setStatus( .rankFloatChild ) } case "padding", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft": if styler != nil { styler!.padding = name == "padding" ? (0, 0, 0, 0) : parsePadding(styler!, name: name, value: "0") styler!.setStatus( .rankFloatChild ) } case "border", "borderTop", "borderRight", "borderBottom", "borderLeft": if styler != nil { styler!.border = name == "border" ? nil : parseBorder(styler!, name: name, value: "none") styler!.setStatus( .checkBorder ) } default: break } } static func setProperty(layer: CALayer, styler: CAStyler?, property: [String: String], altered: [String: String]) { if altered.isEmpty { return } let isfloat = property["float"] != nil if altered["transform"] != nil{ layer.transform = CATransform3DMakeTranslation(0, 0, 0) } setFrameProperty(layer: layer, styler: styler, proterty: property, altered: altered) for (name, value) in altered { if value == "none" { clearProperty(layer: layer, styler: styler, name: name, isNone: true) continue } switch name { case "float": layer.superlayer?.cssStyler.setStatus( .rankFloatChild ) break case "position": if let list = parseValues(value, limit: 2, layer: layer, percentOf: [".width", ".height"]) { layer.position = CGPoint(x: list[0], y: list[1]) } case "anchorPoint": if let list = parseValues(value, limit: 2, layer: layer, percentOf: ["width", "height"]) { let point = CGPoint(x: list[0], y: list[1]) layer.anchorPoint = point.x < 0 ? point : CGPoint(x: point.x/layer.bounds.width, y: point.y/layer.bounds.height ) } // Display case "hidden": let v = value == "false" ? false : true if layer.isHidden != v { layer.isHidden = v } case "rasterize": layer.shouldRasterize = value == "true" case "mask", "overflow": layer.masksToBounds = value == "hidden" || value == "true" ? true : false // Layout case "zPosition", "zIndex": layer.zPosition = CGFloat(value) ?? 1 case "padding", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft": if styler != nil { let padding = parsePadding(styler!, name: name, value: value) if styler!.padding != padding { styler!.padding = padding if isfloat { styler!.setStatus( .rankFloatChild ) } } } case "margin", "marginTop", "marginRight", "marginBottom", "marginLeft": if styler != nil { let margin = parsePadding(styler!, name: name, value: value) if styler!.margin != margin { styler!.margin = margin if isfloat { layer.superlayer?.cssStyler.setStatus( .rankFloatChild ) } } } // Style case "border", "borderTop", "borderRight", "borderBottom", "borderLeft": if styler != nil { styler!.border = parseBorder(styler!, name: name, value: value) styler!.setStatus( .checkBorder ) } case "opacity": layer.opacity = Float(value) ?? 1 case "fillColor", "fill": if layer is CAShapeLayer { (layer as! CAShapeLayer).fillColor = Color(value) } case "background": if let color = Color(value) { layer.backgroundColor = color }else{ setBackgroundImage(layer: layer, image: value) } case "backgroundColor": layer.backgroundColor = Color(value) case "backgroundImage": setBackgroundImage(layer: layer, image: value) case "radius": layer.cornerRadius = parseValue(value, layer: layer, percentOf: "width") ?? 0 // shadow case "shadow": let list = value.components(separatedBy: " ", trim: .whitespacesAndNewlines) if list.count >= 4 { layer.shadowOffset = CGSize(width: CGFloat(list[0]) ?? 0, height: CGFloat(list[1]) ?? 0) layer.shadowRadius = CGFloat(list[2]) ?? 0 layer.shadowColor = Color(list[3]) layer.shadowOpacity = list.count > 4 ? (Float(list[4]) ?? 1) : 1 } case "shadowOffset": if let list = parseValues(value) { if list.count == 2 { layer.shadowOffset = CGSize(width: list[0], height:list[1]) } } case "shadowOpacity": layer.shadowOpacity = Float(value) ?? 1 case "shadowRadius": layer.shadowRadius = CGFloat(value) ?? 0 case "shadowColor": layer.shadowColor = Color(value) case "transform": var offset = 0 var trans = CATransform3DMakeTranslation(0, 0, 0) while let m = TRANSFORM_LEXER.match(value, offset: offset) { switch m[1]! { case "perspective": trans.m34 = -1 / (parseValue(m[2]) ?? 1) case "translate": if let v = parseValues(m[2], layer: layer, percentOf: ["width", "height", "width"]) { let x = v.count > 0 ? v[0] : 0 let y = v.count > 1 ? v[1] : 0 let z = v.count > 2 ? v[2] : 0 trans = CATransform3DTranslate(trans, x, y, z) } case "scale": if let v = parseValues(m[2], layer: layer, percentOf: ["width", "height", "width"]) { let x = v.count > 0 ? v[0] : 1 let y = v.count > 1 ? v[1] : x let z = v.count > 2 ? v[2] : 1 trans = CATransform3DScale(trans, x, y, z) } case "rotate": if let v = parseValues(m[2], layer: layer) { let a = v[0] * CGFloat.pi / 180.0 if v.count == 1 { trans = CATransform3DRotate(trans, a, 0, 0, v[0] > 0 ? 1 : -1) }else{ let x:CGFloat = 1 let y = v.count > 1 ? v[1]/v[0] : 0 let z = v.count > 2 ? v[2]/v[0] : 0 trans = CATransform3DRotate(trans, a, x, y, z) } } default: assertionFailure("[SwiftyCSS.CACssDelegate.setTransformProperty] nonsupport transform property \"\(m[1]!)\"") } offset = m.lastIndex + 1 } layer.transform = trans // Text case "content", "textAlign", "fontSize", "fontName", "color", "wordWrap": if setTextProperty(layer: layer, key: name, value: value) { if property["autoSize"] != nil { styler?.setStatus( .checkSize ) } } default: break } } } static func setTextProperty(layer: CALayer, key: String, value: String) -> Bool { if let text_layer = layer as? CATextLayer { text_layer.contentsScale = UIScreen.main.scale switch key { case "wordWrap": text_layer.isWrapped = value == "true" case "content": text_layer.string = value.replacingOccurrences(of: "\\n", with: "\n") case "textAlign": switch value { case "right": text_layer.alignmentMode = kCAAlignmentRight case "center": text_layer.alignmentMode = kCAAlignmentCenter case "natural": text_layer.alignmentMode = kCAAlignmentNatural case "justified": text_layer.alignmentMode = kCAAlignmentJustified default: text_layer.alignmentMode = kCAAlignmentLeft } case "fontSize": if let size = CGFloat(value) { text_layer.fontSize = size } case "fontName": text_layer.font = CTFontCreateWithName(value as CFString, text_layer.fontSize, nil) case "color": text_layer.foregroundColor = Color(value) return true default: return false } }else if let label = layer.delegate as? UILabel { switch key { case "wordWrap": label.lineBreakMode = NSLineBreakMode.byWordWrapping label.numberOfLines = 0 case "content": label.text = value.replacingOccurrences(of: "\\n", with: "\n") case "textAlign": switch value { case "right": label.textAlignment = .right case "center": label.textAlignment = .center case "natural": label.textAlignment = .natural case "justified": label.textAlignment = .justified default: label.textAlignment = .left } case "fontSize": if let size = CGFloat(value) { label.font = label.font.withSize(size) } case "fontName": label.font = UIFont(name: value, size: label.font.pointSize) case "color": if let color = Color(value) { label.textColor = UIColor(cgColor: color) } return true default: return false } }else if let field = layer.delegate as? UITextField { switch key { case "content": field.text = value.replacingOccurrences(of: "\\n", with: "\n") case "textAlign": switch value { case "right": field.textAlignment = .right case "center": field.textAlignment = .center case "natural": field.textAlignment = .natural case "justified": field.textAlignment = .justified default: field.textAlignment = .left } case "fontSize": if let size = CGFloat(value) { field.font = field.font?.withSize(size) ?? UIFont.systemFont(ofSize: size) } case "fontName": field.font = UIFont(name: value, size: field.font?.pointSize ?? 17 ) case "color": if let color = Color(value) { field.textColor = UIColor(cgColor: color) } return true default: return false } }else if let view = layer.delegate as? UITextView { switch key { case "content": view.text = value.replacingOccurrences(of: "\\n", with: "\n") case "textAlign": switch value { case "right": view.textAlignment = .right case "center": view.textAlignment = .center case "natural": view.textAlignment = .natural case "justified": view.textAlignment = .justified default: view.textAlignment = .left } case "fontSize": if let size = CGFloat(value) { view.font = view.font?.withSize(size) ?? UIFont.systemFont(ofSize: size) } case "fontName": view.font = UIFont(name: value, size: view.font?.pointSize ?? 17 ) case "color": if let color = Color(value) { view.textColor = UIColor(cgColor: color) } return true default: return false } }else{ return false } return true } private static func setFrameProperty(layer: CALayer, styler: CAStyler?, proterty: [String: String], altered: [String: String]) { var frame = layer.frame var isfloat = proterty["float"] != nil var width_changed = false var height_changed = false for key in isfloat ? ["width", "minWidth", "maxWidth", "right"] : ["width", "minWidth", "maxWidth", "left", "right"] { if altered[key] != nil { if isfloat { isfloat = key != "right" } width_changed = true break } } for key in isfloat ? ["height", "minHeight", "maxHeight", "bottom"] : ["height", "minHeight", "maxHeight", "top", "bottom"] { if altered[key] != nil { if isfloat { isfloat = key != "bottom" } height_changed = true break } } if width_changed { if isfloat { frame.size.width = parseValue(proterty["width"], min: proterty["minWidth"], max: proterty["maxWidth"], def: 0, layer: layer, percentOf: ".width") }else{ let left = parseValue(proterty["left"], layer: layer, percentOf: ".width") let right = parseValue(proterty["right"], layer: layer, percentOf: ".width") if left != nil && right != nil { frame.size.width = (layer.superlayer?.bounds.size.width ?? 0) - left! - right! frame.origin.x = left! }else { frame.size.width = parseValue(proterty["width"], min: proterty["minWidth"], max: proterty["maxWidth"], def: frame.width, layer: layer, percentOf: ".width") if left != nil { frame.origin.x = left! }else if right != nil { frame.origin.x = (layer.superlayer?.bounds.size.width ?? 0) - frame.size.width - right! } } } } if height_changed { if isfloat { frame.size.height = parseValue(proterty["height"], min: proterty["minHeight"], max: proterty["maxHeight"], def: 0, layer: layer, percentOf: ".height") }else{ let top = parseValue(proterty["top"], layer: layer, percentOf: ".height") let bottom = parseValue(proterty["bottom"], layer: layer, percentOf: ".height") if top != nil && bottom != nil { frame.size.height = (layer.superlayer?.bounds.size.height ?? 0) - top! - bottom! frame.origin.y = top! }else{ frame.size.height = parseValue(proterty["height"], min: proterty["minHeight"], max: proterty["maxHeight"], def: frame.height, layer: layer, percentOf: ".height") if top != nil { frame.origin.y = top! }else if bottom != nil { frame.origin.y = (layer.superlayer?.bounds.size.height ?? 0) - frame.size.height - bottom! } } } } if frame != layer.frame { if frame.size != layer.frame.size { if isfloat { layer.superlayer?.cssStyler.setStatus( .rankFloatChild ) } if styler?.hooks.isEmpty == false { styler!.setStatus( .checkHookChild ) } } if isfloat { layer.frame.size = frame.size }else{ layer.frame = frame } } } private static func setBackgroundImage(layer: CALayer, image str: String){ if let url = CAStyler.toURL(str) { guard layer.contents == nil || layer.value(forKey: "_node_content_image_") as? String != url.absoluteString else { return } layer.setValue(url.absoluteString, forKey: "_node_content_image_") DispatchQueue(label: "loadImage").async { if let data = try? Data(contentsOf: url), let image = UIImage(data: data) { DispatchQueue.main.async { layer.contents = image.cgImage layer.setNeedsLayout() } }else{ layer.contents = nil print("[SwiftyCss] Cant load backgroundImage: \"\(str)\"") } } } } // MARK: - Private Static private static let TRANSFORM_LEXER = Re("(\\w+)\\s*\\(([^)]+)\\)") }
mit
16720fa2b4154780e9a5cd89f948f09f
39.832016
181
0.447849
5.096448
false
false
false
false
lgp123456/tiantianTV
douyuTV/douyuTV/Classes/BaseVc/XTCollectionViewLayout.swift
1
785
// // XTCollectionViewLayout.swift // douyuTV // // Created by 李贵鹏 on 16/8/24. // Copyright © 2016年 李贵鹏. All rights reserved. // /////////////////////////////////////////////自定义布局///////////////////////////////////////////////// import UIKit class XTCollectionViewLayout: UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() //设置cell的大小 itemSize = CGSize(width: XTScreenW, height: (XTScreenH)) //设置collectionView滚动方向 scrollDirection = .Horizontal //设置cell的行间距 minimumLineSpacing = 0 //设置cell的列间距 minimumInteritemSpacing = 0 collectionView?.backgroundColor = UIColor.whiteColor() } }
mit
c691f939fcbc8e686e3d885078af1f9c
25.444444
99
0.567227
4.824324
false
false
false
false
mkaply/firefox-ios
Extensions/Today/ImageButtonWithLabel.swift
4
1566
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class ImageButtonWithLabel: UIView { lazy var button = UIButton() lazy var label = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) performLayout() } fileprivate func performLayout() { addSubview(button) addSubview(label) button.imageView?.contentMode = .scaleAspectFit button.snp.makeConstraints { make in make.centerX.equalTo(self) make.top.equalTo(self.safeAreaLayoutGuide).offset(5) make.right.greaterThanOrEqualTo(self.safeAreaLayoutGuide).offset(40) make.left.greaterThanOrEqualTo(self.safeAreaLayoutGuide).inset(40) make.height.greaterThanOrEqualTo(60) } label.snp.makeConstraints { make in make.top.equalTo(button.snp.bottom).offset(10) make.leading.trailing.bottom.equalTo(self) make.height.greaterThanOrEqualTo(10) } label.numberOfLines = 1 label.lineBreakMode = .byWordWrapping label.textAlignment = .center } func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControl.Event) { button.addTarget(target, action: action, for: events) } }
mpl-2.0
a9e937fc2b9c59d646144db2e4b0a4c3
32.319149
102
0.65645
4.592375
false
false
false
false
youngsoft/TangramKit
TangramKitDemo/RelativeLayoutDemo/RLTest3ViewController.swift
1
6884
// // RLTest3ViewController.swift // TangramKit // // Created by zhangguangkai on 16/5/5. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit class RLTest3ViewController: UIViewController { override func loadView() { /* 这个例子展示的相对布局里面某些视图整体居中的实现机制。这个可以通过设置子视图的扩展属性的TGLayoutPos对象的equal方法的值为数组来实现。 对于AutoLayout来说一直被诟病的是要实现某些视图整体在父视图中居中时,需要在外层包裹一个视图,然后再将这个包裹的视图在父视图中居中。而对于TGRelativeLayout来说实现起来则非常的简单。 */ self.edgesForExtendedLayout = UIRectEdge(rawValue:0) //设置视图控制器中的视图尺寸不延伸到导航条或者工具条下面。您可以注释这句代码看看效果。 let rootLayout = TGRelativeLayout() rootLayout.backgroundColor = .white self.view = rootLayout let layout1 = createLayout1() //子视图整体水平居中的布局 layout1.tg_height.equal(100); layout1.tg_width.equal(.fill); let layout2 = createLayout2() //子视图整体垂直居中的布局 let layout3 = createLayout3() //子视图整体居中的布局。 layout1.backgroundColor = CFTool.color(0) layout2.backgroundColor = CFTool.color(0) layout3.backgroundColor = CFTool.color(0) layout1.tg_width.equal(rootLayout.tg_width) layout2.tg_width.equal(rootLayout.tg_width) layout3.tg_width.equal(rootLayout.tg_width) //均分三个布局的高度。 layout1.tg_height.equal([layout2.tg_height.add(-10), layout3.tg_height]).add(-10) layout2.tg_top.equal(layout1.tg_bottom, offset:10) layout3.tg_top.equal(layout2.tg_bottom, offset:10) rootLayout.addSubview(layout1) rootLayout.addSubview(layout2) rootLayout.addSubview(layout3) } override func viewDidLoad() { super.viewDidLoad() } } //MARK: - Layout Construction extension RLTest3ViewController { func createLabel(_ title: String, backgroundColor color: UIColor) -> UILabel { let v = UILabel() v.backgroundColor = color v.text = title v.textAlignment = .center v.font = CFTool.font(17) v.sizeToFit() v.layer.shadowOffset = CGSize(width: CGFloat(3), height: CGFloat(3)) v.layer.shadowColor = CFTool.color(4).cgColor v.layer.shadowRadius = 2 v.layer.shadowOpacity = 0.3 return v } //子视图整体水平居中的布局 func createLayout1() -> TGRelativeLayout { let layout = TGRelativeLayout() let titleLabel = UILabel() titleLabel.text = NSLocalizedString("subviews horz centered in superview", comment:"") titleLabel.font = CFTool.font(16) titleLabel.textColor = CFTool.color(4) titleLabel.sizeToFit() layout.addSubview(titleLabel) let v1 = self.createLabel("A", backgroundColor: CFTool.color(5)) v1.tg_width.equal(100) v1.tg_height.equal(50) v1.tg_centerY.equal(0) layout.addSubview(v1) let v2 = self.createLabel("B", backgroundColor: CFTool.color(6)) v2.tg_width.equal(50) v2.tg_height.equal(50) v2.tg_centerY.equal(0) layout.addSubview(v2) //通过为tg_centerX等于一个数组值,表示他们之间整体居中,还可以设置其他视图的偏移量。 v1.tg_centerX.equal([v2.tg_centerX.offset(20)]) return layout } //子视图整体垂直居中的布局 func createLayout2() -> TGRelativeLayout { let layout = TGRelativeLayout() let titleLabel = UILabel() titleLabel.text = NSLocalizedString("subviews vert centered in superview", comment:"") titleLabel.font = CFTool.font(16) titleLabel.textColor = CFTool.color(4) titleLabel.sizeToFit() layout.addSubview(titleLabel) let v1 = self.createLabel("A", backgroundColor: CFTool.color(5)) v1.tg_width.equal(200) v1.tg_height.equal(50) v1.tg_centerX.equal(0) layout.addSubview(v1) let v2 = self.createLabel("B", backgroundColor: CFTool.color(6)) v2.tg_width.equal(200) v2.tg_height.equal(30) v2.tg_centerX.equal(0) layout.addSubview(v2) //通过为tg_centerY等于一个数组值,表示v1和v2在父布局视图之内整体垂直居中,这里的20表示v1和v2之间还有20的间隔。 v1.tg_centerY.equal([v2.tg_centerY.offset(20)]) return layout } //子视图整体居中布局 func createLayout3() -> TGRelativeLayout { let layout = TGRelativeLayout() let titleLabel = UILabel() titleLabel.text = NSLocalizedString("subviews centered in superview", comment:"") titleLabel.font = CFTool.font(16) titleLabel.textColor = CFTool.color(4) titleLabel.sizeToFit() layout.addSubview(titleLabel) let lb1up = self.createLabel("top left", backgroundColor: CFTool.color(5)) layout.addSubview(lb1up) let lb1down = self.createLabel("bottom left", backgroundColor: CFTool.color(6)) layout.addSubview(lb1down) let lb2up = self.createLabel("top center", backgroundColor: CFTool.color(7)) layout.addSubview(lb2up) let lb2down = self.createLabel("center", backgroundColor: CFTool.color(8)) layout.addSubview(lb2down) let lb3up = self.createLabel("top right", backgroundColor: CFTool.color(9)) layout.addSubview(lb3up) let lb3down = self.createLabel("bottom right", backgroundColor: CFTool.color(10)) layout.addSubview(lb3down) //左,中,右三组视图分别整体垂直居中显示,并且下面和上面间隔10 lb1up.tg_centerY.equal([lb1down.tg_centerY.offset(10)]) lb2up.tg_centerY.equal([lb2down.tg_centerY.offset(10)]) lb3up.tg_centerY.equal([lb3down.tg_centerY.offset(10)]) //上面的三个视图整体水平居中显示并且间隔60 lb1up.tg_centerX.equal([lb2up.tg_centerX.offset(60), lb3up.tg_centerX.offset(60)]) //下面的三个视图的水平中心点和上面三个视图的水平中心点对齐 lb1down.tg_centerX.equal(lb1up.tg_centerX) lb2down.tg_centerX.equal(lb2up.tg_centerX) lb3down.tg_centerX.equal(lb3up.tg_centerX) return layout } }
mit
b032b4716dd0d2ed0b6ceef0a495e7cc
32.153005
111
0.624361
3.592066
false
false
false
false
ahoppen/swift
test/stdlib/IntegerCompatibility.swift
32
1819
// RUN: %target-build-swift %s -swift-version 4 -typecheck func byteswap_n(_ a: UInt64) -> UInt64 { return ((a & 0x00000000000000FF) &<< 56) | ((a & 0x000000000000FF00) &<< 40) | ((a & 0x0000000000FF0000) &<< 24) | ((a & 0x00000000FF000000) &<< 8) | ((a & 0x000000FF00000000) &>> 8) | ((a & 0x0000FF0000000000) &>> 24) | ((a & 0x00FF000000000000) &>> 40) | ((a & 0xFF00000000000000) &>> 56) } // expression should not be too complex func radar31845712(_ i: Int, _ buffer: [UInt8]) { _ = UInt64(buffer[i]) | (UInt64(buffer[i + 1]) &<< 8) | (UInt64(buffer[i + 2]) &<< 16) | (UInt64(buffer[i + 3]) &<< 24) | (UInt64(buffer[i + 4]) &<< 32) | (UInt64(buffer[i + 5]) &<< 40) | (UInt64(buffer[i + 6]) &<< 48) | (UInt64(buffer[i + 7]) &<< 56) } // expression should not be too complex func radar32149641() { func from(bigEndian input: UInt32) -> UInt32 { var val: UInt32 = input return withUnsafePointer(to: &val) { (ptr: UnsafePointer<UInt32>) -> UInt32 in return ptr.withMemoryRebound(to: UInt8.self, capacity: 4) { data in return (UInt32(data[3]) &<< 0) | (UInt32(data[2]) &<< 8) | (UInt32(data[1]) &<< 16) | (UInt32(data[0]) &<< 24) } } } } func homogeneousLookingShiftAndAMask(_ i64: Int64) { _ = (i64 >> 8) & 0xFF } func negativeShift(_ u8: UInt8) { _ = (u8 << -1) } func sr5176(description: String = "unambiguous Int32.init(bitPattern:)") { _ = Int32(bitPattern: 0) // should compile without ambiguity } func sr6634(x: UnsafeBufferPointer<UInt8>) -> Int { return x.lazy.filter { $0 > 127 || $0 == 0 }.count // should be unambiguous } // abs of an integer literal func returnIntAbs() -> Int { let x = abs(-8) return x }
apache-2.0
19c13129aa5754deb63450b61369568a
27.873016
82
0.55635
3.011589
false
false
false
false
JigarM/Swift-Tutorials
UICollectionView+Swift/UICollectionView+Swift/AlbumViewController.swift
3
4327
// // AlbumViewController.swift // UICollectionView+Swift // // Created by Mobmaxime on 14/08/14. // Copyright (c) 2014 Jigar M. All rights reserved. // import UIKit let reuseIdentifier = "Cell" class AlbumViewController: UICollectionViewController { var Albums = Array<String>() @IBAction func EditAlbumPressed(sender : AnyObject) { if(self.navigationItem.rightBarButtonItem?.title == "Edit"){ self.navigationItem.rightBarButtonItem?.title = "Done" //Looping through CollectionView Cells in Swift //http://stackoverflow.com/questions/25490380/looping-through-collectionview-cells-in-swift for item in self.collectionView!.visibleCells() as [AlbumCell] { var indexpath : NSIndexPath = self.collectionView!.indexPathForCell(item as AlbumCell)! var cell : AlbumCell = self.collectionView!.cellForItemAtIndexPath(indexpath) as AlbumCell //Profile Picture //var img : UIImageView = cell.viewWithTag(100) as UIImageView //img.image = UIImage(named: "q.png") as UIImage //Close Button var close : UIButton = cell.viewWithTag(102) as UIButton close.hidden = false } } else { self.navigationItem.rightBarButtonItem?.title = "Edit" self.collectionView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() Albums = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png", "g.png", "h.png", "i.png", "j.png", "k.png", "l.png", "m.png"] } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // #pragma mark UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView?) -> Int { return 1 } override func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int { return Albums.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { /* We can use multiple way to create a UICollectionViewCell. */ //1. //We can use Reusablecell identifier with custom UICollectionViewCell /* let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell var AlbumImage : UIImageView = cell.viewWithTag(100) as UIImageView AlbumImage.image = UIImage(named: Albums[indexPath.row]) */ //2. //You can create a Class file for UICollectionViewCell and Set the appropriate component and assign the value to that class let cell : AlbumCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as AlbumCell cell.backgroundView = UIImageView(image: UIImage(named: "photo-frame.png")) as UIView cell.AlbumImage?.image = UIImage(named: Albums[indexPath.row]) if self.navigationItem.rightBarButtonItem!.title == "Edit" { cell.CloseImage?.hidden = true } else { cell.CloseImage?.hidden = false } //Layer property in Objective C => "http://iostutorialstack.blogspot.in/2014/04/how-to-assign-custom-tag-or-value-to.html" cell.CloseImage?.layer.setValue(indexPath.row, forKey: "index") cell.CloseImage?.addTarget(self, action: "deletePhoto:", forControlEvents: UIControlEvents.TouchUpInside) return cell } func deletePhoto(sender:UIButton) { let i : Int = (sender.layer.valueForKey("index")) as Int Albums.removeAtIndex(i) self.collectionView!.reloadData() } }
apache-2.0
2b8fd3e9adbeea1cd38b9d177429ae6a
35.982906
139
0.626531
5.084606
false
false
false
false
SergeyPetrachkov/VIPERTemplates
VIPER/Siberian Table.xctemplate/UIViewController/___FILEBASENAME___ViewController.swift
1
4629
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the SergeyPetrachkov VIPER Xcode Templates so // you can apply VIPER architecture to your iOS projects // import UIKit import SiberianVIPER class ___VARIABLE_moduleName___ViewController: UITableViewController { // MARK: - UI properties // MARK: - Essentials var presenter: ___VARIABLE_moduleName___PresenterInput? lazy var displayManager: SiberianCollectionManager? = { [weak self] in guard let strongSelf = self, let provider = strongSelf.presenter as? AnySiberianCollectionSource else { return nil } let manager = SiberianCollectionManager(provider: provider, delegate: strongSelf.presenter as? SiberianCollectionDelegate) return manager }() // MARK: Initializers override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Setup fileprivate func setup() { self.tableView.dataSource = self.displayManager self.tableView.delegate = self.displayManager self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: #selector(self.handleRefresh(_:)), for: .valueChanged) self.refreshControl?.tintColor = UIColor.darkGray } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.setup() } // MARK: - Actions @objc fileprivate func handleRefresh(_ refreshControl: UIRefreshControl) { self.presenter?.refresh() } } extension ___VARIABLE_moduleName___ViewController: ___VARIABLE_moduleName___PresenterOutput { func didEnterPendingState(visible: Bool, blocking: Bool) { self.tableView.isUserInteractionEnabled = !blocking if visible { self.refreshControl?.beginRefreshing() } } func didExitPendingState() { self.tableView.isUserInteractionEnabled = true self.refreshControl?.endRefreshing() } func didChangeState(viewModel : ___VARIABLE_moduleName___.DataContext.ViewModel) { if viewModel.changeSet.count == 0 { self.presenter?.exitPendingState() return } var newIndexPaths = [IndexPath]() var editedIndexPaths = [IndexPath]() var deletedIndexPaths = [IndexPath]() var shouldScrollToTop = false viewModel.changeSet.forEach({ change in switch change { case .new(let indexPath): if let indexPath = indexPath { newIndexPaths.append(indexPath) } case .edit(let indexPath): editedIndexPaths.append(indexPath) case .delete(let indexPath): deletedIndexPaths.append(indexPath) } }) if deletedIndexPaths.count > 0 { shouldScrollToTop = true } if #available(iOS 11.0, *) { self.tableView.performBatchUpdates({ if deletedIndexPaths.count > 0 { self.tableView.deleteRows(at: deletedIndexPaths, with: .automatic) } if newIndexPaths.count > 0 { self.tableView.insertRows(at: newIndexPaths, with: .automatic) } if editedIndexPaths.count > 0 { self.tableView.reloadRows(at: editedIndexPaths, with: .automatic) } }, completion: { result in print("___VARIABLE_moduleName___ batch update ended with result: \(result) \n\rtotal: \(viewModel.items.count) \n\rnew:\(newIndexPaths.count) \n\rchanged: \(editedIndexPaths.count) \n\rdeleted: \(deletedIndexPaths.count)") if shouldScrollToTop, self.tableView.contentOffset.y > 120 { self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true) } self.presenter?.exitPendingState() }) } else { self.tableView.beginUpdates() if deletedIndexPaths.count > 0 { self.tableView.deleteRows(at: deletedIndexPaths, with: .automatic) } if newIndexPaths.count > 0 { self.tableView.insertRows(at: newIndexPaths, with: .automatic) } if editedIndexPaths.count > 0 { self.tableView.reloadRows(at: editedIndexPaths, with: .automatic) } self.presenter?.exitPendingState() print("-OLD- : ___VARIABLE_moduleName___ batch update ended. \n\rtotal: \(viewModel.items.count) new:\(newIndexPaths.count) changed: \(editedIndexPaths.count) deleted: \(deletedIndexPaths.count)") self.tableView.endUpdates() return } } }
mit
0486ab668f4f8e8aed02635d97dfaae1
34.068182
230
0.669043
4.547151
false
false
false
false
justinmakaila/Moya
Tests/MultipartFormDataSpec.swift
5
771
import Quick import Nimble @testable import Moya class MultiPartFormData: QuickSpec { override func spec() { it("initializes correctly") { let fileURL = URL(fileURLWithPath: "/tmp.txt") let data = MultipartFormData( provider: .file(fileURL), name: "MyName", fileName: "tmp.txt", mimeType: "text/plain" ) expect(data.name) == "MyName" expect(data.fileName) == "tmp.txt" expect(data.mimeType) == "text/plain" if case .file(let url) = data.provider { expect(url) == fileURL } else { fail("The provider was not initialized correctly.") } } } }
mit
e21c940b4ba164942efc30a789971478
27.555556
67
0.503243
4.644578
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/WebActions/AAWebActionController.swift
4
1516
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAWebActionController: AAViewController, UIWebViewDelegate { fileprivate var webView = UIWebView() fileprivate let regex: AARegex fileprivate let desc: ACWebActionDescriptor public init(desc: ACWebActionDescriptor) { self.desc = desc self.regex = AARegex(desc.getRegexp()) super.init() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() webView.delegate = self view.addSubview(webView) webView.loadRequest(URLRequest(url: URL(string: desc.getUri())!)) } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds } open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.url { let rawUrl = url.absoluteString // Match end url if regex.test(rawUrl) { self.executeSafe(Actor.completeWebAction(withHash: desc.getActionHash(), withUrl: rawUrl)) { (val) -> Void in self.dismissController() } return false } } return true } }
agpl-3.0
54f311fb04b2a939bb3ada986dd6fda8
27.074074
135
0.593008
5.053333
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 2/Breadcrumbs/Breadcrumbs-7/Breadcrumbs/BCOptionsTableViewController.swift
2
4389
// // BCOptionsTableViewController.swift // Breadcrumbs // // Created by Nicholas Outram on 22/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit protocol BCOptionsSheetDelegate : class { func dismissWithUpdatedOptions() } class BCOptionsTableViewController: UITableViewController { // MARK: - Outlets @IBOutlet weak var backgroundUpdateSwitch: UISwitch! @IBOutlet weak var headingUPSwitch: UISwitch! @IBOutlet weak var headingUPLabel: UILabel! @IBOutlet weak var showTrafficSwitch: UISwitch! @IBOutlet weak var distanceSlider: UISlider! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var gpsPrecisionLabel: UILabel! @IBOutlet weak var gpsPrecisionSlider: UISlider! //Delegate property weak var delegate : BCOptionsSheetDelegate? // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Actions @IBAction func doBackgroundUpdateSwitch(sender: AnyObject) { print("\(__FUNCTION__)") } @IBAction func doHeadingUpSwitch(sender: AnyObject) { print("\(__FUNCTION__)") } @IBAction func doShowTrafficSwitch(sender: AnyObject) { print("\(__FUNCTION__)") } @IBAction func doDistanceSliderChanged(sender: AnyObject) { print("\(__FUNCTION__)") } @IBAction func doGPSPrecisionSliderChanged(sender: AnyObject) { print("\(__FUNCTION__)") } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 4 { self.delegate?.dismissWithUpdatedOptions() } } }
mit
7d5e0360db1b99f170609d4d7aaa697b
31.746269
157
0.677985
5.450932
false
false
false
false
kenwilcox/Petitions
Petitions/DetailViewController.swift
1
1242
// // DetailViewController.swift // Petitions // // Created by Kenneth Wilcox on 11/11/15. // Copyright © 2015 Kenneth Wilcox. All rights reserved. // import UIKit import WebKit class DetailViewController: UIViewController { var webView: WKWebView! var detailItem: [String: String]! @IBOutlet weak var doneButton: UIBarButtonItem! override func loadView() { webView = WKWebView() view = webView if UIDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { self.doneButton.enabled = false self.doneButton.tintColor = UIColor.clearColor() } } override func viewDidLoad() { super.viewDidLoad() guard detailItem != nil else { return } if let body = detailItem["body"] { var html = "<html>" html += "<head>" html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" html += "<style> body { font-size: 150%; } </style>" html += "</head>" html += "<body>" html += body html += "</body>" html += "</html>" webView.loadHTMLString(html, baseURL: nil) } } @IBAction func doneButtonPressed(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } }
mit
24868a669b4981007aaa5d48d64a554a
23.84
88
0.626914
4.41637
false
false
false
false
shintarogit/wcsession_rx
WCSession+Rx/RxWCSessionDelegateProxy.swift
1
1690
// // RxWCSessionDelegateProxy.swift // WCSession+Rx // // Created by Inomoto Shintaro on 2017/02/19. // Copyright © 2017年 Inomoto Shintaro. All rights reserved. // import WatchConnectivity import RxSwift import RxCocoa extension WCSession: HasDelegate { public typealias Delegate = WCSessionDelegate } @available(watchOSApplicationExtension 2.2, *) public class RxWCSessionDelegateProxy: DelegateProxy<WCSession, WCSessionDelegate>, WCSessionDelegate, DelegateProxyType { public init(session: WCSession) { super.init(parentObject: session, delegateProxy: RxWCSessionDelegateProxy.self) } public static func registerKnownImplementations() { self.register { RxWCSessionDelegateProxy(session: $0) } } fileprivate var _activationStateSubject: PublishSubject<WCSessionActivationState>? internal var activationStateSubject: PublishSubject<WCSessionActivationState> { if let subject = _activationStateSubject { return subject } let subject = PublishSubject<WCSessionActivationState>() _activationStateSubject = subject return subject } public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { if let error = error { _activationStateSubject?.on(.error(error)) } else { _activationStateSubject?.on(.next(activationState)) } _forwardToDelegate?.session(session, activationDidCompleteWith: activationState, error: error) } deinit { _activationStateSubject?.on(.completed) } }
mit
497b00137b84b1b9a2944f2b3682007e
29.125
131
0.694724
5.143293
false
false
false
false
tkremenek/swift
test/Constraints/casts_objc.swift
4
3703
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s // REQUIRES: objc_interop import Foundation struct NotClass {} class SomeClass {} func nsobject_as_class_cast<T>(_ x: NSObject, _: T) { let _ = x is AnyObject.Type let _ = x as! AnyObject.Type let _ = x as? AnyObject.Type let _ = x is Any.Type let _ = x as! Any.Type let _ = x as? Any.Type let _ = x is SomeClass.Type let _ = x as! SomeClass.Type let _ = x as? SomeClass.Type let _ = x is T.Type let _ = x as! T.Type let _ = x as? T.Type let _ = x is NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} let _ = x as! NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} let _ = x as? NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} } // <rdar://problem/20294245> QoI: Error message mentions value rather than key for subscript func test(_ a : CFString!, b : CFString) { let dict = NSMutableDictionary() let object = NSObject() dict[a] = object dict[b] = object } // <rdar://problem/22507759> QoI: poor error message for invalid unsafeDowncast() let r22507759: NSObject! = "test" as NSString let _: NSString! = unsafeDowncast(r22507759) // expected-error {{missing argument for parameter 'to' in call}} // rdar://problem/29496775 / SR-3319 func sr3319(f: CGFloat, n: NSNumber) { let _ = [f].map { $0 as NSNumber } let _ = [n].map { $0 as! CGFloat } } func alwaysSucceedingConditionalCasts(f: CGFloat, n: NSNumber) { let _ = f as? NSNumber // expected-warning{{conditional cast from 'CGFloat' to 'NSNumber' always succeeds}} let _ = n as? CGFloat } func optionalityReducingCasts(f: CGFloat?, n: NSNumber?) { let _ = f as? NSNumber // expected-warning{{conditional downcast from 'CGFloat?' to 'NSNumber' is a bridging conversion; did you mean to use 'as'?}} let _ = f as! NSNumber // expected-warning{{forced cast from 'CGFloat?' to 'NSNumber' only unwraps and bridges; did you mean to use '!' with 'as'?}} let _ = n as? CGFloat let _ = n as! CGFloat } func optionalityMatchingCasts(f: CGFloat?, n: NSNumber?) { let _ = f as NSNumber? let _ = f as? NSNumber? // expected-warning{{conditional cast from 'CGFloat?' to 'NSNumber?' always succeeds}} let _ = f as! NSNumber? // expected-warning{{forced cast from 'CGFloat?' to 'NSNumber?' always succeeds; did you mean to use 'as'?}}{{13-16=as}} let _ = n as? CGFloat? let _ = n as! CGFloat? } func optionalityMatchingCastsIUO(f: CGFloat?!, n: NSNumber?!) { let _ = f as NSNumber? let _ = f as? NSNumber? // expected-warning{{conditional downcast from 'CGFloat??' to 'NSNumber?' is a bridging conversion; did you mean to use 'as'?}} let _ = f as! NSNumber? // expected-warning{{forced cast from 'CGFloat??' to 'NSNumber?' only unwraps and bridges; did you mean to use '!' with 'as'?}} let _ = n as? CGFloat? let _ = n as! CGFloat? } func optionalityMismatchingCasts(f: CGFloat, n: NSNumber, fooo: CGFloat???, nooo: NSNumber???) { _ = f as NSNumber? _ = f as NSNumber?? let _ = fooo as NSNumber?? // expected-error{{'CGFloat???' is not convertible to 'NSNumber??'}} //expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{16-18=as!}} let _ = fooo as NSNumber???? // okay: injects extra optionals } func anyObjectCasts(xo: [Int]?, xooo: [Int]???, x: [Int]) { _ = x as AnyObject _ = x as AnyObject? _ = xo as AnyObject _ = xo as AnyObject? _ = xooo as AnyObject?? _ = xooo as AnyObject??? _ = xooo as AnyObject???? // okay: injects extra optionals }
apache-2.0
cb40dea81c2c8e94838fee8f1679ae88
37.175258
153
0.653254
3.438254
false
false
false
false
lcddhr/BSImagePicker
Pod/Classes/Model/AlbumsDataSource.swift
2
6538
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos final class AlbumsDataSource: NSObject, UITableViewDataSource, AssetsDelegate, Selectable, PHPhotoLibraryChangeObserver { var delegate: AssetsDelegate? private var _assetsModel: AssetsModel<PHAssetCollection> private let albumCellIdentifier = "albumCell" override init() { let fetchOptions = PHFetchOptions() // Camera roll fetch result let cameraRollResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: fetchOptions) // Albums fetch result let albumResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions) _assetsModel = AssetsModel(fetchResult: [cameraRollResult, albumResult]) super.init() PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) } deinit { PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return _assetsModel.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _assetsModel[section].count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(albumCellIdentifier, forIndexPath: indexPath) as! AlbumCell // Fetch album if let album = _assetsModel[indexPath.section][indexPath.row] as? PHAssetCollection { // Title cell.albumTitleLabel.text = album.localizedTitle // Selected cell.selected = contains(_assetsModel.selections(), album) // Selection style cell.selectionStyle = .None // Set images let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] // TODO: Limit result to 3 images fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue) PHAsset.fetchAssetsInAssetCollection(album, options: fetchOptions) if let result = PHAsset.fetchAssetsInAssetCollection(album, options: fetchOptions) { result.enumerateObjectsUsingBlock { (object, idx, stop) in if let asset = object as? PHAsset { let imageSize = CGSize(width: 79, height: 79) let imageContentMode: PHImageContentMode = .AspectFill switch idx { case 0: PHCachingImageManager.defaultManager().requestImageForAsset(asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in cell.firstImageView.image = result cell.secondImageView.image = result cell.thirdImageView.image = result } case 1: PHCachingImageManager.defaultManager().requestImageForAsset(asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in cell.secondImageView.image = result cell.thirdImageView.image = result } case 2: PHCachingImageManager.defaultManager().requestImageForAsset(asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in cell.thirdImageView.image = result } default: // Stop enumeration stop.initialize(true) } } } } } return cell } // MARK: AssetsDelegate func didUpdateAssets(sender: AnyObject, incrementalChange: Bool, insert: [NSIndexPath], delete: [NSIndexPath], change: [NSIndexPath]) { delegate?.didUpdateAssets(self, incrementalChange: incrementalChange, insert: insert, delete: delete, change: change) } // MARK: Selectable func selectObjectAtIndexPath(indexPath: NSIndexPath) { // Only 1 selection allowed, so clear old selection _assetsModel.removeSelections() // Selection new object _assetsModel.selectObjectAtIndexPath(indexPath) } func deselectObjectAtIndexPath(indexPath: NSIndexPath) { // No deselection allowed } func selectionCount() -> Int { return _assetsModel.selectionCount() } func selectedIndexPaths() -> [NSIndexPath] { return _assetsModel.selectedIndexPaths() } func selections() -> [PHAssetCollection] { return _assetsModel.selections() } // MARK: PHPhotoLibraryChangeObserver func photoLibraryDidChange(changeInstance: PHChange!) { _assetsModel.photoLibraryDidChange(changeInstance) } }
mit
f601e118e5f819799f4b8784b738ce1d
42.291391
179
0.623069
5.857527
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/AugmentedAIRuntime/AugmentedAIRuntime_Shapes.swift
1
15790
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension AugmentedAIRuntime { // MARK: Enums public enum ContentClassifier: String, CustomStringConvertible, Codable { case freeofadultcontent = "FreeOfAdultContent" case freeofpersonallyidentifiableinformation = "FreeOfPersonallyIdentifiableInformation" public var description: String { return self.rawValue } } public enum HumanLoopStatus: String, CustomStringConvertible, Codable { case completed = "Completed" case failed = "Failed" case inprogress = "InProgress" case stopped = "Stopped" case stopping = "Stopping" public var description: String { return self.rawValue } } public enum SortOrder: String, CustomStringConvertible, Codable { case ascending = "Ascending" case descending = "Descending" public var description: String { return self.rawValue } } // MARK: Shapes public struct DeleteHumanLoopRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "humanLoopName", location: .uri(locationName: "HumanLoopName")) ] /// The name of the human loop that you want to delete. public let humanLoopName: String public init(humanLoopName: String) { self.humanLoopName = humanLoopName } public func validate(name: String) throws { try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, max: 63) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, min: 1) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, pattern: "^[a-z0-9](-*[a-z0-9])*$") } private enum CodingKeys: CodingKey {} } public struct DeleteHumanLoopResponse: AWSDecodableShape { public init() {} } public struct DescribeHumanLoopRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "humanLoopName", location: .uri(locationName: "HumanLoopName")) ] /// The name of the human loop that you want information about. public let humanLoopName: String public init(humanLoopName: String) { self.humanLoopName = humanLoopName } public func validate(name: String) throws { try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, max: 63) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, min: 1) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, pattern: "^[a-z0-9](-*[a-z0-9])*$") } private enum CodingKeys: CodingKey {} } public struct DescribeHumanLoopResponse: AWSDecodableShape { /// The creation time when Amazon Augmented AI created the human loop. public let creationTime: Date /// A failure code that identifies the type of failure. public let failureCode: String? /// The reason why a human loop failed. The failure reason is returned when the status of the human loop is Failed. public let failureReason: String? /// The Amazon Resource Name (ARN) of the flow definition. public let flowDefinitionArn: String /// The Amazon Resource Name (ARN) of the human loop. public let humanLoopArn: String /// The name of the human loop. The name must be lowercase, unique within the Region in your account, and can have up to 63 characters. Valid characters: a-z, 0-9, and - (hyphen). public let humanLoopName: String /// An object that contains information about the output of the human loop. public let humanLoopOutput: HumanLoopOutput? /// The status of the human loop. public let humanLoopStatus: HumanLoopStatus public init(creationTime: Date, failureCode: String? = nil, failureReason: String? = nil, flowDefinitionArn: String, humanLoopArn: String, humanLoopName: String, humanLoopOutput: HumanLoopOutput? = nil, humanLoopStatus: HumanLoopStatus) { self.creationTime = creationTime self.failureCode = failureCode self.failureReason = failureReason self.flowDefinitionArn = flowDefinitionArn self.humanLoopArn = humanLoopArn self.humanLoopName = humanLoopName self.humanLoopOutput = humanLoopOutput self.humanLoopStatus = humanLoopStatus } private enum CodingKeys: String, CodingKey { case creationTime = "CreationTime" case failureCode = "FailureCode" case failureReason = "FailureReason" case flowDefinitionArn = "FlowDefinitionArn" case humanLoopArn = "HumanLoopArn" case humanLoopName = "HumanLoopName" case humanLoopOutput = "HumanLoopOutput" case humanLoopStatus = "HumanLoopStatus" } } public struct HumanLoopDataAttributes: AWSEncodableShape { /// Declares that your content is free of personally identifiable information or adult content. Amazon SageMaker can restrict the Amazon Mechanical Turk workers who can view your task based on this information. public let contentClassifiers: [ContentClassifier] public init(contentClassifiers: [ContentClassifier]) { self.contentClassifiers = contentClassifiers } public func validate(name: String) throws { try self.validate(self.contentClassifiers, name: "contentClassifiers", parent: name, max: 256) } private enum CodingKeys: String, CodingKey { case contentClassifiers = "ContentClassifiers" } } public struct HumanLoopInput: AWSEncodableShape { /// Serialized input from the human loop. The input must be a string representation of a file in JSON format. public let inputContent: String public init(inputContent: String) { self.inputContent = inputContent } public func validate(name: String) throws { try self.validate(self.inputContent, name: "inputContent", parent: name, max: 3_145_728) } private enum CodingKeys: String, CodingKey { case inputContent = "InputContent" } } public struct HumanLoopOutput: AWSDecodableShape { /// The location of the Amazon S3 object where Amazon Augmented AI stores your human loop output. public let outputS3Uri: String public init(outputS3Uri: String) { self.outputS3Uri = outputS3Uri } private enum CodingKeys: String, CodingKey { case outputS3Uri = "OutputS3Uri" } } public struct HumanLoopSummary: AWSDecodableShape { /// When Amazon Augmented AI created the human loop. public let creationTime: Date? /// The reason why the human loop failed. A failure reason is returned when the status of the human loop is Failed. public let failureReason: String? /// The Amazon Resource Name (ARN) of the flow definition used to configure the human loop. public let flowDefinitionArn: String? /// The name of the human loop. public let humanLoopName: String? /// The status of the human loop. public let humanLoopStatus: HumanLoopStatus? public init(creationTime: Date? = nil, failureReason: String? = nil, flowDefinitionArn: String? = nil, humanLoopName: String? = nil, humanLoopStatus: HumanLoopStatus? = nil) { self.creationTime = creationTime self.failureReason = failureReason self.flowDefinitionArn = flowDefinitionArn self.humanLoopName = humanLoopName self.humanLoopStatus = humanLoopStatus } private enum CodingKeys: String, CodingKey { case creationTime = "CreationTime" case failureReason = "FailureReason" case flowDefinitionArn = "FlowDefinitionArn" case humanLoopName = "HumanLoopName" case humanLoopStatus = "HumanLoopStatus" } } public struct ListHumanLoopsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "creationTimeAfter", location: .querystring(locationName: "CreationTimeAfter")), AWSMemberEncoding(label: "creationTimeBefore", location: .querystring(locationName: "CreationTimeBefore")), AWSMemberEncoding(label: "flowDefinitionArn", location: .querystring(locationName: "FlowDefinitionArn")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")), AWSMemberEncoding(label: "sortOrder", location: .querystring(locationName: "SortOrder")) ] /// (Optional) The timestamp of the date when you want the human loops to begin in ISO 8601 format. For example, 2020-02-24. public let creationTimeAfter: Date? /// (Optional) The timestamp of the date before which you want the human loops to begin in ISO 8601 format. For example, 2020-02-24. public let creationTimeBefore: Date? /// The Amazon Resource Name (ARN) of a flow definition. public let flowDefinitionArn: String /// The total number of items to return. If the total number of available items is more than the value specified in MaxResults, then a NextToken is returned in the output. You can use this token to display the next page of results. public let maxResults: Int? /// A token to display the next page of results. public let nextToken: String? /// Optional. The order for displaying results. Valid values: Ascending and Descending. public let sortOrder: SortOrder? public init(creationTimeAfter: Date? = nil, creationTimeBefore: Date? = nil, flowDefinitionArn: String, maxResults: Int? = nil, nextToken: String? = nil, sortOrder: SortOrder? = nil) { self.creationTimeAfter = creationTimeAfter self.creationTimeBefore = creationTimeBefore self.flowDefinitionArn = flowDefinitionArn self.maxResults = maxResults self.nextToken = nextToken self.sortOrder = sortOrder } public func validate(name: String) throws { try self.validate(self.flowDefinitionArn, name: "flowDefinitionArn", parent: name, max: 1024) try self.validate(self.flowDefinitionArn, name: "flowDefinitionArn", parent: name, pattern: "arn:aws[a-z\\-]*:sagemaker:[a-z0-9\\-]*:[0-9]{12}:flow-definition/.*") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: ".*") } private enum CodingKeys: CodingKey {} } public struct ListHumanLoopsResponse: AWSDecodableShape { /// An array of objects that contain information about the human loops. public let humanLoopSummaries: [HumanLoopSummary] /// A token to display the next page of results. public let nextToken: String? public init(humanLoopSummaries: [HumanLoopSummary], nextToken: String? = nil) { self.humanLoopSummaries = humanLoopSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case humanLoopSummaries = "HumanLoopSummaries" case nextToken = "NextToken" } } public struct StartHumanLoopRequest: AWSEncodableShape { /// Attributes of the specified data. Use DataAttributes to specify if your data is free of personally identifiable information and/or free of adult content. public let dataAttributes: HumanLoopDataAttributes? /// The Amazon Resource Name (ARN) of the flow definition associated with this human loop. public let flowDefinitionArn: String /// An object that contains information about the human loop. public let humanLoopInput: HumanLoopInput /// The name of the human loop. public let humanLoopName: String public init(dataAttributes: HumanLoopDataAttributes? = nil, flowDefinitionArn: String, humanLoopInput: HumanLoopInput, humanLoopName: String) { self.dataAttributes = dataAttributes self.flowDefinitionArn = flowDefinitionArn self.humanLoopInput = humanLoopInput self.humanLoopName = humanLoopName } public func validate(name: String) throws { try self.dataAttributes?.validate(name: "\(name).dataAttributes") try self.validate(self.flowDefinitionArn, name: "flowDefinitionArn", parent: name, max: 1024) try self.validate(self.flowDefinitionArn, name: "flowDefinitionArn", parent: name, pattern: "arn:aws[a-z\\-]*:sagemaker:[a-z0-9\\-]*:[0-9]{12}:flow-definition/.*") try self.humanLoopInput.validate(name: "\(name).humanLoopInput") try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, max: 63) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, min: 1) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, pattern: "^[a-z0-9](-*[a-z0-9])*$") } private enum CodingKeys: String, CodingKey { case dataAttributes = "DataAttributes" case flowDefinitionArn = "FlowDefinitionArn" case humanLoopInput = "HumanLoopInput" case humanLoopName = "HumanLoopName" } } public struct StartHumanLoopResponse: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the human loop. public let humanLoopArn: String? public init(humanLoopArn: String? = nil) { self.humanLoopArn = humanLoopArn } private enum CodingKeys: String, CodingKey { case humanLoopArn = "HumanLoopArn" } } public struct StopHumanLoopRequest: AWSEncodableShape { /// The name of the human loop that you want to stop. public let humanLoopName: String public init(humanLoopName: String) { self.humanLoopName = humanLoopName } public func validate(name: String) throws { try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, max: 63) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, min: 1) try self.validate(self.humanLoopName, name: "humanLoopName", parent: name, pattern: "^[a-z0-9](-*[a-z0-9])*$") } private enum CodingKeys: String, CodingKey { case humanLoopName = "HumanLoopName" } } public struct StopHumanLoopResponse: AWSDecodableShape { public init() {} } }
apache-2.0
135926a54e3cca836585093e185c5714
45.441176
246
0.657505
4.695213
false
false
false
false
jkolb/Shkadov
Shkadov/platform/Metal/MetalTexture.swift
1
5247
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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 Metal import MetalKit import Swiftish public final class MetalTextureOwner : TextureOwner { private unowned(unsafe) let device: MTLDevice private unowned(unsafe) let view: MTKView private var textures: [MTLTexture?] private var reclaimedHandles: [TextureHandle] public init(device: MTLDevice, view: MTKView) { self.device = device self.view = view self.textures = [] self.reclaimedHandles = [] textures.reserveCapacity(128) reclaimedHandles.reserveCapacity(16) } public func createTexture(descriptor: TextureDescriptor) -> TextureHandle { return storeTexture(device.makeTexture(descriptor: map(descriptor))) } public func borrowTexture(handle: TextureHandle) -> Texture { return MetalTexture(handle: handle, instance: self[handle]) } public func generateMipmaps(handles: [TextureHandle]) { } public func destroyTexture(handle: TextureHandle) { reclaimedHandles.append(handle) textures[handle.index] = nil } public func storeTexture(_ texture: MTLTexture) -> TextureHandle { if reclaimedHandles.count > 0 { let handle = reclaimedHandles.removeLast() textures[handle.index] = texture return handle } else { textures.append(texture) return TextureHandle(key: UInt16(textures.count)) } } internal subscript (handle: TextureHandle) -> MTLTexture { return textures[handle.index]! } private func map(_ descriptor: TextureDescriptor) -> MTLTextureDescriptor { let metalDescriptor = MTLTextureDescriptor() metalDescriptor.textureType = map(descriptor.textureType, sampleCount: descriptor.sampleCount) metalDescriptor.pixelFormat = MetalDataTypes.map(descriptor.pixelFormat) metalDescriptor.width = descriptor.width metalDescriptor.height = descriptor.height metalDescriptor.depth = descriptor.depth metalDescriptor.mipmapLevelCount = descriptor.mipmapLevelCount metalDescriptor.sampleCount = descriptor.sampleCount metalDescriptor.arrayLength = descriptor.arrayLength metalDescriptor.usage = map(descriptor.textureUsage) metalDescriptor.storageMode = MetalDataTypes.map(descriptor.storageMode) return metalDescriptor } private func map(_ textureType: TextureType, sampleCount: Int) -> MTLTextureType { switch textureType { case .type1D: return .type1D case .type2D: if sampleCount > 1 { return .type2DMultisample } else { return .type2D } case .type3D: return .type3D case .type1DArray: return .type1DArray case .type2DArray: return .type2DArray case .typeCube: return .typeCube case .typeCubeArray: return .typeCubeArray } } private func map(_ textureUsage: TextureUsage) -> MTLTextureUsage { var usage = MTLTextureUsage() if textureUsage.contains(.shaderRead) { usage.formUnion(.shaderRead) } if textureUsage.contains(.shaderWrite) { usage.formUnion(.shaderWrite) } if textureUsage.contains(.renderTarget) { usage.formUnion(.renderTarget) } return usage } } public struct MetalTexture : Texture { public let handle: TextureHandle public unowned(unsafe) let instance: MTLTexture public init(handle: TextureHandle, instance: MTLTexture) { self.handle = handle self.instance = instance } public func replace(region: Region3<Int>, mipmapLevel level: Int, slice: Int, bytes: UnsafeRawPointer, bytesPerRow: Int, bytesPerImage: Int) { instance.replace(region: MetalDataTypes.map(region), mipmapLevel: level, slice: slice, withBytes: bytes, bytesPerRow: bytesPerRow, bytesPerImage: bytesPerImage) } }
mit
53ebff98313a60f7244049d13aaf3cb6
34.693878
168
0.670669
4.89459
false
false
false
false
languageininteraction/VowelSpaceTravel
mobile/Vowel Space Travel iOS/Vowel Space Travel iOS/LoginViewController.swift
1
6545
// // LoginViewController.swift // Vowel Space Travel iOS // // Created by Wessel Stoop on 11/12/15. // Copyright © 2015 Radboud University. All rights reserved. // import Foundation import UIKit class LoginViewController: SubViewController, PassControlToSubControllerProtocol, UITextFieldDelegate { var screenWidth : CGFloat? var screenHeight : CGFloat? var registerViewController : RegisterViewController = RegisterViewController() var server : VSTServer! let textFieldWidth : CGFloat = 300 let textFieldHeight : CGFloat = 100 var emailTextField : UITextField = UITextField() var passwordTextField : UITextField = UITextField() var numberOfActiveTextFields : Int = 0 override func viewDidLoad() { super.viewDidLoad() //Remember the screen sizes self.screenWidth = self.view.frame.size.width self.screenHeight = self.view.frame.size.height //Show the background image let backgroundImageView = UIImageView(image: UIImage(named: "login_background")) backgroundImageView.frame = CGRect(x: 0,y: 0,width: self.screenWidth!,height: screenHeight!) self.view.addSubview(backgroundImageView) //Create the text fields let textFieldLeft : CGFloat = 360 let textFieldFirstRow : CGFloat = 190 let textFieldSecondRow : CGFloat = 336 self.emailTextField = self.createTextField(textFieldLeft, y: textFieldFirstRow, placeHolder: "Email address") self.passwordTextField = self.createTextField(textFieldLeft, y: textFieldSecondRow, placeHolder: "Password", hidden: true) let defaults = NSUserDefaults.standardUserDefaults() self.emailTextField.text = defaults.valueForKey("email") as? String self.emailTextField.keyboardType = UIKeyboardType.EmailAddress self.view.addSubview(emailTextField) self.view.addSubview(passwordTextField) //Create start button let buttonWidth : CGFloat = 200 let buttonHeight : CGFloat = 70 let buttonTop : CGFloat = 170 let loginbutton = UIButton(frame: CGRectMake(0.5*(self.screenWidth!-buttonWidth),0.5*(self.screenHeight!-buttonHeight)+buttonTop,buttonWidth,buttonHeight)) loginbutton.setImage(UIImage(named: "loginbutton"), forState: UIControlState.Normal) loginbutton.addTarget(self, action: "loginButtonPressed", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(loginbutton) let loginbuttonText = UILabel(); loginbuttonText.frame = CGRectMake(0.5*(self.screenWidth!-buttonWidth)+15,0.5*(self.screenHeight!-buttonHeight-2)+buttonTop,buttonWidth,buttonHeight) loginbuttonText.textAlignment = NSTextAlignment.Center loginbuttonText.font = UIFont(name: "Muli",size:25) loginbuttonText.text = "Log in" loginbuttonText.textColor = UIColor(hue: 0.87, saturation: 0.3, brightness: 0.3, alpha: 1) self.view.addSubview(loginbuttonText) let registerTextTop : CGFloat = 290 let registerText = UILabel(); registerText.frame = CGRectMake(0.5*(self.screenWidth!-buttonWidth)+15,0.5*(self.screenHeight!-buttonHeight-2)+registerTextTop,buttonWidth,buttonHeight) registerText.textAlignment = NSTextAlignment.Center registerText.font = UIFont(name: "Muli",size:25) registerText.text = "Register" registerText.textColor = UIColor.whiteColor() self.view.addSubview(registerText) let registerButton = UIButton() registerButton.frame = CGRectMake(0.5*(self.screenWidth!-buttonWidth)+15,0.5*(self.screenHeight!-buttonHeight-2)+registerTextTop,buttonWidth,buttonHeight) // registerButton.backgroundColor = UIColor.redColor() registerButton.addTarget(self, action: "registerButtonPressed", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(registerButton) } func loginButtonPressed() { self.server!.logIn(self.emailTextField.text!, password: self.passwordTextField.text!) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setValue(self.emailTextField.text!,forKey: "email") self.superController!.subControllerFinished(self) } } func registerButtonPressed() { self.registerViewController.superController = self self.registerViewController.server = self.server self.view.addSubview(self.registerViewController.view) } func createTextField(x : CGFloat, y : CGFloat, placeHolder : String, hidden : Bool = false) -> UITextField { let textField : UITextField = UITextField() textField.frame = CGRect(x : x, y: y, width: self.textFieldWidth, height: self.textFieldHeight) textField.placeholder = placeHolder textField.textAlignment = NSTextAlignment.Center textField.font = UIFont(name: "Muli",size: 40) textField.textColor = UIColor.whiteColor() textField.delegate = self textField.secureTextEntry = hidden textField.autocorrectionType = UITextAutocorrectionType.No textField.autocapitalizationType = UITextAutocapitalizationType.None //textField.backgroundColor = UIColor.redColor() return textField } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { self.numberOfActiveTextFields++ self.moveWholeViewUp() return true } func textFieldShouldEndEditing(textField: UITextField) -> Bool { self.numberOfActiveTextFields-- if (self.numberOfActiveTextFields == 0) { self.moveWholeViewDown() } return true } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return true } func moveWholeViewUp() { UIView.animateWithDuration(1, animations: {self.view.frame.origin.y = -100}) } func moveWholeViewDown() { if self.view.frame.origin.y != 0 { UIView.animateWithDuration(1, animations: {self.view.frame.origin.y = 0}) } } func subControllerFinished(subController: SubViewController) { subController.view.removeFromSuperview() } }
gpl-2.0
82bf639f19522dce4dd96a05fdf9504a
36.83237
163
0.668399
5.065015
false
false
false
false
Sharelink/Bahamut
Bahamut/ShareService.swift
1
15330
// // ShareService.swift // Bahamut // // Created by AlexChow on 15/7/29. // Copyright (c) 2015年 GStudio. All rights reserved. // import Foundation //MARK: sortable share thing class ShareThingSortableObject: Sortable { override func getObjectUniqueIdName() -> String { return "shareId" } var shareId:String! override func isOrderedBefore(b: Sortable) -> Bool { let intervalA = self.compareValue as? NSNumber ?? NSDate().timeIntervalSince1970 let intervalB = b.compareValue as? NSNumber ?? NSDate().timeIntervalSince1970 return intervalA.doubleValue > intervalB.doubleValue } } extension ShareThing { func getSortableObject() -> ShareThingSortableObject { if let obj = PersistentManager.sharedInstance.getModel(ShareThingSortableObject.self, idValue: self.shareId) { return obj } let obj = ShareThingSortableObject() obj.shareId = self.shareId obj.compareValue = NSNumber(double: self.shareTimeOfDate.timeIntervalSince1970) return obj } } extension ShareUpdatedMessage { func isInvalidData() -> Bool { return shareId == nil || time == nil } } //MARK: ShareService let shareUpdatedNotifyRoute:ChicagoRoute = { let route = ChicagoRoute() route.ExtName = "NotificationCenter" route.CmdName = "UsrNewSTMsg" return route }() let NewShareMessages = "NewShareMessages" let UpdatedShares = "UpdatedShares" let NewSharePostedShareId = "NewSharePostedShareId" class ShareService: NSNotificationCenter,ServiceProtocol { static let newSharePosted = "newSharePosted" static let newSharePostFailed = "newSharePostFailed" static let startPostingShare = "startPostingShare" static let newShareMessagesUpdated = "newShareMessagesUpdated" static let shareUpdated = "shareUpdated" @objc static var ServiceName:String{return "Share Service"} @objc func userLoginInit(userId:String) { resetSortObjectList() ChicagoClient.sharedInstance.addChicagoObserver(shareUpdatedNotifyRoute, observer: self, selector: #selector(ShareService.newShareMessagesNotify(_:))) self.setServiceReady() self.getNewShareMessageFromServer() } func userLogout(userId: String) { newShareTime = nil oldShareTime = nil ChicagoClient.sharedInstance.removeObserver(self) } var allShareLoaded:Bool = false private(set) var sendingShareId = [String:String]() private var _newShareTime:NSDate! private var newShareTime:NSDate!{ get{ if _newShareTime == nil { _newShareTime = NSUserDefaults.standardUserDefaults().valueForKey("newShareTime") as? NSDate } return _newShareTime } set{ _newShareTime = newValue NSUserDefaults.standardUserDefaults().setValue(_newShareTime, forKey: "newShareTime") } } private var _oldShareTime:NSDate! private var oldShareTime:NSDate!{ get{ if _oldShareTime == nil { _oldShareTime = NSUserDefaults.standardUserDefaults().valueForKey("oldShareTime") as? NSDate } return _oldShareTime } set{ _oldShareTime = newValue NSUserDefaults.standardUserDefaults().setValue(_oldShareTime, forKey: "oldShareTime") } } private var shareThingSortObjectList:SortableObjectList<ShareThingSortableObject>! private func resetSortObjectList() { PersistentManager.sharedInstance.refreshCache(ShareThingSortableObject.self) let initList = PersistentManager.sharedInstance.getAllModelFromCache(ShareThingSortableObject.self) shareThingSortObjectList = SortableObjectList<ShareThingSortableObject>(initList: initList) } let lock:NSRecursiveLock = NSRecursiveLock() func setSortableObjects(objects:[ShareThingSortableObject]) { self.lock.lock() self.shareThingSortObjectList.setSortableItems(objects) self.lock.unlock() } //MARK: chicago client func newShareMessagesNotify(a:NSNotification) { self.getNewShareMessageFromServer() } //MARK: Get Shares From Server func getNewShareThings(callback:((newShares:[ShareThing]!)->Void)! = nil) { let req = GetShareThingsRequest() if let newestShareTime = self.newShareTime { req.beginTime = newestShareTime req.endTime = NSDate() req.page = -1 }else { req.endTime = NSDate() req.page = 0 req.pageCount = 7 } requestShare(req,callback:callback) } func getPreviousShare(callback:((previousShares:[ShareThing]!)->Void)! = nil) -> Bool { if oldShareTime == nil { return false } let req = GetShareThingsRequest() req.endTime = oldShareTime req.page = 0 req.pageCount = 7 return requestShare(req,callback: callback) } private func requestShare(req:GetShareThingsRequest,callback:((reqShares:[ShareThing]!)->Void)!) -> Bool { allShareLoaded = false let client = BahamutRFKit.sharedInstance.getBahamutClient() as! BahamutRFClient return client.execute(req) { (result:SLResult<[ShareThing]>) -> Void in var shares:[ShareThing]! = nil if result.isSuccess { if let newValues:[ShareThing] = result.returnObject { if newValues.count > 0 { let sortables = newValues.map{$0.getSortableObject()} ShareThing.saveObjectOfArray(newValues) self.updateNewShareAndOldShareTime(newValues) self.setSortableObjects(sortables) shares = newValues }else { self.allShareLoaded = true } } } if let handler = callback { handler(reqShares: shares) } } } private func updateNewShareAndOldShareTime(requestShares:[ShareThing]) { var oldestTime = NSDate() var newestTime = DateHelper.stringToDate("2015-07-07") for s in requestShares { let shareTime = s.shareTimeOfDate if shareTime.timeIntervalSince1970 > newestTime.timeIntervalSince1970 { newestTime = shareTime } if shareTime.timeIntervalSince1970 < oldestTime.timeIntervalSince1970 { oldestTime = shareTime } } if newShareTime == nil || newShareTime.timeIntervalSince1970 < newestTime.timeIntervalSince1970 { newShareTime = newestTime } if oldShareTime == nil || oldShareTime.timeIntervalSince1970 > oldestTime.timeIntervalSince1970 { oldShareTime = oldestTime } } func getSharesWithShareIds(shareIds:[String],callback:((updatedShares:[ShareThing]!)->Void)! = nil) -> [ShareThing] { //read from cache let oldValues = PersistentManager.sharedInstance.getModels(ShareThing.self, idValues: shareIds) //Access Network let req = GetShareOfShareIdsRequest() req.shareIds = shareIds BahamutRFKit.sharedInstance.getBahamutClient().execute(req) { (result:SLResult<[ShareThing]>) ->Void in var shares:[ShareThing]! = nil if result.isSuccess && result.returnObject != nil && result.returnObject.count > 0 { shares = result.returnObject! ShareThing.saveObjectOfArray(shares) let sortables = shares.map{$0.getSortableObject()} self.setSortableObjects(sortables) } if let update = callback { update(updatedShares: shares) } } return oldValues } //Get shares from local func getShareThings(startIndex:Int, pageNum:Int) -> [ShareThing] { return PersistentManager.sharedInstance.getModels(ShareThing.self, idValues: self.shareThingSortObjectList.getSortedObjects(startIndex, pageNum: pageNum).map{ $0.shareId }) } func getShareThing(shareId:String) -> ShareThing! { if let share = PersistentManager.sharedInstance.getModel(ShareThing.self, idValue: shareId) { return share } return nil } //MARK: Share Messages func getNewShareMessageFromServer() { let req = GetShareUpdatedMessageRequest() BahamutRFKit.sharedInstance.getBahamutClient().execute(req){ (result:SLResult<[ShareUpdatedMessage]>) ->Void in if var msgs = result.returnObject { msgs = msgs.filter{!$0.isInvalidData()} //AlamofireJsonToObject Issue:responseArray will invoke all completeHandler if msgs.count == 0 { return } self.postNotificationName(ShareService.newShareMessagesUpdated, object: self, userInfo: [NewShareMessages:msgs]) self.getSharesWithShareIds(msgs.map{$0.shareId }){ (reqShares) -> Void in if let shares = reqShares { var msgMap = [String:ShareUpdatedMessage]() for m in msgs{ msgMap[m.shareId] = m } func shareToSortable(share:ShareThing) -> ShareThingSortableObject { let obj = share.getSortableObject() let timeInterval = DateHelper.stringToDateTime(msgMap[share.shareId]?.time).timeIntervalSince1970 obj.compareValue = NSNumber(double: timeInterval) return obj } let sortables = shares.map{shareToSortable($0)} self.setSortableObjects(sortables) self.postNotificationName(ShareService.shareUpdated, object: self, userInfo: [UpdatedShares:shares]) self.clearShareMessageBox() } } } } } func clearShareMessageBox() { let req = ClearShareUpdatedMessageRequest() BahamutRFKit.sharedInstance.getBahamutClient().execute(req){ (result:SLResult<[ShareUpdatedMessage]>) ->Void in } } //MARK: Create Share func reshare(shareId:String,message:String!,tags:[SharelinkTheme],callback:(suc:Bool,shareId:String!)->Void) { let req = ReShareRequest() req.pShareId = shareId req.message = message req.tags = tags let client = BahamutRFKit.sharedInstance.getBahamutClient() client.execute(req) { (result:SLResult<ShareThing>) -> Void in if result.isSuccess { let newShare = result.returnObject newShare.saveModel() let sortableObject = newShare.getSortableObject() self.setSortableObjects([sortableObject]) callback(suc: true,shareId: newShare.shareId) }else { callback(suc: false,shareId: nil) } } } func postNewShare(newShare:ShareThing,tags:[SharelinkTheme],callback:(shareId:String!)->Void) { let req = AddNewShareThingRequest() req.shareContent = newShare.shareContent req.message = newShare.message req.tags = tags req.shareType = newShare.shareType let client = BahamutRFKit.sharedInstance.getBahamutClient() self.postNotificationName(ShareService.startPostingShare, object: nil) client.execute(req) { (result:SLResult<ShareThing>) -> Void in if result.isSuccess { newShare.shareId = result.returnObject.shareId newShare.saveModel() let sortableObject = newShare.getSortableObject() self.setSortableObjects([sortableObject]) self.sendingShareId[newShare.shareId] = "true" }else { self.postNotificationName(ShareService.newSharePostFailed, object: self, userInfo: nil) } callback(shareId: newShare.shareId) } } func postNewShareFinish(shareId:String,isCompleted:Bool,callback:(isSuc:Bool)->Void) { let req = FinishNewShareThingRequest() req.shareId = shareId req.taskSuccess = isCompleted let client = BahamutRFKit.sharedInstance.getBahamutClient() client.execute(req) { (result:SLResult<ShareThing>) -> Void in if let _ = result.returnObject { self.sendingShareId.removeValueForKey(shareId) self.postNotificationName(ShareService.newSharePosted, object: self, userInfo: [NewSharePostedShareId:shareId]) callback(isSuc: true) }else { self.postNotificationName(ShareService.newSharePostFailed, object: self, userInfo: [NewSharePostedShareId:shareId]) callback(isSuc: false) } } } //MARK: Vote func unVoteShareThing(shareThingModel:ShareThing,updateCallback:(()->Void)! = nil) { let myUserId = ServiceContainer.getService(UserService).myUserId let req = DeleteVoteRequest() req.shareId = shareThingModel.shareId BahamutRFKit.sharedInstance.getBahamutClient().execute(req){ (result:SLResult<BahamutObject>) -> Void in if result.isSuccess { shareThingModel.voteUsers.removeElement{$0 == myUserId} shareThingModel.saveModel() } if let update = updateCallback { update() } } } func voteShareThing(share:ShareThing,updateCallback:(()->Void)! = nil) { let myUserId = ServiceContainer.getService(UserService).myUserId let req = AddVoteRequest() req.shareId = share.shareId BahamutRFKit.sharedInstance.getBahamutClient().execute(req){ (result:SLResult<BahamutObject>) -> Void in if result.isSuccess { if share.voteUsers == nil{ share.voteUsers = [myUserId] }else { share.voteUsers.append(myUserId) } share.saveModel() let sortableObj = share.getSortableObject() sortableObj.compareValue = NSNumber(double: NSDate().timeIntervalSince1970) self.setSortableObjects([sortableObj]) } if let update = updateCallback { update() } } } }
mit
bce3807f086ec5d5ea66d6b7e4b53951
34.401848
180
0.59238
4.867577
false
false
false
false
corchwll/amos-ss15-proj5_ios
MobileTimeAccounting/UserInterface/Settings/Profile/ProfileTableViewController.swift
1
3114
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit class ProfileTableViewController: UITableViewController, EditProfileTableViewControllerDelegate { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var employeeIdLabel: UILabel! @IBOutlet weak var weeklyWorkingTimeLabel: UILabel! @IBOutlet weak var totalVacationTimeLabel: UILabel! /* iOS life-cycle function. Loads user profile. @methodtype Hook @pre Initial user profile is set @post User profile loaded */ override func viewDidLoad() { super.viewDidLoad() loadProfile() } /* iOS life-cycle function, called when segue is triggerd. Sets delegate and modal presentation style. @methodtype Hook @pre Must implement delegate protocel @post Delegate and modal presentation style is set */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let navigationViewController = segue.destinationViewController as! UINavigationController let editProfileTableViewController = navigationViewController.visibleViewController as! EditProfileTableViewController editProfileTableViewController.delegate = self if splitViewController!.collapsed { navigationViewController.modalPresentationStyle = UIModalPresentationStyle.FullScreen } else { navigationViewController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext } } /* Callback function when did finish editing profile. Reloads user profile. @methodtype Command @pre - @post User profile reloaded */ func didEditProfile() { loadProfile() } /* Functions is loading current user profile into ui. @methodtype Command @pre Valid user profile @post User profile was loaded into ui */ func loadProfile() { if let profile = profileDAO.getProfile() { nameLabel.text = profile.firstname + " " + profile.lastname employeeIdLabel.text = profile.employeeId weeklyWorkingTimeLabel.text = profile.weeklyWorkingTime.description totalVacationTimeLabel.text = profile.totalVacationTime.description } } }
agpl-3.0
d785ea1b956649857458c3834cbd28b6
30.77551
126
0.67341
5.734807
false
false
false
false
openhab/openhab.ios
openHAB/OpenHABNotification.swift
1
2144
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import Foundation class OpenHABNotification: NSObject { var message = "" var created: Date? var icon = "" var severity = "" init(message: String, created: Date?) { self.message = message self.created = created } init(dictionary: [String: Any]) { let propertyNames: Set = ["message", "icon", "severity"] super.init() let keyArray = dictionary.keys for key in keyArray { if key as String == "created" { let dateFormatter = DateFormatter() // 2015-09-15T13:39:19.938Z dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S'Z'" created = dateFormatter.date(from: dictionary[key] as? String ?? "") } else { if propertyNames.contains(key) { setValue(dictionary[key], forKey: key) } } } } } // Decode an instance of OpenHABNotification.CodingData rather than decoding a OpenHABNotificaiton value directly, // then convert that into a openHABNotification // Inspired by https://www.swiftbysundell.com/basics/codable?rq=codingdata extension OpenHABNotification { public struct CodingData: Decodable { let id: String let message: String let v: Int let created: Date? private enum CodingKeys: String, CodingKey { case id = "_id" case message case v = "__v" case created } } } // Convenience method to convert a decoded value into a proper OpenHABNotification instance extension OpenHABNotification.CodingData { var openHABNotification: OpenHABNotification { OpenHABNotification(message: message, created: created) } }
epl-1.0
f6590283e222699ebca6f3baf76dfa5e
30.529412
114
0.624534
4.448133
false
false
false
false
marinbenc/ReactiveWeatherExample
WhatsTheWeatherIn/WeatherAPIService.swift
1
1651
// // WeatherAPIService.swift // WhatsTheWeatherIn // // Created by Marin Benčević on 16/05/16. // Copyright © 2016 marinbenc. All rights reserved. // import Foundation import Alamofire import RxSwift import RxAlamofire import SwiftyJSON class WeatherAPIService { private struct Constants { static let APPID = "6a700a1e919dc96b0a98901c9f4bec47" static let baseURL = "http://api.openweathermap.org/" } enum ResourcePath: String { case Forecast = "data/2.5/forecast" case Icon = "img/w/" var path: String { return Constants.baseURL + rawValue } } enum APIError: ErrorType { case CannotParse } func search(withCity city: String)-> Observable<Weather> { let encodedCity = city.withPercentEncodedSpaces let params: [String: AnyObject] = [ "q": encodedCity, "units": "metric", "type": "like", "APPID": Constants.APPID ] return request(.GET, ResourcePath.Forecast.path, parameters: params, encoding: .URLEncodedInURL) .rx_JSON() .map(JSON.init) .flatMap { json -> Observable<Weather> in guard let weather = Weather(json: json) else { return Observable.error(APIError.CannotParse) } return Observable.just(weather) } } func weatherImage(forID imageID: String)-> Observable<NSData> { return request(.GET, ResourcePath.Icon.path + imageID + ".png").rx_data() } }
mit
6ee407c24b351deab1ec66d4643dec20
26.032787
104
0.572816
4.430108
false
false
false
false
chili-ios/CHICore
CHICore/Classes/EventBus/EventBus.swift
1
2219
// // Created by Igors Nemenonoks on 12/02/16. // Copyright (c) 2016 Chili. All rights reserved. // import Foundation public protocol PEventBus { var queue: OperationQueue { get } } public class EventBus: PEventBus { private(set) open var queue: OperationQueue init(queue: OperationQueue) { self.queue = queue } public func send(event: AnyObject) { self.queue.addOperation { NotificationCenter.default.post(name: NSNotification.Name(rawValue:String.className(event)), object: event) } } public func handleEvent<T: PubSubEvent>(target: EventBusObservable, handleBlock: @escaping ((T) -> Swift.Void)) { let notificationName = NSNotification.Name(rawValue: T.eventName()) _ = target.eventBusObserver.addObserver(forName: notificationName, object: nil, queue: self.queue) { (notification) in handleBlock((notification.object as! T)) } } } public class EventBusObserver { var objectProtocol: NSObjectProtocol? public init() { } open func addObserver(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Swift.Void) { self.objectProtocol = NotificationCenter.default.addObserver(forName: name, object: obj, queue: queue, using: block) } deinit { if let obj = self.objectProtocol { NotificationCenter.default.removeObserver(obj) } self.objectProtocol = nil } } public protocol EventBusObservable { var eventBusObserver: EventBusObserver { get set } func handleBGEvent<T>(handleBlock: @escaping ((T) -> Swift.Void)) where T : BGEventBusEvent func handleUIEvent<T>(handleBlock: @escaping ((T) -> Swift.Void)) where T : UIEventBusEvent } extension EventBusObservable { public func handleBGEvent<T>(handleBlock: @escaping ((T) -> Void)) where T : BGEventBusEvent { BGEventBus.sharedInstance.handleEvent(target: self, handleBlock: handleBlock) } public func handleUIEvent<T>(handleBlock: @escaping ((T) -> Swift.Void)) where T : UIEventBusEvent { UIEventBus.sharedInstance.handleEvent(target: self, handleBlock: handleBlock) } }
mit
7bee86b617e62ddf89fd52e24a407208
32.119403
158
0.688598
4.283784
false
false
false
false
jpush/aurora-imui
iOS/sample/sample/IMUIMessageCollectionView/Models/IMUIMessageModel.swift
1
4466
// // MessageModel.swift // IMUIChat // // Created by oshumini on 2017/2/24. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit public enum IMUIMessageType { case text case image case voice case video case location case custom } @objc public enum IMUIMessageStatus: UInt { // Sending message status case failed case sending case success // received message status case mediaDownloading case mediaDownloadFail } // //public enum IMUIMessageReceiveStatus { // case failed // case sending // case success //} public protocol IMUIMessageDataSource { func messageArray(with offset:NSNumber, limit:NSNumber) -> [IMUIMessageModelProtocol] } // MARK: - IMUIMessageModelProtocol /** * The class `IMUIMessageModel` is a concrete class for message model objects that represent a single user message * The message can be text \ voice \ image \ video \ message * It implements `IMUIMessageModelProtocol` protocal * */ open class IMUIMessageModel: NSObject, IMUIMessageModelProtocol { @objc public var duration: CGFloat open var msgId = { return "" }() open var messageStatus: IMUIMessageStatus open var fromUser: IMUIUserProtocol open var isOutGoing: Bool = true open var date: Date open var timeString: String { return date.parseDate } open var isNeedShowTime: Bool = false { didSet { // cellLayout?.isNeedShowTime = isNeedShowTime } } open var status: IMUIMessageStatus open var type: IMUIMessageType open var layout: IMUIMessageCellLayoutProtocal { return cellLayout! } open var cellLayout: IMUIMessageCellLayoutProtocal? open func text() -> String { return "" } open func mediaFilePath() -> String { return "" } open func calculateBubbleContentSize() -> CGSize { var bubbleContentSize: CGSize! switch type { case .image: do { var imgHeight:CGFloat? var imgWidth:CGFloat? let imageData = try Data(contentsOf: URL(fileURLWithPath: self.mediaFilePath())) let img:UIImage = UIImage(data: imageData)! if img.size.height >= img.size.width { imgHeight = CGFloat(135) imgWidth = img.size.width/img.size.height * imgHeight! imgWidth = (imgWidth! < 55) ? 55 : imgWidth } else { imgWidth = CGFloat(135) imgHeight = img.size.height/img.size.width * imgWidth! imgHeight = (imgHeight! < 55) ? 55 : imgHeight! } bubbleContentSize = CGSize(width: imgWidth!, height: imgHeight!) break } catch { print("load image file fail") } case .text: let textSize = self.text().sizeWithConstrainedWidth(with: IMUIMessageCellLayout.bubbleMaxWidth, font: UIFont.systemFont(ofSize: 18)) bubbleContentSize = textSize break case .voice: bubbleContentSize = CGSize(width: 80, height: 37) break case .video: bubbleContentSize = CGSize(width: 120, height: 160) break case .location: bubbleContentSize = CGSize(width: 200, height: 200) break default: break } return bubbleContentSize } public init(msgId: String, messageStatus: IMUIMessageStatus, fromUser: IMUIUserProtocol, isOutGoing: Bool, date: Date, status: IMUIMessageStatus, type: IMUIMessageType, cellLayout: IMUIMessageCellLayoutProtocal?) { self.msgId = msgId self.fromUser = fromUser self.isOutGoing = isOutGoing self.date = date self.status = status self.type = type self.messageStatus = messageStatus self.duration = 0.0 super.init() if let layout = cellLayout { self.cellLayout = layout } else { let bubbleSize = self.calculateBubbleContentSize() self.cellLayout = IMUIMessageCellLayout(isOutGoingMessage: isOutGoing, isNeedShowTime: isNeedShowTime, bubbleContentSize: bubbleSize) } } open var resizableBubbleImage: UIImage { var bubbleImg: UIImage? if isOutGoing { bubbleImg = UIImage.imuiImage(with: "outGoing_bubble") bubbleImg = bubbleImg?.resizableImage(withCapInsets: UIEdgeInsetsMake(24, 10, 9, 15), resizingMode: .tile) } else { bubbleImg = UIImage.imuiImage(with: "inComing_bubble") bubbleImg = bubbleImg?.resizableImage(withCapInsets: UIEdgeInsetsMake(24, 15, 9, 10), resizingMode: .tile) } return bubbleImg! } }
mit
ecac3174fa61228ad3c2fd7a2a536a9a
23.932961
216
0.668384
4.246432
false
false
false
false
HKMOpen/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleCell.swift
9
16675
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import UIKit; class AABubbleCell: UICollectionViewCell { // MARK: - // MARK: Private static vars static let bubbleContentTop: CGFloat = 6 static let bubbleContentBottom: CGFloat = 6 static let bubbleTop: CGFloat = 3 static let bubbleTopCompact: CGFloat = 1 static let bubbleBottom: CGFloat = 3 static let bubbleBottomCompact: CGFloat = 1 static let avatarPadding: CGFloat = 39 static let dateSize: CGFloat = 30 static let newMessageSize: CGFloat = 30 // Cached bubble images private static var cacnedOutTextBg:UIImage? = nil; private static var cacnedOutTextBgBorder:UIImage? = nil; private static var cacnedInTextBg:UIImage? = nil; private static var cacnedInTextBgBorder:UIImage? = nil; private static var cacnedOutTextCompactBg:UIImage? = nil; private static var cacnedOutTextCompactBgBorder:UIImage? = nil; private static var cacnedInTextCompactBg:UIImage? = nil; private static var cacnedInTextCompactBgBorder:UIImage? = nil; private static var cacnedOutMediaBg:UIImage? = nil; private static var cacnedOutMediaBgBorder:UIImage? = nil; private static var cacnedInMediaBg:UIImage? = nil; private static var cacnedInMediaBgBorder:UIImage? = nil; private static var cacnedServiceBg:UIImage? = nil; // MARK: - // MARK: Public vars // Views let mainView = UIView() let avatarView = AvatarView(frameSize: 39) let bubble = UIImageView() let bubbleBorder = UIImageView() private let dateText = UILabel() private let dateBg = UIImageView() private let newMessage = UILabel() // Layout var contentInsets : UIEdgeInsets = UIEdgeInsets() var bubbleInsets : UIEdgeInsets = UIEdgeInsets() var fullContentInsets : UIEdgeInsets { get { return UIEdgeInsets( top: contentInsets.top + bubbleInsets.top + (isShowDate ? AABubbleCell.dateSize : 0) + (isShowNewMessages ? AABubbleCell.newMessageSize : 0), left: contentInsets.left + bubbleInsets.left + (isGroup && !isOut ? AABubbleCell.avatarPadding : 0), bottom: contentInsets.bottom + bubbleInsets.bottom, right: contentInsets.right + bubbleInsets.right) } } var needLayout: Bool = true let groupContentInsetY = 20.0 let groupContentInsetX = 40.0 var bubbleVerticalSpacing: CGFloat = 6.0 let bubblePadding: CGFloat = 6; let bubbleMediaPadding: CGFloat = 10; // Binded data var peer: ACPeer! var controller: ConversationViewController! var isGroup: Bool = false var isFullSize: Bool! var bindedSetting: CellSetting? var bindedMessage: ACMessage? = nil var bubbleType:BubbleType? = nil var isOut: Bool = false var isShowDate: Bool = false var isShowNewMessages: Bool = false // MARK: - // MARK: Constructors init(frame: CGRect, isFullSize: Bool) { super.init(frame: frame) self.isFullSize = isFullSize dateBg.image = Imaging.roundedImage(MainAppTheme.bubbles.serviceBg, size: CGSizeMake(18, 18), radius: 9) dateText.font = UIFont(name: "HelveticaNeue-Medium", size: 12)! dateText.textColor = UIColor.whiteColor() dateText.contentMode = UIViewContentMode.Center dateText.textAlignment = NSTextAlignment.Center newMessage.font = UIFont(name: "HelveticaNeue-Medium", size: 14)! newMessage.textColor = UIColor.whiteColor() newMessage.contentMode = UIViewContentMode.Center newMessage.textAlignment = NSTextAlignment.Center newMessage.backgroundColor = UIColor.alphaBlack(0.3) newMessage.text = "New Messages" // bubble.userInteractionEnabled = true mainView.transform = CGAffineTransformMake(1, 0, 0, -1, 0, 0) mainView.addSubview(bubble) mainView.addSubview(bubbleBorder) mainView.addSubview(newMessage) mainView.addSubview(dateBg) mainView.addSubview(dateText) contentView.addSubview(mainView) avatarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "avatarDidTap")) avatarView.userInteractionEnabled = true backgroundColor = UIColor.clearColor() // Speed up animations self.layer.speed = 1.5 self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setConfig(peer: ACPeer, controller: ConversationViewController) { self.peer = peer self.controller = controller if (peer.getPeerType().ordinal() == jint(ACPeerType.GROUP.rawValue) && !isFullSize) { self.isGroup = true } } override func canBecomeFirstResponder() -> Bool { return false } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "delete:" { return true } return false } override func delete(sender: AnyObject?) { var rids = IOSLongArray(length: 1) rids.replaceLongAtIndex(0, withLong: bindedMessage!.getRid()) Actor.deleteMessagesWithPeer(self.peer, withRids: rids) } func avatarDidTap() { if bindedMessage != nil { controller.onBubbleAvatarTap(self.avatarView, uid: bindedMessage!.getSenderId()) } } func performBind(message: ACMessage, setting: CellSetting, layoutCache: LayoutCache) { self.clipsToBounds = false self.contentView.clipsToBounds = false var reuse = false if (bindedMessage != nil && bindedMessage?.getRid() == message.getRid()) { reuse = true } isOut = message.getSenderId() == Actor.myUid(); bindedMessage = message self.isShowNewMessages = setting.showNewMessages if (!reuse) { if (!isFullSize) { if (!isOut && isGroup) { if let user = Actor.getUserWithUid(message.getSenderId()) { let avatar: ACAvatar? = user.getAvatarModel().get() let name = user.getNameModel().get() avatarView.bind(name, id: user.getId(), avatar: avatar) } mainView.addSubview(avatarView) } else { avatarView.removeFromSuperview() } } } self.isShowDate = setting.showDate if (isShowDate) { self.dateText.text = Actor.getFormatter().formatDate(message.getDate()) } var layout = layoutCache.pick(message.getRid()) if (layout == nil) { layout = MessagesLayouting.buildLayout(message, layoutCache: layoutCache) layoutCache.cache(message.getRid(), layout: layout!) } self.bindedSetting = setting bind(message, reuse: reuse, cellLayout: layout!, setting: setting) if (!reuse) { needLayout = true super.setNeedsLayout() } } func bind(message: ACMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) { fatalError("bind(message:) has not been implemented") } func bindBubbleType(type: BubbleType, isCompact: Bool) { self.bubbleType = type // Update Bubble background images switch(type) { case BubbleType.TextIn: if (isCompact) { if (AABubbleCell.cacnedInTextCompactBg == nil) { AABubbleCell.cacnedInTextCompactBg = UIImage(named: "BubbleIncomingPartial")?.tintImage(MainAppTheme.bubbles.textBgIn) } if (AABubbleCell.cacnedInTextCompactBgBorder == nil) { AABubbleCell.cacnedInTextCompactBgBorder = UIImage(named: "BubbleIncomingPartialBorder")?.tintImage(MainAppTheme.bubbles.textBgInBorder) } bubble.image = AABubbleCell.cacnedInTextCompactBg bubbleBorder.image = AABubbleCell.cacnedInTextCompactBgBorder } else { if (AABubbleCell.cacnedInTextBg == nil) { AABubbleCell.cacnedInTextBg = UIImage(named: "BubbleIncomingFull")?.tintImage(MainAppTheme.bubbles.textBgIn) } if (AABubbleCell.cacnedInTextBgBorder == nil) { AABubbleCell.cacnedInTextBgBorder = UIImage(named: "BubbleIncomingFullBorder")?.tintImage(MainAppTheme.bubbles.textBgInBorder) } bubble.image = AABubbleCell.cacnedInTextBg bubbleBorder.image = AABubbleCell.cacnedInTextBgBorder } break case BubbleType.TextOut: if (isCompact) { if (AABubbleCell.cacnedOutTextCompactBg == nil) { AABubbleCell.cacnedOutTextCompactBg = UIImage(named: "BubbleOutgoingPartial")?.tintImage(MainAppTheme.bubbles.textBgOut) } if (AABubbleCell.cacnedOutTextCompactBgBorder == nil) { AABubbleCell.cacnedOutTextCompactBgBorder = UIImage(named: "BubbleOutgoingPartialBorder")?.tintImage(MainAppTheme.bubbles.textBgOutBorder) } bubble.image = AABubbleCell.cacnedOutTextCompactBg! bubbleBorder.image = AABubbleCell.cacnedOutTextCompactBgBorder! } else { if (AABubbleCell.cacnedOutTextBg == nil) { AABubbleCell.cacnedOutTextBg = UIImage(named: "BubbleOutgoingFull")?.tintImage(MainAppTheme.bubbles.textBgOut) } if (AABubbleCell.cacnedOutTextBgBorder == nil) { AABubbleCell.cacnedOutTextBgBorder = UIImage(named: "BubbleOutgoingFullBorder")?.tintImage(MainAppTheme.bubbles.textBgOutBorder) } bubble.image = AABubbleCell.cacnedOutTextBg! bubbleBorder.image = AABubbleCell.cacnedOutTextBgBorder! } break case BubbleType.MediaIn: if (AABubbleCell.cacnedOutMediaBg == nil) { AABubbleCell.cacnedOutMediaBg = UIImage(named: "BubbleIncomingPartial")?.tintImage(MainAppTheme.bubbles.mediaBgIn) } if (AABubbleCell.cacnedOutMediaBgBorder == nil) { AABubbleCell.cacnedOutMediaBgBorder = UIImage(named: "BubbleIncomingPartialBorder")?.tintImage(MainAppTheme.bubbles.mediaBgInBorder) } bubble.image = AABubbleCell.cacnedOutMediaBg! bubbleBorder.image = AABubbleCell.cacnedOutMediaBgBorder! break case BubbleType.MediaOut: if (AABubbleCell.cacnedOutMediaBg == nil) { AABubbleCell.cacnedOutMediaBg = UIImage(named: "BubbleOutgoingPartial")?.tintImage(MainAppTheme.bubbles.mediaBgOut) } if (AABubbleCell.cacnedOutMediaBgBorder == nil) { AABubbleCell.cacnedOutMediaBgBorder = UIImage(named: "BubbleOutgoingPartialBorder")?.tintImage(MainAppTheme.bubbles.mediaBgOutBorder) } bubble.image = AABubbleCell.cacnedOutMediaBg! bubbleBorder.image = AABubbleCell.cacnedOutMediaBgBorder! break case BubbleType.Service: if (AABubbleCell.cacnedServiceBg == nil) { AABubbleCell.cacnedServiceBg = Imaging.roundedImage(MainAppTheme.bubbles.serviceBg, size: CGSizeMake(18, 18), radius: 9) } bubble.image = AABubbleCell.cacnedServiceBg bubbleBorder.image = nil break default: break } } // MARK: - // MARK: Layout override func layoutSubviews() { super.layoutSubviews() mainView.frame = CGRectMake(0, 0, contentView.bounds.width, contentView.bounds.height) // if (!needLayout) { // return // } // needLayout = false UIView.performWithoutAnimation { () -> Void in let endPadding: CGFloat = 32 let startPadding: CGFloat = (!self.isOut && self.isGroup) ? AABubbleCell.avatarPadding : 0 var cellMaxWidth = self.contentView.frame.size.width - endPadding - startPadding self.layoutContent(cellMaxWidth, offsetX: startPadding) self.layoutAnchor() if (!self.isOut && self.isGroup && !self.isFullSize) { self.layoutAvatar() } } } func layoutAnchor() { if (isShowDate) { dateText.frame = CGRectMake(0, 0, 1000, 1000) dateText.sizeToFit() dateText.frame = CGRectMake( (self.contentView.frame.size.width-dateText.frame.width)/2, 8, dateText.frame.width, 18) dateBg.frame = CGRectMake(dateText.frame.minX - 8, dateText.frame.minY, dateText.frame.width + 16, 18) dateText.hidden = false dateBg.hidden = false } else { dateText.hidden = true dateBg.hidden = true } if (isShowNewMessages) { var top = CGFloat(0) if (isShowDate) { top += AABubbleCell.dateSize } newMessage.hidden = false newMessage.frame = CGRectMake(0, top + CGFloat(2), self.contentView.frame.width, AABubbleCell.newMessageSize - CGFloat(4)) } else { newMessage.hidden = true } } func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { } func layoutAvatar() { let avatarSize = CGFloat(self.avatarView.frameSize) avatarView.frame = CGRect(x: 5 + (isIPad ? 16 : 0), y: self.contentView.frame.size.height - avatarSize - 2 - bubbleInsets.bottom, width: avatarSize, height: avatarSize) } // Need to be called in child cells func layoutBubble(contentWidth: CGFloat, contentHeight: CGFloat) { let fullWidth = contentView.bounds.width let fullHeight = contentView.bounds.height let bubbleW = contentWidth + contentInsets.left + contentInsets.right let bubbleH = contentHeight + contentInsets.top + contentInsets.bottom var topOffset = CGFloat(0) if (isShowDate) { topOffset += AABubbleCell.dateSize } if (isShowNewMessages) { topOffset += AABubbleCell.newMessageSize } var bubbleFrame : CGRect! if (!isFullSize) { if (isOut) { bubbleFrame = CGRect( x: fullWidth - contentWidth - contentInsets.left - contentInsets.right - bubbleInsets.right, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } else { let padding : CGFloat = isGroup ? AABubbleCell.avatarPadding : 0 bubbleFrame = CGRect( x: bubbleInsets.left + padding, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } } else { bubbleFrame = CGRect( x: (fullWidth - contentWidth - contentInsets.left - contentInsets.right)/2, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } bubble.frame = bubbleFrame bubbleBorder.frame = bubbleFrame } func layoutBubble(frame: CGRect) { bubble.frame = frame bubbleBorder.frame = frame } override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes! { return layoutAttributes } } enum BubbleType { case TextOut case TextIn case MediaOut case MediaIn case Service }
mit
30f1171f29ed81b6b2e0c3fa6c7ee2f1
38.423168
176
0.595862
5.280241
false
false
false
false
lethianqt94/Swift-DropdownMenu-ParallaxTableView
ModuleDemo/ModuleDemo/Classes/Controllers/ParallaxScrollView/ParallaxScrollViewVC.swift
1
3647
// // ParallaxScrollViewVC.swift // ModuleDemo // // Created by Le Thi An on 3/2/16. // Copyright © 2016 Le Thi An. All rights reserved. // import UIKit let NAVBAR_CHANGE_POINT:CGFloat = 50 class ParallaxScrollViewVC: UIViewController { //MARK: Outlets & Variables @IBOutlet var header: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var consTopHeaderImgToHeaderView: NSLayoutConstraint! @IBOutlet weak var consBottomHeaderImgToHeaderView: NSLayoutConstraint! //MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.registerNib(UINib(nibName: "TextCell", bundle: nil), forCellReuseIdentifier: "TextCell") tableView.rowHeight = UITableViewAutomaticDimension let navbar:UINavigationBar! = self.navigationController?.navigationBar navbar.translucent = true self.automaticallyAdjustsScrollViewInsets = false navbar.lt_setBackgroundColor(UIColor.clearColor()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func scrollViewDidScroll(scrollView: UIScrollView) { let color = UIColor(red: 0/255.0, green: 175/255.0, blue: 240/255.0, alpha: 1) let offsetY = scrollView.contentOffset.y if offsetY > NAVBAR_CHANGE_POINT { let alpha:CGFloat = min(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64)) self.navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(alpha)) } else { self.navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(0)) } if scrollView.contentOffset.y >= 0 { // scrolling down header.clipsToBounds = true consBottomHeaderImgToHeaderView?.constant = -scrollView.contentOffset.y / 2 consTopHeaderImgToHeaderView?.constant = scrollView.contentOffset.y / 2 } else { // scrolling up consTopHeaderImgToHeaderView?.constant = scrollView.contentOffset.y header.clipsToBounds = false } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.navigationController?.navigationBar.barStyle = .BlackTranslucent self.scrollViewDidScroll(self.tableView) self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(true) self.navigationController?.navigationBar.barStyle = .Default self.navigationController!.navigationBar.lt_reset() } } //MARK: UITableViewDataSource methods extension ParallaxScrollViewVC: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TextCell") as! TextCell return cell } } //MARK: UITableViewDelegate methods extension ParallaxScrollViewVC: UITableViewDelegate { func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 160 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return header } }
mit
9f6ece1708805e23ae34124f79896e23
34.398058
112
0.688151
5.246043
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/FeatureHighlightStoreTests.swift
1
1805
import XCTest @testable import WordPress final class FeatureHighlightStoreTests: XCTestCase { private class MockUserDefaults: UserDefaults { var didDismiss = false var tooltipPresentCounter = 0 override func bool(forKey defaultName: String) -> Bool { didDismiss } override func set(_ value: Bool, forKey defaultName: String) { didDismiss = value } override func integer(forKey defaultName: String) -> Int { tooltipPresentCounter } override func set(_ integer: Int, forKey defaultName: String) { tooltipPresentCounter = integer } } func testShouldShowTooltipReturnsTrueWhenCounterIsBelow3() { var sut = FeatureHighlightStore(userStore: MockUserDefaults()) sut.didDismissTooltip = false sut.followConversationTooltipCounter = 2 XCTAssert(sut.shouldShowTooltip) } func testShouldShowTooltipReturnsFalseWhenCounterIs3() { var sut = FeatureHighlightStore(userStore: MockUserDefaults()) sut.didDismissTooltip = false sut.followConversationTooltipCounter = 3 XCTAssertFalse(sut.shouldShowTooltip) } func testShouldShowTooltipReturnsFalseWhenCounterIsBelow3DidDismissIsTrue() { var sut = FeatureHighlightStore(userStore: MockUserDefaults()) sut.didDismissTooltip = true sut.followConversationTooltipCounter = 0 XCTAssertFalse(sut.shouldShowTooltip) } func testShouldShowTooltipReturnsFalseWhenCounterIsAbove3DidDismissIsTrue() { var sut = FeatureHighlightStore(userStore: MockUserDefaults()) sut.didDismissTooltip = true sut.followConversationTooltipCounter = 7 XCTAssertFalse(sut.shouldShowTooltip) } }
gpl-2.0
47afb6a8549524f3d200733a087dfb61
30.666667
81
0.693629
5.340237
false
true
false
false
DianQK/RxExtensions
RxExtensions/IDHashable.swift
1
704
// // IDHashable.swift // RxExtensions // // Created by DianQK on 29/09/2016. // Copyright © 2016 T. All rights reserved. // import Foundation import RxDataSources public protocol IDHashable: Hashable { associatedtype ID: Hashable var id: ID { get } } extension IDHashable { public var hashValue: Int { return id.hashValue } public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.id == rhs.id } } extension Hashable { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.hashValue == rhs.hashValue } } extension IdentifiableType where Self: IDHashable { public var identity: Self.ID { return id } }
mit
27094621c7877af8441170b930330c6f
18
57
0.635846
3.84153
false
false
false
false
imxieyi/iosu
iosu/Scenes/GamePlayScene.swift
1
15647
// // GameScene.swift // iosu // // Created by xieyi on 2017/3/28. // Copyright © 2017年 xieyi. All rights reserved. // import SpriteKit import SpriteKitEasingSwift import GameplayKit class GamePlayScene: SKScene { var bmactions:[SKAction] = [] var actiontimepoints:[Int] = [] static var testBMIndex = 6 //The index of beatmap to test in the beatmaps var maxlayer:CGFloat=100000 var minlayer:CGFloat=0 var hitaudioHeader:String = "normal-" static var realwidth:Double=512 static var realheight:Double=384 static var scrwidth:Double=750 static var scrheight:Double=750 static var scrscale:Double=1 static var leftedge:Double=0 static var bottomedge:Double=0 static var bgdim:Double=0.2 static var effvolume:Float = 1.0 static var current:SKScene? fileprivate var actions:ActionSet? fileprivate var bgvactions:[SKAction]=[] fileprivate var bgvtimes:[Int]=[] open static var sliderball:SliderBall? var bm:Beatmap? override func sceneDidLoad() { GamePlayScene.current = self GamePlayScene.sliderball=SliderBall(scene: self) GamePlayScene.scrscale=Double(size.height)/480.0 GamePlayScene.realwidth=512.0*GamePlayScene.scrscale GamePlayScene.realheight=384.0*GamePlayScene.scrscale GamePlayScene.scrwidth=Double(size.width) GamePlayScene.scrheight=Double(size.height) GamePlayScene.bottomedge=(Double(size.height)-GamePlayScene.realheight)/2 GamePlayScene.leftedge=(Double(size.width)-GamePlayScene.realwidth)/2 let beatmaps=BeatmapScanner() debugPrint("test beatmap:\(beatmaps.beatmaps[GamePlayScene.testBMIndex])") debugPrint("Enter GamePlayScene, screen size: \(size.width)*\(size.height)") debugPrint("scrscale:\(GamePlayScene.scrscale)") debugPrint("realwidth:\(GamePlayScene.realwidth)") debugPrint("realheight:\(GamePlayScene.realheight)") debugPrint("bottomedge:\(GamePlayScene.bottomedge)") debugPrint("leftedge:\(GamePlayScene.leftedge)") do{ bm=try Beatmap(file: (beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [beatmaps.beatmaps[GamePlayScene.testBMIndex]])[0]) if (bm?.bgvideos.count)! > 0 && GameViewController.showvideo { debugPrint("got \(String(describing: bm?.bgvideos.count)) videos") for i in 0...(bm?.bgvideos.count)!-1 { let file=(beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [(bm?.bgvideos[i].file)!])[0] //var file=URL(fileURLWithPath: beatmaps.beatmapdirs[GamePlayScene.testBMIndex], isDirectory: true) //let file=beatmaps.bmdirurls[GamePlayScene.testBMIndex].appendingPathComponent(bm?.bgvideos[i]) if FileManager.default.fileExists(atPath: file) { bgvactions.append(BGVPlayer.setcontent(file)) bgvtimes.append((bm?.bgvideos[i].time)!) } else { debugPrint("video not found: \(file)") } } } else if bm?.bgimg != "" && !(StoryBoardScene.hasSB) { debugPrint("got bgimg:\(String(describing: bm?.bgimg))") let bgimg=UIImage(contentsOfFile: (beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [(bm?.bgimg)!])[0]) if bgimg==nil { debugPrint("Background image not found") } else { let bgnode=SKSpriteNode(texture: SKTexture(image: bgimg!)) let bgscale:CGFloat = max(size.width/(bgimg?.size.width)!,size.height/(bgimg?.size.height)!) bgnode.setScale(bgscale) bgnode.zPosition=0 bgnode.position=CGPoint(x: size.width/2, y: size.height/2) addChild(bgnode) } } let dimnode=SKShapeNode(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height)) dimnode.fillColor = .black dimnode.alpha=CGFloat(GamePlayScene.bgdim) dimnode.zPosition=1 addChild(dimnode) switch (bm?.sampleSet)! { case .auto: //Likely to be an error hitaudioHeader="normal-" break case .normal: hitaudioHeader="normal-" break case .soft: hitaudioHeader="soft-" break case .drum: hitaudioHeader="drum-" break } debugPrint("bgimg:\(String(describing: bm?.bgimg))") debugPrint("audio:\(String(describing: bm?.audiofile))") debugPrint("colors: \(String(describing: bm?.colors.count))") debugPrint("timingpoints: \(String(describing: bm?.timingpoints.count))") debugPrint("hitobjects: \(String(describing: bm?.hitobjects.count))") debugPrint("hitsoundset: \(hitaudioHeader)") bm?.audiofile=(beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [(bm?.audiofile)!])[0] as String if !FileManager.default.fileExists(atPath: (bm?.audiofile)!){ throw BeatmapError.audioFileNotExist } actions = ActionSet(beatmap: bm!, scene: self) actions?.prepare() BGMusicPlayer.instance.gameScene = self BGMusicPlayer.instance.gameEarliest = Int((actions?.nexttime())!) - Int((bm?.difficulty?.ARTime)!) BGMusicPlayer.instance.setfile((bm?.audiofile)!) if bgvtimes.count>0 { BGMusicPlayer.instance.videoEarliest = bgvtimes.first! } } catch BeatmapError.fileNotFound { debugPrint("ERROR:beatmap file not found") } catch BeatmapError.illegalFormat { debugPrint("ERROR:Illegal beatmap format") } catch BeatmapError.noAudioFile { debugPrint("ERROR:Audio file not found") } catch BeatmapError.audioFileNotExist { debugPrint("ERROR:Audio file does not exist") } catch BeatmapError.noColor { debugPrint("ERROR:Color not found") } catch BeatmapError.noHitObject{ debugPrint("ERROR:No hitobject found") } catch let error { debugPrint("ERROR:unknown error(\(error.localizedDescription))") } } static func conv(x:Double) -> Double { return leftedge+x*scrscale } static func conv(y:Double) -> Double { return scrheight-bottomedge-y*scrscale } static func conv(w:Double) -> Double { return w*scrscale } static func conv(h:Double) -> Double { return h*scrscale } func showresult(x:CGFloat,y:CGFloat,result:HitResult,audio:String) { var img:SKTexture switch result { case .s300: img = SkinBuffer.get("hit300")! break case .s100: img = SkinBuffer.get("hit100")! break case .s50: img = SkinBuffer.get("hit50")! break case .fail: img = SkinBuffer.get("hit0")! break } let node = SKSpriteNode(texture: img) let scale = CGFloat((bm?.difficulty?.AbsoluteCS)! / 128) node.setScale(scale) node.colorBlendFactor = 0 node.alpha = 0 node.position = CGPoint(x: x, y: y) node.zPosition = 100001 self.addChild(node) if result != .fail { self.run(.playSoundFileNamed(audio, atVolume: GamePlayScene.effvolume, waitForCompletion: true)) } else { self.run(.playSoundFileNamed("combobreak.mp3", atVolume: GamePlayScene.effvolume, waitForCompletion: true)) } node.run(.group([.sequence([.fadeIn(withDuration: 0.2),.fadeOut(withDuration: 0.6)]),.sequence([.scale(by: 1.5, duration: 0.1),.scale(to: scale, duration: 0.1)])])) } func hitsound2str(hitsound:HitSound) -> String { switch hitsound { case .normal: return "hitnormal.wav" case .clap: return "hitclap.wav" case .finish: return "hitfinish.wav" case .whistle: return "hitwhistle.wav" } } func distance(x1:CGFloat,y1:CGFloat,x2:CGFloat,y2:CGFloat) -> CGFloat { return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) } //Slider Status private var onslider = false private var hastouch = false private var lastpoint:CGPoint = .zero fileprivate func updateslider(_ time:Double) { let act = actions?.currentact() if act?.getobj().type != .slider { return } let sact = act as! SliderAction let sliderpoint = sact.getposition(time) if hastouch { if distance(x1: lastpoint.x, y1: lastpoint.y, x2: sliderpoint.x, y2: sliderpoint.y) <= CGFloat((bm?.difficulty?.AbsoluteCS)!) { onslider = true GamePlayScene.sliderball?.showfollowcircle() } else { GamePlayScene.sliderball?.hidefollowcircle() onslider = false } } else { onslider = false } switch sact.update(time, following: onslider) { case .failOnce: //self.run(.playSoundFileNamed("combobreak.mp3", waitForCompletion: false)) break case .failAll: showresult(x: sliderpoint.x, y: sliderpoint.y, result: .fail, audio: "") actions?.pointer += 1 hastouch = false break case .edgePass: self.run(.playSoundFileNamed(hitaudioHeader + hitsound2str(hitsound: sact.getobj().hitSound), atVolume: GamePlayScene.effvolume, waitForCompletion: true)) break case .end: if sact.failcount > 0 { showresult(x: sact.endx, y: sact.endy, result: .s100, audio: hitaudioHeader + hitsound2str(hitsound: sact.getobj().hitSound)) } else { showresult(x: sact.endx, y: sact.endy, result: .s300, audio: hitaudioHeader + hitsound2str(hitsound: sact.getobj().hitSound)) } GamePlayScene.sliderball?.hideall() actions?.pointer += 1 hastouch = false break case .tickPass: self.run(.playSoundFileNamed(hitaudioHeader + "slidertick.wav", atVolume: GamePlayScene.effvolume, waitForCompletion: true)) break case .failTick: self.run(.playSoundFileNamed("combobreak.mp3", atVolume: GamePlayScene.effvolume, waitForCompletion: true)) break default: break } } func touchDown(atPoint pos : CGPoint) { hastouch = true let act = actions?.currentact() if act != nil { let time = BGMusicPlayer.instance.getTime()*1000 switch (act?.getobj().type)! { case .circle: if (act?.gettime())! - time < (bm?.difficulty?.ARTime)! { let circle = act?.getobj() as! HitCircle if distance(x1: pos.x, y1: pos.y, x2: CGFloat(circle.x), y2: CGFloat(circle.y)) <= CGFloat((bm?.difficulty?.AbsoluteCS)!) { //debugPrint("time:\(time) required:\(act?.gettime())") let result = (act as! CircleAction).judge(time) showresult(x: CGFloat(circle.x), y: CGFloat(circle.y), result: result, audio: hitaudioHeader + hitsound2str(hitsound: circle.hitSound)) } } hastouch = false break case .slider: lastpoint = pos updateslider(time) break default: break } } } func touchMoved(toPoint pos : CGPoint) { let act = actions?.currentact() if act == nil { return } if (act?.getobj().type)! == .slider { lastpoint = pos updateslider(BGMusicPlayer.instance.getTime()*1000) } } func touchUp(atPoint pos : CGPoint) { hastouch = false GamePlayScene.sliderball?.hidefollowcircle() let act = actions?.currentact() if act == nil { return } updateslider(BGMusicPlayer.instance.getTime()*1000) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } var bgvindex = 0 var firstrun=true func destroyNode(_ node: SKNode) { for child in node.children { destroyNode(child) } node.removeAllActions() node.removeAllChildren() node.removeFromParent() } override func update(_ currentTime: TimeInterval) { // Called before each frame is rendered if(firstrun){ firstrun=false GamePlayScene.sliderball?.initialize(CGFloat((bm?.difficulty?.AbsoluteCS)!)) } if BGMusicPlayer.instance.state == .stopped { destroyNode(self) bm?.hitobjects.removeAll() bm = nil actions?.destroy() actions = nil SkinBuffer.clean() } var mtime=BGMusicPlayer.instance.getTime()*1000 if self.bgvindex < self.bgvactions.count { if self.bgvtimes[self.bgvindex] - Int(mtime) < 1000 { var offset=self.bgvtimes[self.bgvindex] - Int(mtime) if offset<0 { offset=0 } debugPrint("push bgvideo \(self.bgvindex) with offset \(offset)") self.run(SKAction.group([self.bgvactions[self.bgvindex],SKAction.sequence([SKAction.wait(forDuration: Double(offset)/1000),BGVPlayer.play()])])) self.bgvindex+=1 } } if BGMusicPlayer.instance.state == .stopped { return } mtime=BGMusicPlayer.instance.getTime()*1000 let act = self.actions?.currentact() if act != nil { if act?.getobj().type == .slider { self.updateslider(mtime) } } if let bm = self.bm, let actions = self.actions { var offset = actions.nexttime() - mtime - (bm.difficulty?.ARTime)! while actions.hasnext() && offset <= 1000 { if BGMusicPlayer.instance.state == .stopped { return } //debugPrint("mtime \(mtime) objtime \((actions?.nexttime())!) ar \((bm?.difficulty?.ARTime)!) offset \(offset)") actions.shownext(offset) offset = actions.nexttime() - mtime - (bm.difficulty?.ARTime)! } } } }
mit
6965db9bea4d7a10c1fbff9edadda622
39.319588
172
0.574214
4.263832
false
false
false
false
sschiau/swift-package-manager
Sources/Commands/SwiftTool.swift
1
33402
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import Build import PackageLoading import PackageGraph import PackageModel import POSIX import SourceControl import Utility import Workspace import SPMLibc import func Foundation.NSUserName import SPMLLBuild typealias Diagnostic = Basic.Diagnostic struct ChdirDeprecatedDiagnostic: DiagnosticData { static let id = DiagnosticID( type: AnyDiagnostic.self, name: "org.swift.diags.chdir-deprecated", defaultBehavior: .warning, description: { $0 <<< "'--chdir/-C' option is deprecated; use '--package-path' instead" } ) } /// Diagnostic error when the tool could not find a named product. struct ProductNotFoundDiagnostic: DiagnosticData { static let id = DiagnosticID( type: ProductNotFoundDiagnostic.self, name: "org.swift.diags.product-not-found", defaultBehavior: .error, description: { $0 <<< "no product named" <<< { "'\($0.productName)'" } } ) let productName: String } /// Diagnostic for non-existant working directory. struct WorkingDirNotFoundDiagnostic: DiagnosticData { static let id = DiagnosticID( type: WorkingDirNotFoundDiagnostic.self, name: "org.swift.diags.cwd-not-found", defaultBehavior: .error, description: { $0 <<< "couldn't determine the current working directory" } ) } /// Warning when someone tries to build an automatic type product using --product option. struct ProductIsAutomaticDiagnostic: DiagnosticData { static let id = DiagnosticID( type: ProductIsAutomaticDiagnostic.self, name: "org.swift.diags.product-is-automatic", defaultBehavior: .warning, description: { $0 <<< "'--product' cannot be used with the automatic product" <<< { "'\($0.productName)'." } <<< "Building the default target instead" } ) let productName: String } /// Diagnostic error when the tool could not find a named target. struct TargetNotFoundDiagnostic: DiagnosticData { static let id = DiagnosticID( type: TargetNotFoundDiagnostic.self, name: "org.swift.diags.target-not-found", defaultBehavior: .error, description: { $0 <<< "no target named" <<< { "'\($0.targetName)'" } } ) let targetName: String } private class ToolWorkspaceDelegate: WorkspaceDelegate { /// The stream to use for reporting progress. private let stdoutStream: ThreadSafeOutputByteStream init(_ stdoutStream: OutputByteStream) { // FIXME: Implement a class convenience initializer that does this once they are supported // https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924 self.stdoutStream = stdoutStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(stdoutStream) } func packageGraphWillLoad( currentGraph: PackageGraph, dependencies: AnySequence<ManagedDependency>, missingURLs: Set<String> ) { } func fetchingWillBegin(repository: String) { stdoutStream <<< "Fetching \(repository)" stdoutStream <<< "\n" stdoutStream.flush() } func fetchingDidFinish(repository: String, diagnostic: Diagnostic?) { } func repositoryWillUpdate(_ repository: String) { stdoutStream <<< "Updating \(repository)" stdoutStream <<< "\n" stdoutStream.flush() } func repositoryDidUpdate(_ repository: String) { } func dependenciesUpToDate() { stdoutStream <<< "Everything is already up-to-date" stdoutStream <<< "\n" stdoutStream.flush() } func cloning(repository: String) { stdoutStream <<< "Cloning \(repository)" stdoutStream <<< "\n" stdoutStream.flush() } func checkingOut(repository: String, atReference reference: String, to path: AbsolutePath) { stdoutStream <<< "Resolving \(repository) at \(reference)" stdoutStream <<< "\n" stdoutStream.flush() } func removing(repository: String) { stdoutStream <<< "Removing \(repository)" stdoutStream <<< "\n" stdoutStream.flush() } func warning(message: String) { // FIXME: We should emit warnings through the diagnostic engine. stdoutStream <<< "warning: " <<< message stdoutStream <<< "\n" stdoutStream.flush() } func managedDependenciesDidUpdate(_ dependencies: AnySequence<ManagedDependency>) { } } protocol ToolName { static var toolName: String { get } } extension ToolName { static func otherToolNames() -> String { let allTools: [ToolName.Type] = [SwiftBuildTool.self, SwiftRunTool.self, SwiftPackageTool.self, SwiftTestTool.self] return allTools.filter({ $0 != self }).map({ $0.toolName }).joined(separator: ", ") } } /// Handler for the main DiagnosticsEngine used by the SwiftTool class. private final class DiagnosticsEngineHandler { /// The standard output stream. var stdoutStream = Basic.stdoutStream /// The default instance. static let `default` = DiagnosticsEngineHandler() private init() {} func diagnosticsHandler(_ diagnostic: Diagnostic) { print(diagnostic: diagnostic, stdoutStream: stderrStream) } } public class SwiftTool<Options: ToolOptions> { /// The original working directory. let originalWorkingDirectory: AbsolutePath /// The options of this tool. let options: Options /// Path to the root package directory, nil if manifest is not found. let packageRoot: AbsolutePath? /// Helper function to get package root or throw error if it is not found. func getPackageRoot() throws -> AbsolutePath { guard let packageRoot = packageRoot else { throw Error.rootManifestFileNotFound } return packageRoot } /// Get the current workspace root object. func getWorkspaceRoot() throws -> PackageGraphRootInput { return try PackageGraphRootInput(packages: [getPackageRoot()]) } /// Path to the build directory. let buildPath: AbsolutePath /// Reference to the argument parser. let parser: ArgumentParser /// The process set to hold the launched processes. These will be terminated on any signal /// received by the swift tools. let processSet: ProcessSet /// The interrupt handler. let interruptHandler: InterruptHandler /// The diagnostics engine. let diagnostics: DiagnosticsEngine = DiagnosticsEngine( handlers: [DiagnosticsEngineHandler.default.diagnosticsHandler]) /// The llbuild Build System delegate. private(set) var buildDelegate: BuildDelegate /// The execution status of the tool. var executionStatus: ExecutionStatus = .success /// The stream to print standard output on. fileprivate var stdoutStream: OutputByteStream = Basic.stdoutStream /// If true, Redirects the stdout stream to stderr when invoking /// `swift-build-tool`. private var shouldRedirectStdoutToStderr = false /// Create an instance of this tool. /// /// - parameter args: The command line arguments to be passed to this tool. public init(toolName: String, usage: String, overview: String, args: [String], seeAlso: String? = nil) { // Capture the original working directory ASAP. guard let cwd = localFileSystem.currentWorkingDirectory else { diagnostics.emit(data: WorkingDirNotFoundDiagnostic()) SwiftTool.exit(with: .failure) } originalWorkingDirectory = cwd // Setup the build delegate. buildDelegate = BuildDelegate(diagnostics: diagnostics) // Create the parser. parser = ArgumentParser( commandName: "swift \(toolName)", usage: usage, overview: overview, seeAlso: seeAlso) // Create the binder. let binder = ArgumentBinder<Options>() // Bind the common options. binder.bindArray( parser.add( option: "-Xcc", kind: [String].self, strategy: .oneByOne, usage: "Pass flag through to all C compiler invocations"), parser.add( option: "-Xswiftc", kind: [String].self, strategy: .oneByOne, usage: "Pass flag through to all Swift compiler invocations"), parser.add( option: "-Xlinker", kind: [String].self, strategy: .oneByOne, usage: "Pass flag through to all linker invocations"), to: { $0.buildFlags.cCompilerFlags = $1 $0.buildFlags.swiftCompilerFlags = $2 $0.buildFlags.linkerFlags = $3 }) binder.bindArray( option: parser.add( option: "-Xcxx", kind: [String].self, strategy: .oneByOne, usage: "Pass flag through to all C++ compiler invocations"), to: { $0.buildFlags.cxxCompilerFlags = $1 }) binder.bind( option: parser.add( option: "--configuration", shortName: "-c", kind: BuildConfiguration.self, usage: "Build with configuration (debug|release) [default: debug]"), to: { $0.configuration = $1 }) binder.bind( option: parser.add( option: "--build-path", kind: PathArgument.self, usage: "Specify build/cache directory [default: ./.build]"), to: { $0.buildPath = $1.path }) binder.bind( option: parser.add( option: "--chdir", shortName: "-C", kind: PathArgument.self), to: { $0.chdir = $1.path }) binder.bind( option: parser.add( option: "--package-path", kind: PathArgument.self, usage: "Change working directory before any other operation"), to: { $0.packagePath = $1.path }) binder.bindArray( option: parser.add(option: "--sanitize", kind: [Sanitizer].self, strategy: .oneByOne, usage: "Turn on runtime checks for erroneous behavior"), to: { $0.sanitizers = EnabledSanitizers(Set($1)) }) binder.bind( option: parser.add(option: "--disable-prefetching", kind: Bool.self, usage: ""), to: { $0.shouldEnableResolverPrefetching = !$1 }) binder.bind( option: parser.add(option: "--skip-update", kind: Bool.self, usage: "Skip updating dependencies from their remote during a resolution"), to: { $0.skipDependencyUpdate = $1 }) binder.bind( option: parser.add(option: "--disable-sandbox", kind: Bool.self, usage: "Disable using the sandbox when executing subprocesses"), to: { $0.shouldDisableSandbox = $1 }) binder.bind( option: parser.add(option: "--disable-package-manifest-caching", kind: Bool.self, usage: "Disable caching Package.swift manifests"), to: { $0.shouldDisableManifestCaching = $1 }) binder.bind( option: parser.add(option: "--version", kind: Bool.self), to: { $0.shouldPrintVersion = $1 }) binder.bind( option: parser.add(option: "--destination", kind: PathArgument.self), to: { $0.customCompileDestination = $1.path }) // FIXME: We need to allow -vv type options for this. binder.bind( option: parser.add(option: "--verbose", shortName: "-v", kind: Bool.self, usage: "Increase verbosity of informational output"), to: { $0.verbosity = $1 ? 1 : 0 }) binder.bind( option: parser.add(option: "--no-static-swift-stdlib", kind: Bool.self, usage: "Do not link Swift stdlib statically [default]"), to: { $0.shouldLinkStaticSwiftStdlib = !$1 }) binder.bind( option: parser.add(option: "--static-swift-stdlib", kind: Bool.self, usage: "Link Swift stdlib statically"), to: { $0.shouldLinkStaticSwiftStdlib = $1 }) binder.bind( option: parser.add(option: "--enable-llbuild-library", kind: Bool.self, usage: "Enable building with the llbuild library"), to: { $0.shouldEnableLLBuildLibrary = $1 }) binder.bind( option: parser.add(option: "--force-resolved-versions", kind: Bool.self), to: { $0.forceResolvedVersions = $1 }) binder.bind( option: parser.add(option: "--disable-automatic-resolution", kind: Bool.self, usage: "Disable automatic resolution if Package.resolved file is out-of-date"), to: { $0.forceResolvedVersions = $1 }) binder.bind( option: parser.add(option: "--enable-index-store", kind: Bool.self, usage: "Enable indexing-while-building feature"), to: { if $1 { $0.indexStoreMode = .on } }) binder.bind( option: parser.add(option: "--disable-index-store", kind: Bool.self, usage: "Disable indexing-while-building feature"), to: { if $1 { $0.indexStoreMode = .off } }) // Let subclasses bind arguments. type(of: self).defineArguments(parser: parser, binder: binder) do { // Parse the result. let result = try parser.parse(args) var options = Options() try binder.fill(parseResult: result, into: &options) self.options = options // Honor package-path option is provided. if let packagePath = options.packagePath ?? options.chdir { // FIXME: This should be an API which takes AbsolutePath and maybe // should be moved to file system APIs with currentWorkingDirectory. try POSIX.chdir(packagePath.asString) } let processSet = ProcessSet() interruptHandler = try InterruptHandler { // Terminate all processes on receiving an interrupt signal. processSet.terminate() // Install the default signal handler. var action = sigaction() #if os(macOS) action.__sigaction_u.__sa_handler = SIG_DFL #else action.__sigaction_handler = unsafeBitCast( SIG_DFL, to: sigaction.__Unnamed_union___sigaction_handler.self) #endif sigaction(SIGINT, &action, nil) // Die with sigint. kill(getpid(), SIGINT) } self.processSet = processSet } catch { handle(error: error) SwiftTool.exit(with: .failure) } // Create local variables to use while finding build path to avoid capture self before init error. let customBuildPath = options.buildPath let packageRoot = findPackageRoot() self.packageRoot = packageRoot self.buildPath = getEnvBuildPath(workingDir: cwd) ?? customBuildPath ?? (packageRoot ?? cwd).appending(component: ".build") if options.chdir != nil { diagnostics.emit(data: ChdirDeprecatedDiagnostic()) } } class func defineArguments(parser: ArgumentParser, binder: ArgumentBinder<Options>) { fatalError("Must be implemented by subclasses") } func resolvedFilePath() throws -> AbsolutePath { return try getPackageRoot().appending(component: "Package.resolved") } func configFilePath() throws -> AbsolutePath { // Look for the override in the environment. if let envPath = Process.env["SWIFTPM_MIRROR_CONFIG"] { return try AbsolutePath(validating: envPath) } // Otherwise, use the default path. return try getPackageRoot().appending(components: ".swiftpm", "config") } func getSwiftPMConfig() throws -> SwiftPMConfig { return try _swiftpmConfig.dematerialize() } private lazy var _swiftpmConfig: Result<SwiftPMConfig, AnyError> = { return Result(anyError: { SwiftPMConfig(path: try configFilePath()) }) }() /// Holds the currently active workspace. /// /// It is not initialized in init() because for some of the commands like package init , usage etc, /// workspace is not needed, infact it would be an error to ask for the workspace object /// for package init because the Manifest file should *not* present. private var _workspace: Workspace? /// Returns the currently active workspace. func getActiveWorkspace() throws -> Workspace { if let workspace = _workspace { return workspace } let delegate = ToolWorkspaceDelegate(self.stdoutStream) let rootPackage = try getPackageRoot() let provider = GitRepositoryProvider(processSet: processSet) let workspace = Workspace( dataPath: buildPath, editablesPath: rootPackage.appending(component: "Packages"), pinsFile: try resolvedFilePath(), manifestLoader: try getManifestLoader(), toolsVersionLoader: ToolsVersionLoader(), delegate: delegate, config: try getSwiftPMConfig(), repositoryProvider: provider, isResolverPrefetchingEnabled: options.shouldEnableResolverPrefetching, skipUpdate: options.skipDependencyUpdate ) _workspace = workspace return workspace } /// Execute the tool. public func run() { do { // Setup the globals. verbosity = Verbosity(rawValue: options.verbosity) Process.verbose = verbosity != .concise // Call the implementation. try runImpl() if diagnostics.hasErrors { throw Diagnostics.fatalError } } catch { // Set execution status to failure in case of errors. executionStatus = .failure handle(error: error) } SwiftTool.exit(with: executionStatus) } /// Exit the tool with the given execution status. private static func exit(with status: ExecutionStatus) -> Never { switch status { case .success: POSIX.exit(0) case .failure: POSIX.exit(1) } } /// Run method implementation to be overridden by subclasses. func runImpl() throws { fatalError("Must be implemented by subclasses") } /// Start redirecting the standard output stream to the standard error stream. func redirectStdoutToStderr() { self.shouldRedirectStdoutToStderr = true self.stdoutStream = Basic.stderrStream DiagnosticsEngineHandler.default.stdoutStream = Basic.stderrStream buildDelegate.outputStream = Basic.stderrStream } /// Resolve the dependencies. func resolve() throws { let workspace = try getActiveWorkspace() let root = try getWorkspaceRoot() if options.forceResolvedVersions { workspace.resolveToResolvedVersion(root: root, diagnostics: diagnostics) } else { workspace.resolve(root: root, diagnostics: diagnostics) } // Throw if there were errors when loading the graph. // The actual errors will be printed before exiting. guard !diagnostics.hasErrors else { throw Diagnostics.fatalError } } /// Fetch and load the complete package graph. @discardableResult func loadPackageGraph( createREPLProduct: Bool = false ) throws -> PackageGraph { do { let workspace = try getActiveWorkspace() // Fetch and load the package graph. let graph = try workspace.loadPackageGraph( root: getWorkspaceRoot(), createREPLProduct: createREPLProduct, forceResolvedVersions: options.forceResolvedVersions, diagnostics: diagnostics ) // Throw if there were errors when loading the graph. // The actual errors will be printed before exiting. guard !diagnostics.hasErrors else { throw Diagnostics.fatalError } return graph } catch { throw error } } /// Returns the user toolchain to compile the actual product. func getToolchain() throws -> UserToolchain { return try _destinationToolchain.dematerialize() } func getManifestLoader() throws -> ManifestLoader { return try _manifestLoader.dematerialize() } func computeLLBuildTargetName(for subset: BuildSubset, buildParameters: BuildParameters) throws -> String? { switch subset { case .allExcludingTests: return LLBuildManifestGenerator.llbuildMainTargetName case .allIncludingTests: return LLBuildManifestGenerator.llbuildTestTargetName default: // FIXME: This is super unfortunate that we might need to load the package graph. return try subset.llbuildTargetName(for: loadPackageGraph(), diagnostics: diagnostics, config: buildParameters.configuration.dirname) } } func build(parameters: BuildParameters, subset: BuildSubset) throws { guard let llbuildTargetName = try computeLLBuildTargetName(for: subset, buildParameters: parameters) else { return } try runLLBuild(manifest: parameters.llbuildManifest, llbuildTarget: llbuildTargetName) } /// Build a subset of products and targets using swift-build-tool. func build(plan: BuildPlan, subset: BuildSubset) throws { guard let llbuildTargetName = subset.llbuildTargetName(for: plan.graph, diagnostics: diagnostics, config: plan.buildParameters.configuration.dirname) else { return } let yaml = plan.buildParameters.llbuildManifest // Generate the llbuild manifest. let client = options.shouldEnableLLBuildLibrary ? "basic" : "swift-build" let llbuild = LLBuildManifestGenerator(plan, client: client, resolvedFile: try resolvedFilePath()) try llbuild.generateManifest(at: yaml) // Run llbuild. try runLLBuild(manifest: yaml, llbuildTarget: llbuildTargetName) // Create backwards-compatibilty symlink to old build path. let oldBuildPath = buildPath.appending(component: options.configuration.dirname) if exists(oldBuildPath) { try localFileSystem.removeFileTree(oldBuildPath) } try createSymlink(oldBuildPath, pointingAt: plan.buildParameters.buildPath, relative: true) } func runLLBuild(manifest: AbsolutePath, llbuildTarget: String) throws { assert(localFileSystem.isFile(manifest), "llbuild manifest not present: \(manifest.asString)") if options.shouldEnableLLBuildLibrary { try runLLBuildAsLibrary(manifest: manifest, llbuildTarget: llbuildTarget) } else { try runLLBuildAsExecutable(manifest: manifest, llbuildTarget: llbuildTarget) } } func runLLBuildAsLibrary(manifest: AbsolutePath, llbuildTarget: String) throws { let databasePath = buildPath.appending(component: "build.db").asString let buildSystem = BuildSystem(buildFile: manifest.asString, databaseFile: databasePath, delegate: buildDelegate) buildDelegate.isVerbose = verbosity != .concise buildDelegate.onCommmandFailure = { [weak buildSystem] in buildSystem?.cancel() } guard buildSystem.build(target: llbuildTarget) else { throw Diagnostics.fatalError } } func runLLBuildAsExecutable(manifest: AbsolutePath, llbuildTarget: String) throws { // Create a temporary directory for the build process. let tempDirName = "org.swift.swiftpm.\(NSUserName())" let tempDir = try determineTempDirectory().appending(component: tempDirName) try localFileSystem.createDirectory(tempDir, recursive: true) // Run the swift-build-tool with the generated manifest. var args = [String]() #if os(macOS) // If enabled, use sandbox-exec on macOS. This provides some safety // against arbitrary code execution. We only allow the permissions which // are absolutely necessary for performing a build. if !options.shouldDisableSandbox { let allowedDirectories = [ tempDir, buildPath, BuildParameters.swiftpmTestCache ].map(resolveSymlinks) args += ["sandbox-exec", "-p", sandboxProfile(allowedDirectories: allowedDirectories)] } #endif args += [try getToolchain().llbuild.asString, "-f", manifest.asString, llbuildTarget] if verbosity != .concise { args.append("-v") } // Create the environment for llbuild. var env = Process.env // We override the temporary directory so tools assuming full access to // the tmp dir can create files here freely, provided they respect this // variable. env["TMPDIR"] = tempDir.asString // Run llbuild and print output on standard streams. let process = Process(arguments: args, environment: env, outputRedirection: shouldRedirectStdoutToStderr ? .collect : .none) try process.launch() try processSet.add(process) let result = try process.waitUntilExit() // Emit the output to the selected stream if we need to redirect the // stream. if shouldRedirectStdoutToStderr { self.stdoutStream <<< (try result.utf8stderrOutput()) self.stdoutStream <<< (try result.utf8Output()) self.stdoutStream.flush() } guard result.exitStatus == .terminated(code: 0) else { throw ProcessResult.Error.nonZeroExit(result) } } /// Return the build parameters. func buildParameters() throws -> BuildParameters { return try _buildParameters.dematerialize() } private lazy var _buildParameters: Result<BuildParameters, AnyError> = { return Result(anyError: { let toolchain = try self.getToolchain() let triple = try Triple(toolchain.destination.target) return BuildParameters( dataPath: buildPath.appending(component: toolchain.destination.target), configuration: options.configuration, toolchain: toolchain, destinationTriple: triple, flags: options.buildFlags, shouldLinkStaticSwiftStdlib: options.shouldLinkStaticSwiftStdlib, sanitizers: options.sanitizers, enableCodeCoverage: options.shouldEnableCodeCoverage, indexStoreMode: options.indexStoreMode ) }) }() /// Lazily compute the destination toolchain. private lazy var _destinationToolchain: Result<UserToolchain, AnyError> = { // Create custom toolchain if present. if let customDestination = self.options.customCompileDestination { return Result(anyError: { try UserToolchain(destination: Destination(fromFile: customDestination)) }) } // Otherwise use the host toolchain. return self._hostToolchain }() /// Lazily compute the host toolchain used to compile the package description. private lazy var _hostToolchain: Result<UserToolchain, AnyError> = { return Result(anyError: { try UserToolchain(destination: Destination.hostDestination( originalWorkingDirectory: self.originalWorkingDirectory)) }) }() private lazy var _manifestLoader: Result<ManifestLoader, AnyError> = { return Result(anyError: { try ManifestLoader( // Always use the host toolchain's resources for parsing manifest. manifestResources: self._hostToolchain.dematerialize().manifestResources, isManifestSandboxEnabled: !self.options.shouldDisableSandbox, cacheDir: self.options.shouldDisableManifestCaching ? nil : self.buildPath ) }) }() /// An enum indicating the execution status of run commands. enum ExecutionStatus { case success case failure } } /// An enum representing what subset of the package to build. enum BuildSubset { /// Represents the subset of all products and non-test targets. case allExcludingTests /// Represents the subset of all products and targets. case allIncludingTests /// Represents a specific product. case product(String) /// Represents a specific target. case target(String) } extension BuildSubset { /// Returns the name of the llbuild target that corresponds to the build subset. func llbuildTargetName(for graph: PackageGraph, diagnostics: DiagnosticsEngine, config: String) -> String? { switch self { case .allExcludingTests: return LLBuildManifestGenerator.llbuildMainTargetName case .allIncludingTests: return LLBuildManifestGenerator.llbuildTestTargetName case .product(let productName): guard let product = graph.allProducts.first(where: { $0.name == productName }) else { diagnostics.emit(data: ProductNotFoundDiagnostic(productName: productName)) return nil } // If the product is automatic, we build the main target because automatic products // do not produce a binary right now. if product.type == .library(.automatic) { diagnostics.emit(data: ProductIsAutomaticDiagnostic(productName: productName)) return LLBuildManifestGenerator.llbuildMainTargetName } return product.getLLBuildTargetName(config: config) case .target(let targetName): guard let target = graph.allTargets.first(where: { $0.name == targetName }) else { diagnostics.emit(data: TargetNotFoundDiagnostic(targetName: targetName)) return nil } return target.getLLBuildTargetName(config: config) } } } /// Returns path of the nearest directory containing the manifest file w.r.t /// current working directory. private func findPackageRoot() -> AbsolutePath? { guard var root = localFileSystem.currentWorkingDirectory else { return nil } // FIXME: It would be nice to move this to a generalized method which takes path and predicate and // finds the lowest path for which the predicate is true. while !isFile(root.appending(component: Manifest.filename)) { root = root.parentDirectory guard !root.isRoot else { return nil } } return root } /// Returns the build path from the environment, if present. private func getEnvBuildPath(workingDir: AbsolutePath) -> AbsolutePath? { // Don't rely on build path from env for SwiftPM's own tests. guard POSIX.getenv("IS_SWIFTPM_TEST") == nil else { return nil } guard let env = POSIX.getenv("SWIFTPM_BUILD_DIR") else { return nil } return AbsolutePath(env, relativeTo: workingDir) } /// Returns the sandbox profile to be used when parsing manifest on macOS. private func sandboxProfile(allowedDirectories: [AbsolutePath]) -> String { let stream = BufferedOutputByteStream() stream <<< "(version 1)" <<< "\n" // Deny everything by default. stream <<< "(deny default)" <<< "\n" // Import the system sandbox profile. stream <<< "(import \"system.sb\")" <<< "\n" // Allow reading all files. stream <<< "(allow file-read*)" <<< "\n" // These are required by the Swift compiler. stream <<< "(allow process*)" <<< "\n" stream <<< "(allow sysctl*)" <<< "\n" // Allow writing in temporary locations. stream <<< "(allow file-write*" <<< "\n" for directory in Platform.darwinCacheDirectories() { // For compiler module cache. stream <<< " (regex #\"^\(directory.asString)/org\\.llvm\\.clang.*\")" <<< "\n" // For archive tool. stream <<< " (regex #\"^\(directory.asString)/ar.*\")" <<< "\n" // For xcrun cache. stream <<< " (regex #\"^\(directory.asString)/xcrun.*\")" <<< "\n" // For autolink files. stream <<< " (regex #\"^\(directory.asString)/.*\\.(swift|c)-[0-9a-f]+\\.autolink\")" <<< "\n" } for directory in allowedDirectories { stream <<< " (subpath \"\(directory.asString)\")" <<< "\n" } stream <<< ")" <<< "\n" return stream.bytes.asString! } extension BuildConfiguration: StringEnumArgument { public static var completion: ShellCompletion = .values([ (debug.rawValue, "build with DEBUG configuration"), (release.rawValue, "build with RELEASE configuration"), ]) }
apache-2.0
772ad37f34e1fd3749a329b154849211
37.74942
164
0.631968
4.853531
false
false
false
false
godenzim/NetKit
NetKit/HTTPSession/HTTPRequestBuilder.swift
1
3435
// // HTTPRequestBuilder.swift // NetKit // // Created by Mike Godenzi on 27.09.14. // Copyright (c) 2014 Mike Godenzi. All rights reserved. // import Foundation public protocol RequestBuilder { func buildRequest(request : NSURLRequest, parameters : NSDictionary?) throws -> NSURLRequest } public class HTTPRequestBuilder : RequestBuilder { public var percentEncodeParameters = true public var stringEncoding = NSUTF8StringEncoding private let methodsWithParameterizedURL = ["GET", "HEAD", "DELETE"] public required init() {} public func buildRequest(request: NSURLRequest, parameters: NSDictionary?) throws -> NSURLRequest { guard let parameters = parameters as? [String:String] else { return request } let parameterString = formURLEncodedParameters(parameters, encode: false) let mutableRequest = request.mutableCopy() as! NSMutableURLRequest let method = request.HTTPMethod?.uppercaseString ?? "GET" if methodsWithParameterizedURL.contains(method) { let URL = request.URL let URLComponents = NSURLComponents(string: URL?.absoluteString ?? "") if percentEncodeParameters { URLComponents?.query = parameterString } else { URLComponents?.percentEncodedQuery = parameterString } mutableRequest.URL = URLComponents?.URL } else { let data = parameterString.dataUsingEncoding(stringEncoding, allowLossyConversion: false) mutableRequest.HTTPBody = data let charset : NSString = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(stringEncoding)) let contentType = "application/x-www-form-urlencoded; charset=\(charset)" mutableRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") } return mutableRequest.copy() as! NSURLRequest } } public class JSONRequestBuilder : HTTPRequestBuilder { public override func buildRequest(request: NSURLRequest, parameters: NSDictionary?) throws -> NSURLRequest { guard let parameters = parameters else { return request } let method = request.HTTPMethod?.uppercaseString ?? "GET" var result : NSURLRequest if !methodsWithParameterizedURL.contains(method) { let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted) let mutableRequest = request.mutableCopy() as! NSMutableURLRequest mutableRequest.HTTPBody = data let charset : NSString = CFStringConvertEncodingToIANACharSetName(CFStringBuiltInEncodings.UTF8.rawValue) let contentType = "application/json; charset=\(charset)" mutableRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") result = mutableRequest.copy() as! NSURLRequest } else { result = try super.buildRequest(request, parameters: parameters) } return result } } private func formURLEncodedParameters(parameters : [String:String], encode : Bool) -> String { var result = "" let keys = parameters.keys.sort { $0 < $1 } let count = keys.count if keys.count > 0 { for i in 0..<count { let key = encode ? keys[i].URLEncodedString() : keys[i] let value = encode ? parameters[key]!.URLEncodedString() : parameters[key]! result += "\(key)=\(value)" if i != count { result += "&" } } } return result } extension String { func URLEncodedString() -> String { return CFURLCreateStringByAddingPercentEscapes(nil, self as NSString, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) as NSString as String; } }
mit
9c0c9e8cb5c5eab4bfba7977c96005ba
33.009901
162
0.745852
4.409499
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/ShippingRulesViewModelTests.swift
1
42788
import Foundation @testable import KsApi @testable import Library import Prelude import ReactiveExtensions_TestHelpers private let shippingRules = [ ShippingRule.template |> ShippingRule.lens.location .~ .australia, ShippingRule.template |> ShippingRule.lens.location .~ .brooklyn, ShippingRule.template |> ShippingRule.lens.location .~ .canada, ShippingRule.template |> ShippingRule.lens.location .~ .greatBritain, ShippingRule.template |> ShippingRule.lens.location .~ .london, ShippingRule.template |> ShippingRule.lens.location .~ .losAngeles, ShippingRule.template |> ShippingRule.lens.location .~ .portland, ShippingRule.template |> ShippingRule.lens.location .~ .usa ] final class ShippingRulesViewModelTests: TestCase { private let vm: ShippingRulesViewModelType = ShippingRulesViewModel() private let deselectVisibleCells = TestObserver<Void, Never>() private let flashScrollIndicators = TestObserver<Void, Never>() private let notifyDelegateOfSelectedShippingRule = TestObserver<ShippingRule, Never>() private let reloadDataWithShippingRulesData = TestObserver<[ShippingRuleData], Never>() private let reloadDataWithShippingRulesReload = TestObserver<Bool, Never>() private let scrollToCellAtIndex = TestObserver<Int, Never>() private let selectCellAtIndex = TestObserver<Int, Never>() override func setUp() { super.setUp() self.vm.outputs.deselectVisibleCells.observe(self.deselectVisibleCells.observer) self.vm.outputs.flashScrollIndicators.observe(self.flashScrollIndicators.observer) self.vm.outputs.notifyDelegateOfSelectedShippingRule.observe( self.notifyDelegateOfSelectedShippingRule.observer ) self.vm.outputs.reloadDataWithShippingRules.map(first).observe( self.reloadDataWithShippingRulesData.observer ) self.vm.outputs.reloadDataWithShippingRules.map(second).observe( self.reloadDataWithShippingRulesReload.observer ) self.vm.outputs.scrollToCellAtIndex.observe(self.scrollToCellAtIndex.observer) self.vm.outputs.selectCellAtIndex.observe(self.selectCellAtIndex.observer) } func testFlashScrollIndicators() { self.vm.inputs.configureWith(.template, shippingRules: shippingRules, selectedShippingRule: .template) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidLayoutSubviews() self.flashScrollIndicators.assertValueCount(1) } func testDataIsSortedBasedOnLocalizedName() { let shippingRulesUnsorted = [ ShippingRule.template |> ShippingRule.lens.location .~ .usa, ShippingRule.template |> ShippingRule.lens.location .~ .portland, ShippingRule.template |> ShippingRule.lens.location .~ .losAngeles, ShippingRule.template |> ShippingRule.lens.location .~ .london, ShippingRule.template |> ShippingRule.lens.location .~ .greatBritain, ShippingRule.template |> ShippingRule.lens.location .~ .canada, ShippingRule.template |> ShippingRule.lens.location .~ .brooklyn, ShippingRule.template |> ShippingRule.lens.location .~ .australia ] let project = Project.template let selectedShippingRule = shippingRulesUnsorted[0] self.vm.inputs.configureWith( project, shippingRules: shippingRulesUnsorted, selectedShippingRule: selectedShippingRule ) self.vm.inputs.viewDidLoad() self.reloadDataWithShippingRulesData.assertValues( [ // Sorted list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[7] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRulesUnsorted[0] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true]) } /** This test checks whether the table scrolls to the selected shipping rule row 1) We load the list - Selected rule: Brooklyn - Scrolls to Brooklyn 2) We perform search for shipping rules locations starting with "Lo" prefix - Selected rule: Brooklyn - Does not scroll since Brooklyn is now not in the filtered list 3) We perform search for shipping rules locations starting with "B" prefix - Selected rule: Brooklyn - Scrolls to Brooklyn */ func testScrollToCellAtIndex() { let selectedShippingRule = shippingRules[1] self.vm.inputs.configureWith( .template, shippingRules: shippingRules, selectedShippingRule: selectedShippingRule ) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidLayoutSubviews() self.scrollToCellAtIndex.assertValues([1]) self.vm.inputs.searchTextDidChange("Lo") self.scheduler.advance(by: .milliseconds(100)) self.scrollToCellAtIndex.assertValues([1]) self.vm.inputs.searchTextDidChange("B") self.scheduler.advance(by: .milliseconds(100)) self.scrollToCellAtIndex.assertValues([1, 0]) } /** This test performs a search on shipping rules list 1) We load the list - Shows: Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA 2) We perform search for shipping rules locations starting with "Lo" prefix - Shows: London, Los Angeles 3) We perform another search for shipping rules locations starting with "a" prefix - Shows: Australia 4) We perform another search for shipping rules locations starting with "x" prefix - Shows: empty list 5) We clear the search query in order to show the original list - Shows: Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA 6) We perform another search for shipping rules locations starting with "C" prefix - Shows: Canada */ func testSearch() { let project = Project.template let selectedShippingRule = shippingRules[0] self.vm.inputs.configureWith( project, shippingRules: shippingRules, selectedShippingRule: selectedShippingRule ) self.vm.inputs.viewDidLoad() self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true]) // Search for shipping rules locations starting with "Lo" (should filter down to London, Los Angeles) self.vm.inputs.searchTextDidChange("Lo") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo" // [London, Los Angeles] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true]) // Search for shipping rules locations starting with "a" (should filter down to Australia) self.vm.inputs.searchTextDidChange("a") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo" // [London, Los Angeles] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "a" // [Australia] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, true]) self.vm.inputs.searchTextDidChange("x") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo" // [London, Los Angeles] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "a" // [Australia] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ) ], // Filtered list by "x" // Empty (no matches found) [ ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, true, true]) self.vm.inputs.searchTextDidChange("") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo" // [London, Los Angeles] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "a" // [Australia] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ) ], // Filtered list by "x" // Empty (no matches found) [ ], // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, true, true, true]) self.vm.inputs.searchTextDidChange("C") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo" // [London, Los Angeles] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "a" // [Australia] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ) ], // Filtered list by "x" // Empty (no matches found) [ ], // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "c" // [Canada] [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, true, true, true, true]) } /** This test performs a search on shipping rules list as well as selection of a shipping rule 1) We load the list - Shows: Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA - Selected rule: Australia 2) We perform search for shipping rules locations starting with "Lo" prefix - Shows: London, Los Angeles - Selected rule: Australia 3) We perform selection of Los Angeles - Shows: London, Los Angeles - Selected rule: Los Angeles 4) We perform search for shipping rules locations starting with "c" prefix - Shows: Canada - Selected rule: Los Angeles 5) We perform selection of Los Angeles - Shows: Canada - Selected rule: Canada */ func testSearchAndSelection() { let project = Project.template let selectedShippingRule = shippingRules[0] self.vm.inputs.configureWith( project, shippingRules: shippingRules, selectedShippingRule: selectedShippingRule ) self.vm.inputs.viewDidLoad() self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true]) // Search for shipping rules locations starting with "Lo" (should filter down to London, Los Angeles) self.vm.inputs.searchTextDidChange("Lo") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true]) self.vm.inputs.didSelectShippingRule(at: 1) let firstManuallySelectedShippingRule = shippingRules[5] self.deselectVisibleCells.assertValueCount(1) self.notifyDelegateOfSelectedShippingRule.assertValues([firstManuallySelectedShippingRule]) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Los Angeles [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[5] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, false]) self.selectCellAtIndex.assertValues([1]) // Search for shipping rules locations starting with "c" (should filter down to Canada) self.vm.inputs.searchTextDidChange("c") self.scheduler.advance(by: .milliseconds(100)) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Los Angeles [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "c": [Canada] // Selected rule: Los Angeles [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[2] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, false, true]) self.vm.inputs.didSelectShippingRule(at: 0) let secondManuallySelectedShippingRule = shippingRules[2] self.deselectVisibleCells.assertValueCount(2) self.notifyDelegateOfSelectedShippingRule.assertValues( [firstManuallySelectedShippingRule, secondManuallySelectedShippingRule] ) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "Lo": [London, Los Angeles] // Selected rule: Los Angeles [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[5] ) ], // Filtered list by "c": [Canada] // Selected rule: Los Angeles [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[2] ) ], // Filtered list by "c": [Canada] // Selected rule: Canada [ ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[2] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, true, false, true, false]) self.selectCellAtIndex.assertValues([1, 0]) } /** This test performs selection of a shipping rule 1) We load the list - Shows: Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA - Selected rule: Brooklyn 2) We perform selection of Portland - Shows: Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA - Selected rule: Portland 3) We perform selection of Great Britain - Shows: Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA - Selected rule: Great Britain */ func testSelection() { let project = Project.template let selectedShippingRule = shippingRules[1] self.vm.inputs.configureWith( project, shippingRules: shippingRules, selectedShippingRule: selectedShippingRule ) self.vm.inputs.viewDidLoad() self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Brooklyn [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true]) self.vm.inputs.didSelectShippingRule(at: 6) let firstManuallySelectedShippingRule = shippingRules[6] self.deselectVisibleCells.assertValueCount(1) self.notifyDelegateOfSelectedShippingRule.assertValues([firstManuallySelectedShippingRule]) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Australia [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Portland [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[7] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, false]) self.selectCellAtIndex.assertValues([6]) self.vm.inputs.didSelectShippingRule(at: 3) let secondManuallySelectedShippingRule = shippingRules[3] self.deselectVisibleCells.assertValueCount(2) self.notifyDelegateOfSelectedShippingRule.assertValues( [firstManuallySelectedShippingRule, secondManuallySelectedShippingRule] ) self.reloadDataWithShippingRulesData.assertValues( [ // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Great Britain [ ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: selectedShippingRule, shippingRule: shippingRules[7] ) ], // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Portland [ ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: firstManuallySelectedShippingRule, shippingRule: shippingRules[7] ) ], // Unfiltered list: [Australia, Brooklyn, Canada, Great Britain, London, Los Angeles, Portland, USA] // Selected rule: Great Britain [ ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[0] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[1] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[2] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[3] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[4] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[5] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[6] ), ShippingRuleData( selectedShippingRule: secondManuallySelectedShippingRule, shippingRule: shippingRules[7] ) ] ] ) self.reloadDataWithShippingRulesReload.assertValues([true, false, false]) self.selectCellAtIndex.assertValues([6, 3]) } }
apache-2.0
64b53390da1ef4e2cf077c75adf23f66
36.271777
108
0.64871
4.890057
false
false
false
false
ewhitley/CDAKit
CDAKit/health-data-standards/lib/import/ccda/ccda_patient_importer.swift
1
1675
// // ccda_patient_importer.swift // CDAKit // // Created by Eric Whitley on 1/25/16. // Copyright © 2016 Eric Whitley. All rights reserved. // import Foundation import Fuzi class CDAKImport_CCDA_PatientImporter: CDAKImport_C32_PatientImporter { override init(check_usable: Bool = true) { super.init(check_usable: check_usable) //NOTE: original Ruby does NOT call super section_importers["encounters"] = CDAKImport_CCDA_EncounterImporter() section_importers["procedures"] = CDAKImport_CCDA_ProcedureImporter() section_importers["results"] = CDAKImport_CCDA_ResultImporter() section_importers["vital_signs"] = CDAKImport_CCDA_VitalSignImporter() section_importers["medications"] = CDAKImport_CCDA_MedicationImporter() section_importers["conditions"] = CDAKImport_CCDA_ConditionImporter() //section_importers["social_history"] = CDAKImport_CDA_SectionImporter(entry_finder: CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.22.4.38' or cda:templateId/@root='2.16.840.1.113883.10.20.15.3.8']")) section_importers["social_history"] = CDAKImport_CCDA_SocialHistoryImporter() section_importers["care_goals"] = CDAKImport_CCDA_CareGoalImporter() section_importers["medical_equipment"] = CDAKImport_CCDA_MedicalEquipmentImporter() section_importers["allergies"] = CDAKImport_CCDA_AllergyImporter() section_importers["immunizations"] = CDAKImport_CCDA_ImmunizationImporter() section_importers["insurance_providers"] = CDAKImport_CCDA_InsuranceProviderImporter() } func parse_ccda(doc: XMLDocument) -> CDAKRecord { return parse_c32(doc) } }
mit
963cd4b8486b4c39e3bfed321d9e5c06
41.948718
263
0.744325
3.761798
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/Home(首页)/View/pageView/KYFocusView.swift
1
3307
// // KYFocusView.swift // KYHandMade // // Created by Kerain on 2017/6/13. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // import UIKit import SnapKit fileprivate let KYFocusCellId = "KYFocusCellId" class KYFocusView: UIView { lazy var collectionView : UICollectionView = { let layout = KYLayout() layout.itemSize = CGSize(width: SCREEN_WIDTH-20, height: SCREEN_HEIGHT*0.3) let collView = UICollectionView(frame: self.bounds, collectionViewLayout:layout) collView.dataSource = self collView.delegate = self collView.register(UINib(nibName:"KYFocusCell", bundle:nil), forCellWithReuseIdentifier: KYFocusCellId) return collView }() var focusModels = [KYFocusModel]() override init(frame: CGRect) { super.init(frame: frame) loadfocusData() addSubview(collectionView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func loadfocusData() { focusModels.removeAll() let focesModesDict : [Any] = [ ["iconStr":"001","contentImage":"01","nameStr":"我是小菜蛋对你点赞了","contenStr":"哈哈哈哈,下拉&点击有惊喜呀,要不要试一试呢"], ["iconStr":"002","contentImage":"02","nameStr":"我是小菜蛋关注了你","contenStr":"暗恋的女孩告诉我,如果我喜欢她就别说出来,因为愿望说出来就不灵了。这道理我懂!"], ["iconStr":"003","contentImage":"03","nameStr":"我是小菜蛋求你赏个赞呗","contenStr":"你现在不喜欢我,我告诉你,过了这个村,我在下一个村等你!!"], ["iconStr":"004","contentImage":"04","nameStr":"我是小菜蛋求你给个关注呗","contenStr":"我姓黄,又在秋天出生,所以我叫黄天出"], ["iconStr":"005","contentImage":"05","nameStr":"我是小菜蛋祝你发大财","contenStr":"哈哈哈,上拉&点击也有惊喜"] ] for focusDict in focesModesDict { let focusModel = KYFocusModel(dict:focusDict as! [String : AnyObject]) focusModels.append(focusModel) } collectionView.reloadData() } } extension KYFocusView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return focusModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let focuesCell = collectionView.dequeueReusableCell(withReuseIdentifier: KYFocusCellId, for: indexPath) as! KYFocusCell focuesCell.focusModel = focusModels[indexPath.item] return focuesCell } } extension KYFocusView : UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.item % 2 == 0 { KYPageRouter.openAuthorWebView(webURL: authorBlog) }else { KYPageRouter.openAuthorWebView(webURL: authorGithub) } } }
apache-2.0
c26430029e5ed55ea890406ecdfb7cb4
30.361702
127
0.641113
3.813713
false
false
false
false
nessBautista/iOSBackup
RxSwift_01/RxSwift_01/TableMultipleCells/ViewModel03.swift
1
3501
// // ViewModel03.swift // RxSwift_01 // // Created by Nestor Javier Hernandez Bautista on 6/3/17. // Copyright © 2017 Definity First. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources struct User { let followersCount: Int let followingCount: Int let screenName: String var profileImage: UIImage? var imgUrl = PublishSubject<String>() init(followersCount:Int, followingCount:Int, screenName: String) { self.followersCount = followersCount self.followingCount = followingCount self.screenName = screenName self.profileImage = nil } } class ViewModel03: NSObject { let disposeBag = DisposeBag() let scheduler = ConcurrentDispatchQueueScheduler(qos: .background) let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>() func getUsers() -> Observable<[SectionModel<String, User>]> { return Observable.create { (observer) -> Disposable in let users = [User(followersCount: 1005, followingCount: 495, screenName: "BalestraPatrick"), User(followersCount: 380, followingCount: 5, screenName: "RxSwiftLang"), User(followersCount: 36069, followingCount: 0, screenName: "SwiftLang")] print(users.count) for (i, user) in users.enumerated() { user.imgUrl.observeOn(self.scheduler) .map({ (str) -> UIImage in if let url = URL(string: (str)) { if let data = try? Data(contentsOf: url) { if let img = UIImage(data: data) { return img } } } return UIImage() }) .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] img in //print("Brought image at \(i)") var items = self?.dataSource.sectionModels[0].items items?[i].profileImage = img // self?.dataSource.value[i].name = "Done" // self?.dataSource.value[i].imgProfile = $0 }, onError: {error in print(error)}, onCompleted: {print("completed \(i)")}, onDisposed: {print("disposed \(i)")}) .addDisposableTo(self.disposeBag) } let section = [SectionModel(model: "", items: users)] observer.onNext(section) observer.onCompleted() return Disposables.create() } } // func getUsersAsVariable() -> Variable<[SectionModel<String, User>]> // { // let users = [User(followersCount: 1005, followingCount: 495, screenName: "BalestraPatrick"), // User(followersCount: 380, followingCount: 5, screenName: "RxSwiftLang"), // User(followersCount: 36069, followingCount: 0, screenName: "SwiftLang")] // // let section = Variable([SectionModel(model: "", items: [users])]) // // return section // // } }
cc0-1.0
43184ade79a5093cd6f4b6fd02436be2
35.842105
104
0.507143
5.279035
false
false
false
false
Trioser/Psychologist
Psychologist/PsychologistViewController.swift
1
1688
// // ViewController.swift // Psychologist // // Created by Richard E Millet on 2/22/15. // Copyright (c) 2015 remillet. All rights reserved. // import UIKit class PsychologistViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // // My code // @IBAction func nothingAction(sender: UIButton) { performSegueWithIdentifier("showNothing", sender: sender) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // // If our destination is a UINavigationController, get it's first visible view controller // var destinationViewController = segue.destinationViewController as? UIViewController if let navigationController = destinationViewController as? UINavigationController { destinationViewController = navigationController.visibleViewController } // // If our destination is a happiness controller, prepare it for the segue // if let happinessViewControl = destinationViewController as? HappinessViewController { if let identifier = segue.identifier { switch identifier { case "showSadDiag": happinessViewControl.happiness = 0 case "showHappyDiag": happinessViewControl.happiness = 100 case "showMehDiag": happinessViewControl.happiness = 50 case "showNothing": happinessViewControl.happiness = 55 default: happinessViewControl.happiness = 50 } } } else { println("WARNING! Could not segue to HappinessViewController.") } } }
apache-2.0
ba31b50c1dc6f69bf9a2938b625e01db
28.614035
91
0.747038
4.430446
false
false
false
false
iOS-Swift-Developers/Swift
RxSwift使用教程/3-RxSwift中Subjects使用/3-RxSwift中Subjects使用/ViewController.swift
1
2361
// // ViewController.swift // 3-RxSwift中Subjects使用 // // Created by 韩俊强 on 2017/8/2. // Copyright © 2017年 HaRi. All rights reserved. // import UIKit import RxSwift class ViewController: UIViewController { fileprivate lazy var bag : DisposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // 1.PulishSubject, 订阅者只能接受, 订阅之后发出的事情 let pulishSub = PublishSubject<String>() pulishSub.onNext("20") pulishSub.subscribe { (event : Event<String>) in print(event) }.addDisposableTo(bag) pulishSub.onNext("HaRi") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~") // 2.ReplaySubject, 订阅者可以接受订阅之前的事件&订阅之后的事件 let replaySub = ReplaySubject<String>.createUnbounded() replaySub.onNext("a") replaySub.onNext("b") replaySub.onNext("c") replaySub.subscribe { (event : Event<String>) in print(event) }.addDisposableTo(bag) replaySub.onNext("d") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~") // 3.BehaviorSubject, 订阅者可以接受, 订阅之前的最后一个事件 let behaviorSub = BehaviorSubject(value: "a") behaviorSub.subscribe { (event : Event<String>) in print(event) }.addDisposableTo(bag) behaviorSub.onNext("e") behaviorSub.onNext("f") behaviorSub.onNext("g") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~") // 4.Variable /* Variable 1> 相当于对BehaviorSubject进行装箱; 2> 如果想将Variable当成Obserable, 让订阅者进行订阅时, 需要asObserable转成Obserable; 3> 如果Variable打算发出事件, 直接修改对象的value即可; 4> 当事件结束时, Variable会自动发出completed事件 */ let variable = Variable("a") variable.value = "b" variable.asObservable().subscribe { (event : Event<String>) in print(event) }.addDisposableTo(bag) variable.value = "c" variable.value = "d" } }
mit
5869defa19ce3d11988d320d888d7b67
25.197531
77
0.520264
4.35729
false
false
false
false