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
bluesnap/bluesnap-ios
BluesnapSDK/BluesnapSDK/BSSubtotalUIView.swift
1
4648
// // SubtotalUIView.swift // BluesnapSDK // // Created by Shevie Chen on 14/08/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import UIKit @IBDesignable class BSSubtotalUIView: UIView { // MARK: public properties var subtotalAmount: Double = 10.0 var taxAmount: Double = 2.0 var currency: String = "USD" // MARK: private properties var shouldSetupConstraints = true var designMode = false var taxLabel : UILabel = UILabel() var taxValueLabel : UILabel = UILabel() var subtotalLabel : UILabel = UILabel() var subtotalValueLabel : UILabel = UILabel() // MARK: public functions public func setAmounts(subtotalAmount: Double, taxAmount: Double, currency: String) { self.subtotalAmount = subtotalAmount self.taxAmount = taxAmount self.currency = currency setElementAttributes() } /** Set the width/height/font-size of the view content; this code may be called many times. */ internal func resizeElements() { let halfWidth = (self.frame.width / 2).rounded() let halfHeight = (self.frame.height / 2).rounded() subtotalLabel.frame = CGRect(x: 0, y: 0, width: halfWidth, height: halfHeight) subtotalValueLabel.frame = CGRect(x: halfWidth, y: 0, width: halfWidth, height: halfHeight) taxLabel.frame = CGRect(x: 0, y: halfHeight, width: halfWidth, height: halfHeight) taxValueLabel.frame = CGRect(x: halfWidth, y: halfHeight, width: halfWidth, height: halfHeight) // for height 40 we want font size 12 let actualFieldFontSize = (self.frame.height * 12 / 40).rounded() if let fieldFont : UIFont = UIFont(name: subtotalLabel.font.fontName, size: actualFieldFontSize) { subtotalLabel.font = fieldFont subtotalValueLabel.font = fieldFont taxLabel.font = fieldFont taxValueLabel.font = fieldFont } } // MARK: UIView override functions // called at design time (StoryBoard) to init the component override init(frame: CGRect) { super.init(frame: frame) designMode = true buildElements() } // called at runtime to init the component required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) designMode = false buildElements() } override public func draw(_ rect: CGRect) { resizeElements() } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setElementAttributes() resizeElements() } override public func updateConstraints() { if (shouldSetupConstraints) { // AutoLayout constraints shouldSetupConstraints = false } super.updateConstraints() } // MARK: Internal/private functions /** Create the UI elements for the component This code needs to run only once (as opposed to sizes that may change). */ internal func buildElements() { self.addSubview(taxLabel) self.addSubview(taxValueLabel) self.addSubview(subtotalLabel) self.addSubview(subtotalValueLabel) setElementAttributes() } /** set the attributes that are not affected by resizing */ internal func setElementAttributes() { if taxAmount == 0 { self.isHidden = true return } subtotalLabel.text = BSLocalizedStrings.getString(BSLocalizedString.Label_Subtotal_Amount) taxLabel.text = BSLocalizedStrings.getString(BSLocalizedString.Label_Tax_Amount) let subTotalFormat = BSLocalizedStrings.getString(BSLocalizedString.Payment_subtotal_and_tax_format) let currencyCode = (currency == "USD" ? "$" : currency) subtotalValueLabel.text = String(format: subTotalFormat, currencyCode, CGFloat(self.subtotalAmount)) taxValueLabel.text = String(format: subTotalFormat, currencyCode, CGFloat(taxAmount)) subtotalLabel.textAlignment = .right subtotalValueLabel.textAlignment = .right taxLabel.textAlignment = .right taxValueLabel.textAlignment = .right //self.backgroundColor = UIColor.white subtotalLabel.textColor = UIColor.darkGray subtotalValueLabel.textColor = UIColor.darkGray taxLabel.textColor = UIColor.darkGray taxValueLabel.textColor = UIColor.darkGray } }
mit
66eec4c25079b73c5202e681ec96c607
30.398649
108
0.634603
4.825545
false
false
false
false
alexsosn/ConvNetSwift
ConvNetSwift/convnet-swift/Layers/LayersDotproducts/ConvolutionLayer.swift
1
9359
// // ConvolutionLayer.swift // ConvNetSwift // // Created by Alex on 2/17/17. // Copyright © 2017 OWL. All rights reserved. // // - ConvLayer does convolutions (so weight sharing spatially) // putting them together in one file because they are very similar import Foundation struct ConvLayerOpt: LayerInOptProtocol, LayerOptActivationProtocol { var layerType: LayerType = .Conv var filters: Int var sx: Int var sy: Int? var inDepth: Int = 0 var inSx: Int = 0 var inSy: Int = 0 var stride: Int = 1 var pad: Int = 0 var l1DecayMul: Double = 0.0 var l2DecayMul: Double = 1.0 var biasPref: Double = 0.0 var activation: ActivationType = .Undefined init (sx: Int, filters: Int, stride: Int, pad: Int, activation: ActivationType) { self.sx = sx self.filters = filters self.stride = stride self.pad = pad self.activation = activation } } class ConvLayer: InnerLayer { var outDepth: Int var sx: Int var sy: Int var inDepth: Int var inSx: Int var inSy: Int var stride: Int = 1 var pad: Int = 0 var l1DecayMul: Double = 0.0 var l2DecayMul: Double = 1.0 var outSx: Int var outSy: Int var layerType: LayerType var filters: [Vol] var biases: Vol var inAct: Vol? var outAct: Vol? init(opt: ConvLayerOpt) { // required outDepth = opt.filters sx = opt.sx // filter size. Should be odd if possible, it's cleaner. inDepth = opt.inDepth inSx = opt.inSx inSy = opt.inSy // optional sy = opt.sy ?? opt.sx stride = opt.stride // stride at which we apply filters to input volume pad = opt.pad // amount of 0 padding to add around borders of input volume l1DecayMul = opt.l1DecayMul l2DecayMul = opt.l2DecayMul // computed // note we are doing floor, so if the strided convolution of the filter doesnt fit into the input // volume exactly, the output volume will be trimmed and not contain the (incomplete) computed // final application. outSx = Int(floor(Double(inSx + pad * 2 - sx) / Double(stride + 1))) outSy = Int(floor(Double(inSy + pad * 2 - sy) / Double(stride + 1))) layerType = .Conv // initializations let bias = opt.biasPref filters = [] for _ in 0..<outDepth { filters.append(Vol(sx: sx, sy: sy, depth: inDepth)) } biases = Vol(sx: 1, sy: 1, depth: outDepth, c: bias) } func forward(_ V: inout Vol, isTraining: Bool) -> Vol { // optimized code by @mdda that achieves 2x speedup over previous version inAct = V let A = Vol(sx: outSx, sy: outSy, depth: outDepth, c: 0.0) let V_sx = V.sx let V_sy = V.sy let xy_stride = stride for d in 0 ..< outDepth { let f = filters[d] var x = -pad var y = -pad for ay in 0 ..< outSy { y+=xy_stride // xy_stride x = -pad for ax in 0 ..< outSx { // xy_stride x+=xy_stride // convolve centered at this particular location var a: Double = 0.0 for fy in 0 ..< f.sy { let oy = y+fy // coordinates in the original input array coordinates for fx in 0 ..< f.sx { let ox = x+fx if oy>=0 && oy<V_sy && ox>=0 && ox<V_sx { for fd in 0 ..< f.depth { // avoid function call overhead (x2) for efficiency, compromise modularity :( a += f.w[((f.sx * fy)+fx)*f.depth+fd] * V.w[((V_sx * oy)+ox)*V.depth+fd] } } } } a += biases.w[d] A.set(x: ax, y: ay, d: d, v: a) } } } outAct = A return outAct! } func backward() -> () { guard let V = inAct, let outAct = outAct else { return } V.dw = ArrayUtils.zerosDouble(V.w.count) // zero out gradient wrt bottom data, we're about to fill it let V_sx = V.sx let V_sy = V.sy let xy_stride = stride for d in 0 ..< outDepth { let f = filters[d] var x = -pad var y = -pad for ay in 0 ..< outSy { // xy_stride y+=xy_stride x = -pad for ax in 0 ..< outSx { // xy_stride x+=xy_stride // convolve centered at this particular location let chainGrad = outAct.getGrad(x: ax, y: ay, d: d) // gradient from above, from chain rule for fy in 0 ..< f.sy { let oy = y+fy // coordinates in the original input array coordinates for fx in 0 ..< f.sx { let ox = x+fx if oy>=0 && oy<V_sy && ox>=0 && ox<V_sx { for fd in 0 ..< f.depth { // avoid function call overhead (x2) for efficiency, compromise modularity :( let ix1 = ((V_sx * oy)+ox)*V.depth+fd let ix2 = ((f.sx * fy)+fx)*f.depth+fd f.dw[ix2] += V.w[ix1]*chainGrad V.dw[ix1] += f.w[ix2]*chainGrad } } } } biases.dw[d] += chainGrad } } filters[d] = f } // inAct = V } func getParamsAndGrads() -> [ParamsAndGrads] { var response: [ParamsAndGrads] = [] for i in 0 ..< outDepth { response.append(ParamsAndGrads( params: &filters[i].w, grads: &filters[i].dw, l1DecayMul: l1DecayMul, l2DecayMul: l2DecayMul)) } response.append(ParamsAndGrads( params: &biases.w, grads: &biases.dw, l1DecayMul: 0.0, l2DecayMul: 0.0)) return response } func assignParamsAndGrads(_ paramsAndGrads: [ParamsAndGrads]) { assert(filters.count + 1 == paramsAndGrads.count) for i in 0 ..< outDepth { filters[i].w = paramsAndGrads[i].params filters[i].dw = paramsAndGrads[i].grads } biases.w = paramsAndGrads.last!.params biases.dw = paramsAndGrads.last!.grads } func toJSON() -> [String: AnyObject] { var json: [String: AnyObject] = [:] json["sx"] = sx as AnyObject? // filter size in x, y dims json["sy"] = sy as AnyObject? json["stride"] = stride as AnyObject? json["inDepth"] = inDepth as AnyObject? json["outDepth"] = outDepth as AnyObject? json["outSx"] = outSx as AnyObject? json["outSy"] = outSy as AnyObject? json["layerType"] = layerType.rawValue as AnyObject? json["l1DecayMul"] = l1DecayMul as AnyObject? json["l2DecayMul"] = l2DecayMul as AnyObject? json["pad"] = pad as AnyObject? var jsonFilters: [[String: AnyObject]] = [] for i in 0 ..< filters.count { jsonFilters.append(filters[i].toJSON()) } json["filters"] = jsonFilters as AnyObject? json["biases"] = biases.toJSON() as AnyObject? return json } // // func fromJSON(json: [String: AnyObject]) -> () { // outDepth = json["outDepth"] as! Int // outSx = json["outSx"] as! Int // outSy = json["outSy"] as! Int // layerType = json["layerType"] as! String // sx = json["sx"] as! Int // filter size in x, y dims // sy = json["sy"] as! Int // stride = json["stride"] as! Int // inDepth = json["inDepth"] as! Int // depth of input volume // filters = [] //// l1DecayMul = json["l1DecayMul"] != nil ? json["l1DecayMul"] : 1.0 //// l2DecayMul = json["l2DecayMul"] != nil ? json["l2DecayMul"] : 1.0 //// pad = json["pad"] != nil ? json["pad"] : 0 // // var jsonFilters = json["filters"] as! [[String: AnyObject]] // for i in 0 ..< jsonFilters.count { // let v = Vol(0,0,0,0) // v.fromJSON(jsonFilters[i]) // filters.append(v) // } // // biases = Vol(0,0,0,0) // biases.fromJSON(json["biases"] as! [String: AnyObject]) // } }
mit
d4f7e5781e449a4f79f3f722f69b99e7
33.659259
113
0.462492
4.146212
false
false
false
false
lorentey/swift
benchmark/utils/TestsUtils.swift
13
11160
//===--- TestsUtils.swift -------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if os(Linux) import Glibc #elseif os(Windows) import MSVCRT #else import Darwin #endif public enum BenchmarkCategory : String { // Validation "micro" benchmarks test a specific operation or critical path that // we know is important to measure. case validation // subsystems to validate and their subcategories. case api, Array, String, Dictionary, Codable, Set, Data case sdk case runtime, refcount, metadata // Other general areas of compiled code validation. case abstraction, safetychecks, exceptions, bridging, concurrency, existential case exclusivity // Algorithms are "micro" that test some well-known algorithm in isolation: // sorting, searching, hashing, fibonaci, crypto, etc. case algorithm // Miniapplications are contrived to mimic some subset of application behavior // in a way that can be easily measured. They are larger than micro-benchmarks, // combining multiple APIs, data structures, or algorithms. This includes small // standardized benchmarks, pieces of real applications that have been extracted // into a benchmark, important functionality like JSON parsing, etc. case miniapplication // Regression benchmarks is a catch-all for less important "micro" // benchmarks. This could be a random piece of code that was attached to a bug // report. We want to make sure the optimizer as a whole continues to handle // this case, but don't know how applicable it is to general Swift performance // relative to the other micro-benchmarks. In particular, these aren't weighted // as highly as "validation" benchmarks and likely won't be the subject of // future investigation unless they significantly regress. case regression // Most benchmarks are assumed to be "stable" and will be regularly tracked at // each commit. A handful may be marked unstable if continually tracking them is // counterproductive. case unstable // CPU benchmarks represent instrinsic Swift performance. They are useful for // measuring a fully baked Swift implementation across different platforms and // hardware. The benchmark should also be reasonably applicable to real Swift // code--it should exercise a known performance critical area. Typically these // will be drawn from the validation benchmarks once the language and standard // library implementation of the benchmark meets a reasonable efficiency // baseline. A benchmark should only be tagged "cpubench" after a full // performance investigation of the benchmark has been completed to determine // that it is a good representation of future Swift performance. Benchmarks // should not be tagged if they make use of an API that we plan on // reimplementing or call into code paths that have known opportunities for // significant optimization. case cpubench // Explicit skip marker case skip } extension BenchmarkCategory : CustomStringConvertible { public var description: String { return self.rawValue } } extension BenchmarkCategory : Comparable { public static func < (lhs: BenchmarkCategory, rhs: BenchmarkCategory) -> Bool { return lhs.rawValue < rhs.rawValue } } public struct BenchmarkPlatformSet : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let darwin = BenchmarkPlatformSet(rawValue: 1 << 0) public static let linux = BenchmarkPlatformSet(rawValue: 1 << 1) public static var currentPlatform: BenchmarkPlatformSet { #if os(Linux) return .linux #else return .darwin #endif } public static var allPlatforms: BenchmarkPlatformSet { return [.darwin, .linux] } } public struct BenchmarkInfo { /// The name of the benchmark that should be displayed by the harness. public var name: String /// Shadow static variable for runFunction. private var _runFunction: (Int) -> () /// A function that invokes the specific benchmark routine. public var runFunction: ((Int) -> ())? { if !shouldRun { return nil } return _runFunction } /// A set of category tags that describe this benchmark. This is used by the /// harness to allow for easy slicing of the set of benchmarks along tag /// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc. public var tags: Set<BenchmarkCategory> /// The platforms that this benchmark supports. This is an OptionSet. private var unsupportedPlatforms: BenchmarkPlatformSet /// Shadow variable for setUpFunction. private var _setUpFunction: (() -> ())? /// An optional function that if non-null is run before benchmark samples /// are timed. public var setUpFunction : (() -> ())? { if !shouldRun { return nil } return _setUpFunction } /// Shadow static variable for computed property tearDownFunction. private var _tearDownFunction: (() -> ())? /// An optional function that if non-null is run after samples are taken. public var tearDownFunction: (() -> ())? { if !shouldRun { return nil } return _tearDownFunction } /// DON'T USE ON NEW BENCHMARKS! /// Optional `legacyFactor` is a multiplication constant applied to runtime /// statistics reported in the benchmark summary (it doesn’t affect the /// individual sample times reported in `--verbose` mode). /// /// It enables the migration of benchmark suite to smaller workloads (< 1 ms), /// which are more robust to measurement errors from system under load, /// while maintaining the continuity of longterm benchmark tracking. /// /// Most legacy benchmarks had workloads artificially inflated in their main /// `for` loops with a constant integer factor and the migration consisted of /// dividing it so that the optimized runtime (-O) was less than 1000 μs and /// storing the divisor in `legacyFactor`. This effectively only increases the /// frequency of measurement, gathering more samples that are much less likely /// to be interrupted by a context switch. public var legacyFactor: Int? public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory], setUpFunction: (() -> ())? = nil, tearDownFunction: (() -> ())? = nil, unsupportedPlatforms: BenchmarkPlatformSet = [], legacyFactor: Int? = nil) { self.name = name self._runFunction = runFunction self.tags = Set(tags) self._setUpFunction = setUpFunction self._tearDownFunction = tearDownFunction self.unsupportedPlatforms = unsupportedPlatforms self.legacyFactor = legacyFactor } /// Returns true if this benchmark should be run on the current platform. var shouldRun: Bool { return !unsupportedPlatforms.contains(.currentPlatform) } } extension BenchmarkInfo : Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name == rhs.name } } extension BenchmarkInfo : Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(name) } } // Linear function shift register. // // This is just to drive benchmarks. I don't make any claim about its // strength. According to Wikipedia, it has the maximal period for a // 32-bit register. struct LFSR { // Set the register to some seed that I pulled out of a hat. var lfsr : UInt32 = 0xb78978e7 mutating func shift() { lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001) } mutating func randInt() -> Int64 { var result : UInt32 = 0 for _ in 0..<32 { result = (result << 1) | (lfsr & 1) shift() } return Int64(bitPattern: UInt64(result)) } } var lfsrRandomGenerator = LFSR() // Start the generator from the beginning public func SRand() { lfsrRandomGenerator = LFSR() } public func Random() -> Int64 { return lfsrRandomGenerator.randInt() } // This is a fixed-increment version of Java 8's SplittableRandom generator. // It is a very fast generator passing BigCrush, with 64 bits of state. // See http://dx.doi.org/10.1145/2714064.2660195 and // http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html // // Derived from public domain C implementation by Sebastiano Vigna // See http://xoshiro.di.unimi.it/splitmix64.c public struct SplitMix64: RandomNumberGenerator { private var state: UInt64 public init(seed: UInt64) { self.state = seed } public mutating func next() -> UInt64 { self.state &+= 0x9e3779b97f4a7c15 var z: UInt64 = self.state z = (z ^ (z &>> 30)) &* 0xbf58476d1ce4e5b9 z = (z ^ (z &>> 27)) &* 0x94d049bb133111eb return z ^ (z &>> 31) } } @inlinable // FIXME(inline-always) @inline(__always) public func CheckResults( _ resultsMatch: Bool, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) { guard _fastPath(resultsMatch) else { print("Incorrect result in \(function), \(file):\(line)") abort() } } #if !_runtime(_ObjC) // If we do not have an objc-runtime, then we do not have a definition for // autoreleasepool. Add in our own fake autoclosure for it that is inline // always. That should be able to be eaten through by the optimizer no problem. @inlinable // FIXME(inline-always) @inline(__always) public func autoreleasepool<Result>( invoking body: () throws -> Result ) rethrows -> Result { return try body() } #endif public func False() -> Bool { return false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct : SomeProtocol { init() {} func getValue() -> Int { return 1 } } public func someProtocolFactory() -> SomeProtocol { return MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func blackHole<T>(_ x: T) { } // Return the passed argument without letting the optimizer know that. @inline(never) public func identity<T>(_ x: T) -> T { return x } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func getInt(_ x: Int) -> Int { return x } // The same for String. @inline(never) public func getString(_ s: String) -> String { return s } // The same for Substring. @inline(never) public func getSubstring(_ s: Substring) -> Substring { return s }
apache-2.0
25ce1160ee804da5362bb9d32c0e6b81
33.119266
90
0.698665
4.336183
false
false
false
false
Ben21hao/edx-app-ios-new
Source/CourseCatalogAPI.swift
1
3451
// // CourseCatalogAPI.swift // edX // // Created by Anna Callahan on 10/14/15. // Copyright © 2015 edX. All rights reserved. // import edXCore public struct CourseCatalogAPI { static func coursesDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<[OEXCourse]> { return (json.array?.flatMap {item in item.dictionaryObject.map { OEXCourse(dictionary: $0) } }).toResult() } static func courseDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<OEXCourse> { return json.dictionaryObject.map { OEXCourse(dictionary: $0) }.toResult() } static func enrollmentDeserializer(response: NSHTTPURLResponse, json: JSON) -> Result<UserCourseEnrollment> { return UserCourseEnrollment(json: json).toResult() } private enum Params : String { case User = "username" case CourseDetails = "course_details" case CourseID = "course_id" case EmailOptIn = "email_opt_in" case Mobile = "mobile" case Org = "org" case CompanyId = "company_id" } public static func getCourseCatalog(userID: String, company_id: String, page : Int) -> NetworkRequest<Paginated<[OEXCourse]>> { // public static func getCourseCatalog(userID: String, page : Int, organizationCode: String?) -> NetworkRequest<Paginated<[OEXCourse]>> { // var query = [Params.Mobile.rawValue: JSON(true), Params.User.rawValue: JSON(userID)] // if let orgCode = organizationCode { // query[Params.Org.rawValue] = JSON(orgCode) // } let query = [Params.Mobile.rawValue: JSON(true), Params.CompanyId.rawValue: JSON(company_id), Params.User.rawValue: JSON(userID)] return NetworkRequest( method: .GET, path : "/api/mobile/enterprise/v0.5/companyfindcourses/", //api/courses/v1/ query : query, requiresAuth : true, deserializer: .JSONResponse(coursesDeserializer) ).paginated(page: page) } public static func getCourse(courseID: String, companyID : String) -> NetworkRequest<OEXCourse> { return NetworkRequest( // method: .GET, // path: "/api/mobile/enterprise/v0.5/companycoursesdetail/{courseID}".oex_formatWithParameters(["courseID" : courseID]), // deserializer: .JSONResponse(courseDeserializer)) //api/courses/v1/courses/{courseID} // /api/mobile/enterprise/v0.5/companycoursesdetail/course-v1:EliteU+11067001+A1?company_id=600000001 method: .GET, path: "/api/mobile/enterprise/v0.5/companycoursesdetail/{courseID}".oex_formatWithParameters(["courseID" : courseID]), query : [Params.CompanyId.rawValue: JSON(companyID)], deserializer: .JSONResponse(courseDeserializer)) } public static func enroll(courseID: String, emailOptIn: Bool = true) -> NetworkRequest<UserCourseEnrollment> { return NetworkRequest( method: .POST, path: "api/enrollment/v1/enrollment", requiresAuth: true, body: .JSONBody(JSON([ "course_details" : [ "course_id": courseID, "email_opt_in": emailOptIn ] ])), deserializer: .JSONResponse(enrollmentDeserializer) ) } }
apache-2.0
52b6782f1f0d1a1a2c49b823d82530a0
37.764045
140
0.614493
4.367089
false
false
false
false
mingxianzyh/D3View
D3View/D3View/D3TextFiled.swift
1
1195
// // D3TextFiled.swift // D3View // // Created by mozhenhau on 15/5/15. // Copyright (c) 2015年 mozhenhau. All rights reserved. // import Foundation import UIKit public class D3TextField:UITextField,UITextFieldDelegate{ @IBInspectable var litmit: Int = 30 //为0则不限制 @IBInspectable var isGrayBorder: Bool = false { didSet { if isGrayBorder{ self.borderStyle = UITextBorderStyle.None self.initStyle(ViewStyle.Border) self.layer.borderColor = UIColor(red: 50/255 , green: 50/255, blue: 50/255, alpha: 0.8).CGColor } } } required public init(coder aDecoder: NSCoder) { super.init(coder:aDecoder)! delegate = self if let style:ViewStyle = ViewStyle(rawValue: self.tag){ initStyle(style) } } func setLitmitCount(litmit:Int){ self.litmit = litmit } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{ if litmit != 0 && range.location > litmit{ return false } return true } }
mit
50ac4b53e4b105cbe8e41fa19b925496
27.190476
138
0.611158
4.195035
false
false
false
false
Tangdixi/DCQRCode
Source/FunctionalCoreImage.swift
2
4847
// // CoreImageWrapper.swift // Example_DCPathButton // // Created by tang dixi on 9/5/2016. // Copyright © 2016 Tangdixi. All rights reserved. // import Foundation import CoreImage import UIKit typealias Filter = ((CIImage) -> CIImage) infix operator >>> : DCQRCodePrecedence precedencegroup DCQRCodePrecedence { associativity: left higherThan: AdditionPrecedence lowerThan: MultiplicationPrecedence } func >>>(firstFilter: @escaping Filter, secondFilter: @escaping Filter) -> Filter { return { image in secondFilter(firstFilter(image)) } } func generateQRCodeFilter(_ info:String) -> Filter { return { _ in // Guard no illegal characters guard let data = info.data(using: String.Encoding.isoLatin1) else { fatalError() } let parameters = ["inputMessage": data, "inputCorrectionLevel": "H"] as [String : Any] guard let filter = CIFilter(name: "CIQRCodeGenerator", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func cropFilter(_ cropRect:CGRect) -> Filter { return { image in let croppedImage = image.cropping(to: cropRect) return croppedImage } } func bitmapResizeFilter(_ desireSize:CGSize) -> Filter { return { image in let extent = image.extent.integral let scale = min(desireSize.width/extent.width, desireSize.height/extent.height) let width = Int(extent.width*scale) let height = Int(extent.height*scale) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let bitmapRef = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) let context = CIContext() let bitmapImage = context.createCGImage(image, from: extent) bitmapRef?.interpolationQuality = .none bitmapRef?.scaleBy(x: scale, y: scale) bitmapRef?.draw(bitmapImage!, in: extent) guard let scaledImageRef = bitmapRef?.makeImage() else { fatalError() } let scaledImage = CIImage(cgImage: scaledImageRef) return scaledImage } } func resizeFilter(_ desireSize:CGSize) -> Filter { return { image in let scaleRatio = desireSize.width/image.extent.width let scaledImage = image.applying(CGAffineTransform(scaleX: scaleRatio, y: scaleRatio)) return scaledImage } } func falseColorFilter(_ color0:UIColor, color1:UIColor) -> Filter { return { image in let ciColor0 = CIColor(color:color0) let ciColor1 = CIColor(color:color1) let parameters = ["inputImage": image, "inputColor0": ciColor0, "inputColor1": ciColor1] guard let filter = CIFilter(name: "CIFalseColor", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func maskToAlphaFilter() -> Filter { return { image in let parameters = ["inputImage": image] guard let filter = CIFilter(name: "CIMaskToAlpha", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func blendWithAlphaMaskFilter(_ backgroundImage:CIImage, maskImage:CIImage) -> Filter { return { image in let parameters = ["inputImage": image, "inputBackgroundImage": backgroundImage, "inputMaskImage": maskImage] guard let filter = CIFilter(name: "CIBlendWithAlphaMask", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func affineTileFilter(_ transform:NSValue, corpRect:CGRect) -> Filter { return { image in let parameters = ["inputImage": image, "inputTransform": transform] guard let filter = CIFilter(name: "CIAffineTile", withInputParameters: parameters) else { fatalError() } guard var outputImage = filter.outputImage else { fatalError() } outputImage = outputImage.cropping(to: corpRect) return outputImage } } func colorBlendModeFilter(_ backgroundImage:CIImage) -> Filter { return { image in let parameters = ["inputImage": image, "inputBackgroundImage": backgroundImage] guard let filter = CIFilter(name: "CIColorBlendMode", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func constantColorGenerateFilter(_ color:CIColor) -> Filter { return { _ in let parameters = ["inputColor": color] guard let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } }
mit
8efa15402526620b054fe4e168cd1497
34.115942
160
0.718531
4.429616
false
false
false
false
nextcloud/ios
iOSClient/Media/NCMedia.swift
1
34408
// // NCMedia.swift // Nextcloud // // Created by Marino Faggiana on 12/02/2019. // Copyright © 2019 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit import NextcloudKit class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { @IBOutlet weak var collectionView: UICollectionView! private var emptyDataSet: NCEmptyDataSet? private var mediaCommandView: NCMediaCommandView? private var gridLayout: NCGridMediaLayout! internal let appDelegate = UIApplication.shared.delegate as! AppDelegate public var metadatas: [tableMetadata] = [] private var account: String = "" private var predicateDefault: NSPredicate? private var predicate: NSPredicate? internal var isEditMode = false internal var selectOcId: [String] = [] internal var filterClassTypeImage = false internal var filterClassTypeVideo = false private let maxImageGrid: CGFloat = 7 private var cellHeigth: CGFloat = 0 private var oldInProgress = false private var newInProgress = false private var lastContentOffsetY: CGFloat = 0 private var mediaPath = "" private var livePhoto: Bool = false private var timeIntervalSearchNewMedia: TimeInterval = 3.0 private var timerSearchNewMedia: Timer? private let insetsTop: CGFloat = 75 struct cacheImages { static var cellLivePhotoImage = UIImage() static var cellPlayImage = UIImage() } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground collectionView.register(UINib(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell") collectionView.alwaysBounceVertical = true collectionView.contentInset = UIEdgeInsets(top: insetsTop, left: 0, bottom: 50, right: 0) collectionView.backgroundColor = .systemBackground gridLayout = NCGridMediaLayout() gridLayout.itemForLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5)) gridLayout.sectionHeadersPinToVisibleBounds = true collectionView.collectionViewLayout = gridLayout // Empty emptyDataSet = NCEmptyDataSet(view: collectionView, offset: 0, delegate: self) // Notification NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil) mediaCommandView = Bundle.main.loadNibNamed("NCMediaCommandView", owner: self, options: nil)?.first as? NCMediaCommandView self.view.addSubview(mediaCommandView!) mediaCommandView?.mediaView = self mediaCommandView?.zoomInButton.isEnabled = !(gridLayout.itemForLine == 1) mediaCommandView?.zoomOutButton.isEnabled = !(gridLayout.itemForLine == maxImageGrid - 1) mediaCommandView?.collapseControlButtonView(true) mediaCommandView?.translatesAutoresizingMaskIntoConstraints = false mediaCommandView?.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true mediaCommandView?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true mediaCommandView?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true mediaCommandView?.heightAnchor.constraint(equalToConstant: 150).isActive = true self.updateMediaControlVisibility() collectionView.prefetchDataSource = self cacheImages.cellLivePhotoImage = NCUtility.shared.loadImage(named: "livephoto", color: .white) cacheImages.cellPlayImage = NCUtility.shared.loadImage(named: "play.fill", color: .white) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) appDelegate.activeViewController = self navigationController?.setMediaAppreance() NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil) self.reloadDataSourceWithCompletion { _ in self.timerSearchNewMedia?.invalidate() self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) mediaCommandTitle() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) self.collectionView?.collectionViewLayout.invalidateLayout() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - NotificationCenter @objc func initialize() { self.reloadDataSourceWithCompletion { _ in self.timerSearchNewMedia?.invalidate() self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.mediaCommandTitle() } } } @objc func deleteFile(_ notification: NSNotification) { guard let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String else { return } let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == ocId } let metadatas = self.metadatas.filter { $0.ocId != ocId } self.metadatas = metadatas if self.metadatas.count == 0 { collectionView?.reloadData() } else if let row = indexes.first { let indexPath = IndexPath(row: row, section: 0) collectionView?.deleteItems(at: [indexPath]) } self.updateMediaControlVisibility() } @objc func moveFile(_ notification: NSNotification) { guard let userInfo = notification.userInfo as NSDictionary?, let account = userInfo["account"] as? String, account == appDelegate.account else { return } self.reloadDataSourceWithCompletion { _ in } } @objc func renameFile(_ notification: NSNotification) { guard let userInfo = notification.userInfo as NSDictionary?, let account = userInfo["account"] as? String, account == appDelegate.account else { return } self.reloadDataSourceWithCompletion { _ in } } @objc func uploadedFile(_ notification: NSNotification) { guard let userInfo = notification.userInfo as NSDictionary?, let error = userInfo["error"] as? NKError, error == .success, let account = userInfo["account"] as? String, account == appDelegate.account else { return } self.reloadDataSourceWithCompletion { _ in } } // MARK: - Command func mediaCommandTitle() { mediaCommandView?.title.text = "" if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) { if let cell = visibleCells.first as? NCGridMediaCell { if cell.date != nil { mediaCommandView?.title.text = CCUtility.getTitleSectionDate(cell.date) } } } } @objc func zoomOutGrid() { UIView.animate(withDuration: 0.0, animations: { if self.gridLayout.itemForLine + 1 < self.maxImageGrid { self.gridLayout.itemForLine += 1 self.mediaCommandView?.zoomInButton.isEnabled = true } if self.gridLayout.itemForLine == self.maxImageGrid - 1 { self.mediaCommandView?.zoomOutButton.isEnabled = false } self.collectionView.collectionViewLayout.invalidateLayout() CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine)) }) } @objc func zoomInGrid() { UIView.animate(withDuration: 0.0, animations: { if self.gridLayout.itemForLine - 1 > 0 { self.gridLayout.itemForLine -= 1 self.mediaCommandView?.zoomOutButton.isEnabled = true } if self.gridLayout.itemForLine == 1 { self.mediaCommandView?.zoomInButton.isEnabled = false } self.collectionView.collectionViewLayout.invalidateLayout() CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine)) }) } @objc func openMenuButtonMore(_ sender: Any) { toggleMenu() } // MARK: Select Path func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) { guard let serverUrl = serverUrl else { return } let path = CCUtility.returnPathfromServerUrl(serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account) ?? "" NCManageDatabase.shared.setAccountMediaPath(path, account: appDelegate.account) reloadDataSourceWithCompletion { _ in self.searchNewMedia() } } // MARK: - Empty func emptyDataSetView(_ view: NCEmptyView) { view.emptyImage.image = UIImage(named: "media")?.image(color: .gray, size: UIScreen.main.bounds.width) if oldInProgress || newInProgress { view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "") } else { view.emptyTitle.text = NSLocalizedString("_tutorial_photo_view_", comment: "") } view.emptyDescription.text = "" } } // MARK: - Collection View extension NCMedia: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let metadata = metadatas[indexPath.row] if isEditMode { if let index = selectOcId.firstIndex(of: metadata.ocId) { selectOcId.remove(at: index) } else { selectOcId.append(metadata.ocId) } if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) { collectionView.reloadItems(at: [indexPath]) } } else { // ACTIVE SERVERURL appDelegate.activeServerUrl = metadata.serverUrl let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: cell?.imageItem.image) } } func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let cell = collectionView.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil } let metadata = metadatas[indexPath.row] let identifier = indexPath as NSCopying let image = cell.imageItem.image return UIContextMenuConfiguration(identifier: identifier, previewProvider: { return NCViewerProviderContextMenu(metadata: metadata, image: image) }, actionProvider: { _ in return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: false, enableViewInFolder: true, image: image) }) } func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { animator.addCompletion { if let indexPath = configuration.identifier as? IndexPath { self.collectionView(collectionView, didSelectItemAt: indexPath) } } } } extension NCMedia: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { // print("[LOG] n. " + String(indexPaths.count)) } } extension NCMedia: UICollectionViewDataSource { func reloadDataThenPerform(_ closure: @escaping (() -> Void)) { CATransaction.begin() CATransaction.setCompletionBlock(closure) collectionView?.reloadData() CATransaction.commit() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section) return metadatas.count } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = (cell as? NCGridMediaCell), indexPath.row < self.metadatas.count else { return } let metadata = self.metadatas[indexPath.row] if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { cell.imageItem.backgroundColor = nil cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) } else { NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: false, cell: cell, view: collectionView) } } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count { let metadata = metadatas[indexPath.row] NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < metadatas.count { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell let metadata = metadatas[indexPath.row] self.cellHeigth = cell.frame.size.height cell.date = metadata.date as Date cell.fileObjectId = metadata.ocId cell.fileUser = metadata.ownerId if metadata.classFile == NKCommon.typeClassFile.video.rawValue || metadata.classFile == NKCommon.typeClassFile.audio.rawValue { cell.imageStatus.image = cacheImages.cellPlayImage } else if metadata.livePhoto && livePhoto { cell.imageStatus.image = cacheImages.cellLivePhotoImage } if isEditMode { cell.selectMode(true) if selectOcId.contains(metadata.ocId) { cell.selected(true) } else { cell.selected(false) } } else { cell.selectMode(false) } return cell } else { return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell } } } extension NCMedia: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: collectionView.frame.width, height: 0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize(width: collectionView.frame.width, height: 0) } } extension NCMedia { // MARK: - Datasource @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) { guard !appDelegate.account.isEmpty else { return } if account != appDelegate.account { self.metadatas = [] account = appDelegate.account collectionView?.reloadData() } livePhoto = CCUtility.getLivePhoto() if let activeAccount = NCManageDatabase.shared.getActiveAccount() { self.mediaPath = activeAccount.mediaPath } let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) + mediaPath predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.typeClassFile.image.rawValue, NKCommon.typeClassFile.video.rawValue) if filterClassTypeImage { predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.typeClassFile.video.rawValue) } else if filterClassTypeVideo { predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.typeClassFile.image.rawValue) } else { predicate = predicateDefault } guard var predicateForGetMetadatasMedia = predicate else { return } if livePhoto { let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)") predicateForGetMetadatasMedia = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateForGetMetadatasMedia, predicateLivePhoto]) } DispatchQueue.global().async { self.metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate()) DispatchQueue.main.sync { self.reloadDataThenPerform { self.updateMediaControlVisibility() self.mediaCommandTitle() completion(self.metadatas) } } } } func updateMediaControlVisibility() { if self.metadatas.count == 0 { if !self.filterClassTypeImage && !self.filterClassTypeVideo { self.mediaCommandView?.toggleEmptyView(isEmpty: true) self.mediaCommandView?.isHidden = false } else { self.mediaCommandView?.toggleEmptyView(isEmpty: true) self.mediaCommandView?.isHidden = false } } else { self.mediaCommandView?.toggleEmptyView(isEmpty: false) self.mediaCommandView?.isHidden = false } } // MARK: - Search media private func searchOldMedia(value: Int = -30, limit: Int = 300) { if oldInProgress { return } else { oldInProgress = true } collectionView.reloadData() var lessDate = Date() if predicateDefault != nil { if let metadata = NCManageDatabase.shared.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) { lessDate = metadata.date as Date } } var greaterDate: Date if value == -999 { greaterDate = Date.distantPast } else { greaterDate = Calendar.current.date(byAdding: .day, value: value, to: lessDate)! } var bottom: CGFloat = 0 if let mainTabBar = self.tabBarController?.tabBar as? NCMainTabBar { bottom = -mainTabBar.getHight() } NCActivityIndicator.shared.start(backgroundView: self.view, bottom: bottom-5, style: .gray) let options = NKRequestOptions(timeout: 300) NextcloudKit.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, data, error in self.oldInProgress = false NCActivityIndicator.shared.stop() self.collectionView.reloadData() if error == .success && account == self.appDelegate.account { if files.count > 0 { NCManageDatabase.shared.convertNKFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { _, _, metadatas in let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate) let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateDate, self.predicateDefault!]) let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult) let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false) if metadatasChanged.metadatasUpdate.count == 0 { self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: true) } else { self.reloadDataSourceWithCompletion { _ in } } } } else { self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: false) } } else if error != .success { NKCommon.shared.writeLog("[INFO] Media search old media error code \(error.errorCode) " + error.errorDescription) } } } private func researchOldMedia(value: Int, limit: Int, withElseReloadDataSource: Bool) { if value == -30 { searchOldMedia(value: -90) } else if value == -90 { searchOldMedia(value: -180) } else if value == -180 { searchOldMedia(value: -999) } else if value == -999 && limit > 0 { searchOldMedia(value: -999, limit: 0) } else { if withElseReloadDataSource { self.reloadDataSourceWithCompletion { _ in } } } } @objc func searchNewMediaTimer() { self.searchNewMedia() } @objc func searchNewMedia() { if newInProgress { return } else { newInProgress = true mediaCommandView?.activityIndicator.startAnimating() } var limit: Int = 1000 guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return } guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return } if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) { if let cell = visibleCells.first as? NCGridMediaCell { if cell.date != nil { if cell.date != self.metadatas.first?.date as Date? { lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)! limit = 0 } } } if let cell = visibleCells.last as? NCGridMediaCell { if cell.date != nil { greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)! } } } reloadDataThenPerform { let options = NKRequestOptions(timeout: 300) NextcloudKit.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, data, error in self.newInProgress = false self.mediaCommandView?.activityIndicator.stopAnimating() if error == .success && account == self.appDelegate.account && files.count > 0 { NCManageDatabase.shared.convertNKFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, _, metadatas in let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate) let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, self.predicate!]) let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult) let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false) if updateMetadatas.metadatasUpdate.count > 0 || updateMetadatas.metadatasDelete.count > 0 { self.reloadDataSourceWithCompletion { _ in } } } } else if error == .success && files.count == 0 && self.metadatas.count == 0 { self.searchOldMedia() } else if error != .success { NKCommon.shared.writeLog("[ERROR] Media search new media error code \(error.errorCode) " + error.errorDescription) } } } } } // MARK: - ScrollView extension NCMedia: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y { mediaCommandTitle() lastContentOffsetY = scrollView.contentOffset.y } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { mediaCommandView?.collapseControlButtonView(true) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { timerSearchNewMedia?.invalidate() timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false) if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) { searchOldMedia() } } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { timerSearchNewMedia?.invalidate() timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false) if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) { searchOldMedia() } } func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { let y = view.safeAreaInsets.top scrollView.contentOffset.y = -(insetsTop + y) } } // MARK: - Media Command View class NCMediaCommandView: UIView { @IBOutlet weak var moreView: UIVisualEffectView! @IBOutlet weak var gridSwitchButton: UIButton! @IBOutlet weak var separatorView: UIView! @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint! @IBOutlet weak var zoomInButton: UIButton! @IBOutlet weak var zoomOutButton: UIButton! @IBOutlet weak var moreButton: UIButton! @IBOutlet weak var controlButtonView: UIVisualEffectView! @IBOutlet weak var title: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var mediaView: NCMedia? private let gradient: CAGradientLayer = CAGradientLayer() override func awakeFromNib() { moreView.layer.cornerRadius = 20 moreView.layer.masksToBounds = true controlButtonView.layer.cornerRadius = 20 controlButtonView.layer.masksToBounds = true controlButtonView.effect = UIBlurEffect(style: .dark) gradient.frame = bounds gradient.startPoint = CGPoint(x: 0, y: 0.5) gradient.endPoint = CGPoint(x: 0, y: 1) gradient.colors = [UIColor.black.withAlphaComponent(UIAccessibility.isReduceTransparencyEnabled ? 0.8 : 0.4).cgColor, UIColor.clear.cgColor] layer.insertSublayer(gradient, at: 0) moreButton.setImage(UIImage(named: "more")!.image(color: .white, size: 25), for: .normal) title.text = "" } func toggleEmptyView(isEmpty: Bool) { if isEmpty { UIView.animate(withDuration: 0.3) { self.moreView.effect = UIBlurEffect(style: .dark) self.gradient.isHidden = true self.controlButtonView.isHidden = true } } else { UIView.animate(withDuration: 0.3) { self.moreView.effect = UIBlurEffect(style: .dark) self.gradient.isHidden = false self.controlButtonView.isHidden = false } } } @IBAction func moreButtonPressed(_ sender: UIButton) { mediaView?.openMenuButtonMore(sender) } @IBAction func zoomInPressed(_ sender: UIButton) { mediaView?.zoomInGrid() } @IBAction func zoomOutPressed(_ sender: UIButton) { mediaView?.zoomOutGrid() } @IBAction func gridSwitchButtonPressed(_ sender: Any) { self.collapseControlButtonView(false) } func collapseControlButtonView(_ collapse: Bool) { if collapse { self.buttonControlWidthConstraint.constant = 40 UIView.animate(withDuration: 0.25) { self.zoomOutButton.isHidden = true self.zoomInButton.isHidden = true self.separatorView.isHidden = true self.gridSwitchButton.isHidden = false self.layoutIfNeeded() } } else { self.buttonControlWidthConstraint.constant = 80 UIView.animate(withDuration: 0.25) { self.zoomOutButton.isHidden = false self.zoomInButton.isHidden = false self.separatorView.isHidden = false self.gridSwitchButton.isHidden = true self.layoutIfNeeded() } } } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return moreView.frame.contains(point) || controlButtonView.frame.contains(point) } override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) gradient.frame = bounds } } // MARK: - Media Grid Layout class NCGridMediaLayout: UICollectionViewFlowLayout { var marginLeftRight: CGFloat = 2 var itemForLine: CGFloat = 3 override init() { super.init() sectionHeadersPinToVisibleBounds = false minimumInteritemSpacing = 0 minimumLineSpacing = marginLeftRight self.scrollDirection = .vertical self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var itemSize: CGSize { get { if let collectionView = collectionView { let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine let itemHeight: CGFloat = itemWidth return CGSize(width: itemWidth, height: itemHeight) } // Default fallback return CGSize(width: 100, height: 100) } set { super.itemSize = newValue } } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { return proposedContentOffset } }
gpl-3.0
63675384d35b3d3a8cc82abea18bee31
40.857664
286
0.656843
4.936442
false
false
false
false
elpassion/el-space-ios
ELSpaceTests/TestCases/Commons/Presenters/Modal/ModalViewControllerPresentTransitionSpec.swift
1
5132
import Quick import Nimble @testable import ELSpace class ModalViewControllerPresentTransitionSpec: QuickSpec { override func spec() { describe("ModalViewControllerPresentTransition") { var sut: ModalViewControllerPresentTransition! var animatorMock: AnimatorMock.Type! beforeEach { animatorMock = AnimatorMock.self animatorMock.prepare() sut = ModalViewControllerPresentTransition(animator: animatorMock) } it("should has correct transition duration") { expect(sut.transitionDuration(using: nil)).to(equal(0.4)) } context("when animating without to view") { beforeEach { sut.animateTransition(using: ViewControllerTransitionContextStub()) } it("should not animate") { expect(animatorMock.animatingWithDuration).to(beNil()) } } context("when animating") { var transitionContext: ViewControllerTransitionContextStub! beforeEach { transitionContext = ViewControllerTransitionContextStub() transitionContext.stubbedToView = UIView() sut.animateTransition(using: transitionContext) } describe("target view") { var targetView: UIView? beforeEach { targetView = transitionContext.containerView.subviews.first(where: { $0.isEqual(transitionContext.stubbedToView) }) } it("should not be nil") { expect(targetView).notTo(beNil()) } it("should have correct alpha") { expect(targetView?.alpha).to(equal(0)) } it("should have correct transform") { expect(targetView?.transform).to(equal(CGAffineTransform(translationX: 0, y: 200))) } } describe("background view") { var backgroundView: UIView? beforeEach { backgroundView = transitionContext.containerView.subviews.first(where: { $0.isKind(of: ModalViewControllerBackgroundView.self) }) } it("should not be nil") { expect(backgroundView).notTo(beNil()) } it("should have correct alpha") { expect(backgroundView?.alpha).to(equal(0)) } } it("should animate with correct duration") { expect(animatorMock.animatingWithDuration).to(equal(sut.transitionDuration(using: nil))) } context("when performing animations") { beforeEach { animatorMock.animations?() animatorMock.completion?(true) } it("should complete transition") { expect(transitionContext.invokedCompleteTransition?.count) == 1 expect(transitionContext.invokedCompleteTransition?.didComplete) == true } describe("target view") { var targetView: UIView? beforeEach { targetView = transitionContext.containerView.subviews.first(where: { $0.isEqual(transitionContext.stubbedToView) }) } it("should not be nil") { expect(targetView).notTo(beNil()) } it("should have correct alpha") { expect(targetView?.alpha).to(equal(1)) } it("should have correct transform") { expect(targetView?.transform).to(equal(CGAffineTransform.identity)) } } describe("background view") { var backgroundView: UIView? beforeEach { backgroundView = transitionContext.containerView.subviews.first(where: { $0.isKind(of: ModalViewControllerBackgroundView.self) }) } it("should not be nil") { expect(backgroundView).notTo(beNil()) } it("should have correct alpha") { expect(backgroundView?.alpha).to(equal(1)) } } } } } } }
gpl-3.0
14d0c5bf96230b636aeba7f43aaff43f
35.397163
108
0.455378
6.925776
false
false
false
false
egouletlang/BaseUtils
BaseUtils/Extension/UIColor_EXT.swift
2
2341
// // UIColor_EXT.swift // Bankroll // // Created by Etienne Goulet-Lang on 5/25/16. // Copyright © 2016 Etienne Goulet-Lang. All rights reserved. // import Foundation import UIKit /// Represents RGB color values (0xRRGGBB) public typealias UIColorRGB = Int64 public extension UIColor { public convenience init(rgb: Int64) { if rgb > 0xFFFFFF { // there is some alpha component self.init(argb: rgb) } else { let red = CGFloat((rgb>>16)&0xFF) / 255 let green = CGFloat((rgb>>8)&0xFF) / 255 let blue = CGFloat(rgb&0xFF) / 255 self.init(red: red, green: green, blue: blue, alpha: 1) } } public convenience init(argb: Int64) { if argb <= 0xFFFFFF { self.init(rgb: argb) } else { let alpha = CGFloat((argb>>24)&0xFF) / 255 let red = CGFloat((argb>>16)&0xFF) / 255 let green = CGFloat((argb>>8)&0xFF) / 255 let blue = CGFloat(argb&0xFF) / 255 self.init(red: red, green: green, blue: blue, alpha: alpha) } } public convenience init?(hexString: String) { var r, g, b, a: CGFloat let scrubbedStr = hexString .replacingOccurrences(of: "#", with: "") .replacingOccurrences(of: "0x", with: "").uppercased() let scanner = Scanner(string: scrubbedStr) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { a = CGFloat((hexNumber & 0xff000000) >> 24) / 255 r = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 g = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 b = CGFloat(hexNumber & 0x000000ff) / 255 if (scrubbedStr as NSString).length == 6 { a = 1 } self.init(red: r, green: g, blue: b, alpha: a) return } return nil } public func toColorComponents() -> [CGFloat] { return self.cgColor.toColorComponents() } public func toRGB() -> UIColorRGB { return self.cgColor.toRGB() } public func toRGBString(_ prefixWithHash: Bool = true) -> String { return self.cgColor.toRGBString(prefixWithHash) } }
mit
c8851d38017e57953f8b79edd90e3028
28.25
71
0.534615
3.979592
false
false
false
false
polydice/ICInputAccessory
Source/KeyboardDismissTextField/KeyboardDismissTextField.swift
1
3078
// // KeyboardDismissTextField.swift // ICInputAccessory // // Created by Ben on 07/03/2016. // Copyright © 2016 Polydice, Inc. // // 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 /// A text field that has a button to dismiss keyboard on the input accessory view. @IBDesignable open class KeyboardDismissTextField: UITextField { /// The custom input accessory view with a button to dismiss keyboard. @IBOutlet public var keyboardAccessoryView: KeyboardDismissAccessoryView! { didSet { if UI_USER_INTERFACE_IDIOM() != .phone { return } keyboardAccessoryView.dismissButton.addTarget(self, action: .dismiss, for: .touchUpInside) inputAccessoryView = keyboardAccessoryView } } // MARK: - Initialization /// Initializes and returns a newly allocated view object with the specified frame rectangle. public override init(frame: CGRect) { super.init(frame: frame) setUpAccessoryView() } /// Returns an object initialized from data in a given unarchiver. public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpAccessoryView() } // MARK: - UIResponder open override func becomeFirstResponder() -> Bool { if UI_USER_INTERFACE_IDIOM() == .phone { keyboardAccessoryView.alpha = 1 } return super.becomeFirstResponder() } @objc fileprivate func dismiss(_ sender: UIButton) { resignFirstResponder() UIView.animate(withDuration: 0.3) { self.keyboardAccessoryView.alpha = 0 } } // MARK: - Private Methods private func setUpAccessoryView() { if keyboardAccessoryView == nil { // Set an initial frame for the button to appear during UI testing. let frame = CGRect(x: 0, y: 0, width: 320, height: 60) keyboardAccessoryView = KeyboardDismissAccessoryView(frame: frame) } } } //////////////////////////////////////////////////////////////////////////////// private extension Selector { static let dismiss = #selector(KeyboardDismissTextField.dismiss(_:)) }
mit
0ee78ba385ad931e32063f227f80bf3b
33.188889
96
0.704582
4.585693
false
false
false
false
sivu22/AnyTracker
AnyTracker/ItemsTableViewController.swift
1
14069
// // ItemsTableViewController.swift // AnyTracker // // Created by Cristian Sava on 14/06/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import UIKit protocol ItemsDelegate: class { func numItemsChange(increased increase: Bool) } class ItemsTableViewController: UITableViewController, NewItemDelegate, EditItemDelegate, ItemChangeDelegate { weak var delegate: ItemsDelegate? @IBOutlet weak var addButton: UIBarButtonItem! fileprivate(set) var app: App? var listName: String! var listTitle: String! var allItems: Bool = false var alert: UIAlertController? var list: List? // The current list (nil for ALL) var items: [Item] = [] // All the items that can be seen in the VC fileprivate var addItem: Item? = nil fileprivate var addItemIndex: Int = 0 fileprivate var editItemIndex: Int = -1 fileprivate var refreshItemIndex: Int = -1 var numItems: Int = -1 fileprivate var reorderTableView: LongPressReorderTableView! override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.estimatedRowHeight = 90 tableView.rowHeight = UITableView.automaticDimension alert = nil if listName == "all" { allItems = true // ALL is only for looking at available items (readonly) addButton.hide() // Build up the list of items if let app = app, let lists = app.lists { DispatchQueue.global().async { let listIDs = lists.getListIDs() for list in listIDs { let itemIDs = List.getItemIDs(fromList: list) for itemID in itemIDs { do { let item = try Items.loadItem(withID: itemID) self.items.append(item) } catch let error as Status { self.alert = error.createErrorAlert() } catch { self.alert = Status.errorDefault.createErrorAlert() } } } DispatchQueue.main.async { self.numItems = self.items.count self.tableView.reloadData() } } } } else { title = listTitle DispatchQueue.global().async { do { self.list = try List.loadListFromFile(self.listName) self.numItems = self.list!.numItems for itemID in self.list!.items { let item = try Items.loadItem(withID: itemID) self.items.append(item) } } catch let error as Status { self.alert = error.createErrorAlert() } catch { self.alert = Status.errorDefault.createErrorAlert() } DispatchQueue.main.async { self.tableView.reloadData() if let alert = self.alert { self.addButton.isEnabled = false if self.presentedViewController == nil { self.present(alert, animated: true, completion: nil) } } self.reorderTableView = LongPressReorderTableView(self.tableView) self.reorderTableView.delegate = self self.reorderTableView.enableLongPressReorder() } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numItems == items.count ? numItems : items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell cell.initCell(withItem: items[indexPath.row], separator: app?.numberSeparator ?? true, longFormat: app?.dateFormatLong ?? true) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let itemID: String = items[indexPath.row].ID guard let type = Items.getItemType(fromID: itemID) else { Utils.debugLog("Can't get item type of item \(itemID) at index \(indexPath)") return } switch type { case .sum: performSegue(withIdentifier: "toSumItem", sender: indexPath) case .counter: performSegue(withIdentifier: "toCounterItem", sender: indexPath) case .journal: performSegue(withIdentifier: "toJournalItem", sender: indexPath) } } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if allItems { return false } return true } fileprivate func deleteItem(withIndexPath indexPath: IndexPath) { let index = indexPath.row var alert: UIAlertController? DispatchQueue.global().async { do { let _ = Items.deleteItemFile(withID: self.list!.items[index]) try self.list!.removeItem(atIndex: index) } catch let error as Status { alert = error.createErrorAlert() } catch { alert = Status.errorDefault.createErrorAlert() } DispatchQueue.main.async { if alert != nil { self.present(alert!, animated: true, completion: nil) return } self.numItems -= 1 self.items.remove(at: index) self.delegate?.numItemsChange(increased: false) self.tableView.deleteRows(at: [indexPath], with: .fade) } } } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let itemIndex = indexPath.row let edit = UITableViewRowAction(style: .normal, title: "Edit") { action, index in let vcNav = self.storyboard!.instantiateViewController(withIdentifier: "NewItemNavigation") as! UINavigationController let vc = vcNav.children[0] as! NewItemViewController vc.delegateEdit = self self.editItemIndex = itemIndex vc.longDateFormat = self.app?.dateFormatLong ?? true vc.editItem = self.items[itemIndex] self.present(vcNav, animated: true, completion: nil) self.tableView.setEditing(false, animated: true) } edit.backgroundColor = UIColor.lightGray let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, index in let item = self.items[itemIndex] if !item.isEmpty() { let alert = UIAlertController(title: "", message: "Are you sure you want to delete the item?", preferredStyle: UIAlertController.Style.alert) let yesAction = UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { (action: UIAlertAction!) in self.deleteItem(withIndexPath: indexPath) }) let noAction = UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: { (action: UIAlertAction!) in self.tableView.setEditing(false, animated: true) }) alert.addAction(yesAction) alert.addAction(noAction) self.present(alert, animated: true, completion: nil) return } self.deleteItem(withIndexPath: indexPath) } return [delete, edit] } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { } 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, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) { } // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { if allItems { return false } return true } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. guard let identifier = segue.identifier else { return } let itemIndex = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row ?? -1 let itemIDIndex = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row ?? 0 if identifier == "toNewItem" { let vc = segue.destination.children[0] as! NewItemViewController vc.list = list! vc.longDateFormat = app?.dateFormatLong ?? true vc.insertItemAtFront = app?.addNewItemTop ?? false vc.delegateNew = self } else if identifier == "toSumItem" { let vc = segue.destination as! ItemSumViewController vc.numberSeparator = app?.numberSeparator ?? true vc.itemChangeDelegate = self refreshItemIndex = itemIndex vc.item = items[itemIDIndex] as? ItemSum } else if identifier == "toCounterItem" { let vc = segue.destination as! ItemCounterViewController vc.numberSeparator = app?.numberSeparator ?? true vc.itemChangeDelegate = self refreshItemIndex = itemIndex vc.item = items[itemIDIndex] as? ItemCounter } else if identifier == "toJournalItem" { let vc = segue.destination as! ItemJournalViewController vc.itemChangeDelegate = self vc.longDateFormat = app?.dateFormatLong ?? true refreshItemIndex = itemIndex vc.item = items[itemIDIndex] as? ItemJournal } } @IBAction func unwindToItems(_ segue: UIStoryboardSegue) { let srcVC = segue.source as? NewItemViewController if let vc = srcVC { vc.prepareForDismissingController() } } func injectApp(_ app: App) { self.app = app } func newItem(_ item : Item, atIndex index: Int, sender: NewItemViewController) { addItem = item addItemIndex = index if addItem != nil && addItemIndex > -1 { // Item is already added to list and written on disk numItems += 1 delegate?.numItemsChange(increased: true) if addItemIndex == 0 { items.insert(addItem!, at: 0) } else { items.append(addItem!) } tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: addItemIndex, section: 0)], with: UITableView.RowAnimation.right) tableView.endUpdates() // Not needed, should be a bool instead addItem = nil } } func updateItem(fromSender sender: NewItemViewController) { let itemIndex = editItemIndex editItemIndex = -1 reloadRows(at: [itemIndex]) } func itemChanged() { if refreshItemIndex > -1 { reloadRows(at: [refreshItemIndex]) } } } // MARK: - Long press drag and drop reorder extension ItemsTableViewController { override func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) { list!.exchangeItem(fromIndex: currentIndex.row, toIndex: newIndex.row) items.swapAt(currentIndex.row, newIndex.row) } override func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) { // Save the new list of items IDs DispatchQueue.global().async { var alert: UIAlertController? do { try self.list!.saveListToFile() } catch let error as Status { alert = error.createErrorAlert() } catch { alert = Status.errorDefault.createErrorAlert() } if alert != nil { DispatchQueue.main.async { self.present(alert!, animated: true, completion: nil) } } } } }
mit
12faeb44290a055a50ab034597600e3f
36.021053
157
0.560989
5.454827
false
false
false
false
tgebarowski/SwiftySettings
Source/UI/OptionCell.swift
1
1875
// // SettingsOptionCell.swift // // SwiftySettings // Created by Tomasz Gebarowski on 07/08/15. // Copyright © 2015 codica Tomasz Gebarowski <gebarowski at gmail.com>. // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit class OptionCell : SettingsCell { override func configureAppearance() { super.configureAppearance() textLabel?.textColor = appearance?.cellTextColor backgroundColor = appearance?.cellBackgroundColor accessoryView?.backgroundColor = appearance?.cellBackgroundColor } func load(_ item: Option) { configureAppearance() textLabel?.text = item.title accessoryType = item.selected ? .checkmark : .none; if let image = item.icon { self.imageView?.image = image } } }
mit
0f9f658b4e83a4e182af4b827f43bd1d
35.745098
80
0.72412
4.62716
false
true
false
false
richardpiazza/SOSwift
Sources/SOSwift/LoanOrCredit.swift
1
3907
import Foundation /// A financial product for the loaning of an amount of money under agreed terms and charges. public class LoanOrCredit: FinancialProduct { /// The amount of money. public var amount: MonetaryAmountOrNumber? /// The currency in which the monetary amount is expressed. public var currency: String? /// The period of time after any due date that the borrower has to fulfil its obligations before a default /// (failure to pay) is deemed to have occurred. public var gracePeriod: Duration? /// A form of paying back money previously borrowed from a lender. /// /// Repayment usually takes the form of periodic payments that normally include part principal plus interest in each /// payment. public var loanRepaymentForm: RepaymentSpecification? /// The duration of the loan or credit agreement. public var loanTerm: QuantitativeValue? /// The type of a loan or credit. public var loanType: URLOrText? /// The only way you get the money back in the event of default is the security. /// /// Recourse is where you still have the opportunity to go back to the borrower for the rest of the money. public var isRecourseLoan: Bool? /// Whether the terms for payment of interest can be renegotiated during the life of the loan. public var isRenegotiableLoan: Bool? /// Assets required to secure loan or credit repayments. It may take form of third party pledge, goods, financial /// instruments (cash, securities, etc.) public var requiredCollateral: ThingOrText? internal enum LoanOrCreditCodingKeys: String, CodingKey { case amount case currency case gracePeriod case loanRepaymentForm case loanTerm case loanType case isRecourseLoan = "recourseLoan" case isRenegotiableLoan = "renegotiableLoan" case requiredCollateral } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: LoanOrCreditCodingKeys.self) amount = try container.decodeIfPresent(MonetaryAmountOrNumber.self, forKey: .amount) currency = try container.decodeIfPresent(String.self, forKey: .currency) gracePeriod = try container.decodeIfPresent(Duration.self, forKey: .gracePeriod) loanRepaymentForm = try container.decodeIfPresent(RepaymentSpecification.self, forKey: .loanRepaymentForm) loanTerm = try container.decodeIfPresent(QuantitativeValue.self, forKey: .loanTerm) loanType = try container.decodeIfPresent(URLOrText.self, forKey: .loanType) isRecourseLoan = try container.decodeIfPresent(Bool.self, forKey: .isRecourseLoan) isRenegotiableLoan = try container.decodeIfPresent(Bool.self, forKey: .isRenegotiableLoan) requiredCollateral = try container.decodeIfPresent(ThingOrText.self, forKey: .requiredCollateral) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: LoanOrCreditCodingKeys.self) try container.encodeIfPresent(amount, forKey: .amount) try container.encodeIfPresent(currency, forKey: .currency) try container.encodeIfPresent(gracePeriod, forKey: .gracePeriod) try container.encodeIfPresent(loanRepaymentForm, forKey: .loanRepaymentForm) try container.encodeIfPresent(loanTerm, forKey: .loanTerm) try container.encodeIfPresent(loanType, forKey: .loanType) try container.encodeIfPresent(isRecourseLoan, forKey: .isRecourseLoan) try container.encodeIfPresent(isRenegotiableLoan, forKey: .isRenegotiableLoan) try container.encodeIfPresent(requiredCollateral, forKey: .requiredCollateral) try super.encode(to: encoder) } }
mit
6c7ac157d84dfd0d997e39b9dcca4f0e
46.072289
120
0.714359
4.429705
false
false
false
false
nmdias/DefaultsKit
Tests/DefaultsTests.swift
1
6071
// // DefaultsTests.swift // // Copyright (c) 2017 - 2018 Nuno Manuel Dias // // 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 XCTest @testable import DefaultsKit class DefaultsKitTests: XCTestCase { var defaults: Defaults! override func setUp() { super.setUp() self.defaults = Defaults() } override func tearDown() { super.tearDown() self.defaults = nil } func testInteger() { // Given let value = 123 // When defaults.set(value, for: .integerKey) // Then let hasKey = defaults.has(.integerKey) XCTAssertTrue(hasKey) let savedValue = defaults.get(for: .integerKey) XCTAssertEqual(savedValue, value) } func testFloat() { // Given let value: Float = 123.1 // When defaults.set(value, for: .floatKey) // Then let hasKey = defaults.has(.floatKey) XCTAssertTrue(hasKey) let savedValue = defaults.get(for: .floatKey) XCTAssertEqual(savedValue, value) } func testDouble() { // Given let value: Double = 123.1 // When defaults.set(value, for: .doubleKey) // Then let hasKey = defaults.has(.doubleKey) XCTAssertTrue(hasKey) let savedValue = defaults.get(for: .doubleKey) XCTAssertEqual(savedValue, value) } func testString() { // Given let value = "a string" // When defaults.set(value, for: .stringKey) // Then let hasKey = defaults.has(.stringKey) XCTAssertTrue(hasKey) let savedValue = defaults.get(for: .stringKey) XCTAssertEqual(savedValue, value) } func testBool() { // Given let value = true // When defaults.set(value, for: .boolKey) // Then let hasKey = defaults.has(.boolKey) XCTAssertTrue(hasKey) let savedValue = defaults.get(for: .boolKey) XCTAssertEqual(savedValue, value) } func testDate() { // Given let value = Date() // When defaults.set(value, for: .dateKey) // Then let hasKey = defaults.has(.dateKey) XCTAssertTrue(hasKey) let savedValue = defaults.get(for: .dateKey) XCTAssertEqual(savedValue, value) } func testEnum() { // Give let value = EnumMock.three // When defaults.set(value, for: .enumKey) // Then let hasKey = defaults.has(.enumKey) XCTAssert(hasKey) let savedValue = defaults.get(for: .enumKey) XCTAssertEqual(savedValue, value) } func testOptionSet() { // Give let value = OptionSetMock.option3 // When defaults.set(value, for: .optionSetKey) // Then let hasKey = defaults.has(.optionSetKey) XCTAssert(hasKey) let savedValue = defaults.get(for: .optionSetKey) XCTAssertEqual(savedValue, value) } func testSet() { // Given let values = [1,2,3,4] // When defaults.set(values, for: .arrayOfIntegersKey) // Then let hasKey = defaults.has(.arrayOfIntegersKey) XCTAssertTrue(hasKey) let savedValues = defaults.get(for: .arrayOfIntegersKey) XCTAssertNotNil(savedValues) savedValues?.forEach({ (value) in XCTAssertTrue(savedValues?.contains(value) ?? false) }) } func testClear() { // Given let values = [1,2,3,4] // When defaults.set(values, for: .arrayOfIntegersKey) defaults.clear(.arrayOfIntegersKey) // Then let hasKey = defaults.has(.arrayOfIntegersKey) XCTAssertFalse(hasKey) let savedValues = defaults.get(for: .arrayOfIntegersKey) XCTAssertNil(savedValues) } func testSetObject() { // Given let child = PersonMock(name: "Anne Greenwell", age: 30, children: []) let person = PersonMock(name: "Bonnie Greenwell", age: 80, children: [child]) // When defaults.set(person, for: .personMockKey) // Then let hasKey = defaults.has(.personMockKey) XCTAssertTrue(hasKey) let savedPerson = defaults.get(for: .personMockKey) XCTAssertEqual(savedPerson?.name, "Bonnie Greenwell") XCTAssertEqual(savedPerson?.age, 80) XCTAssertEqual(savedPerson?.children.first?.name, "Anne Greenwell") XCTAssertEqual(savedPerson?.children.first?.age, 30) } }
mit
b49f66a2b4493b520640fb7dbf9fab5e
25.055794
85
0.568605
4.655675
false
true
false
false
mightydeveloper/swift
test/SILGen/transparent_attribute.swift
7
5646
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | FileCheck %s // Test if 'transparent' atribute gets propagated correctly to apply instructions. // Test that the attribute gets set on default argument generators. @_transparent func transparentFuncWithDefaultArgument (x: Int = 1) -> Int { return x } func useTransparentFuncWithDefaultArgument() ->Int { return transparentFuncWithDefaultArgument(); // CHECK-LABEL: sil hidden @_TF21transparent_attribute37useTransparentFuncWithDefaultArgumentFT_Si // CHECK: apply {{.*}} line:10:44 // CHECK: apply {{.*}} line:10:10 // CHECK: return } func transparentFuncWithoutDefaultArgument (x: Int = 1) -> Int { return x } func useTransparentFuncWithoutDefaultArgument() -> Int { return transparentFuncWithoutDefaultArgument(); // CHECK-LABEL: sil hidden @_TF21transparent_attribute40useTransparentFuncWithoutDefaultArgumentFT_Si // CHECK: apply {{.*}} line:23:47 // CHECK-NOT: transparent // CHECK: apply {{.*}} line:23:10 // CHECK: return } // Make sure the transparent attribute is set on constructors (allocating and initializing). struct StructWithTranspConstructor { @_transparent init () {} } func testStructWithTranspConstructor() -> StructWithTranspConstructor { return StructWithTranspConstructor() // transparent_attribute.StructWithTranspConstructor.constructor // CHECK-APPLY: sil hidden @_TFV21transparent_attribute27StructWithTranspConstructorC // testStructWithTranspConstructor // CHECK-APPLY: _T21transparent_attribute31testStructWithTranspConstructorFT_VS_27StructWithTranspConstructor // CHECK: apply {{.*}} line:38:10 } struct MySt {} var _x = MySt() var x1 : MySt { @_transparent get { return _x } @_transparent set { _x = newValue } } var x2 : MySt { @_transparent set(v) { _x = v } @_transparent get { return _x } } func testProperty(z: MySt) { x1 = z x2 = z var m1 : MySt = x1; var m2 : MySt = x2; // CHECK-APPLY: sil hidden @_TF21transparent_attribute12testPropertyFT1zVS_4MySt_T_ // CHECK: function_ref @_TF21transparent_attributes2x1VS_4MySt // CHECK-NEXT: apply // CHECK: function_ref @_TF21transparent_attributes2x2VS_4MySt // CHECK-NEXT: apply // CHECK: function_ref @_TF21transparent_attributeg2x1VS_4MySt // CHECK-NEXT: apply // CHECK: function_ref @_TF21transparent_attributeg2x2VS_4MySt // CHECK-NEXT: apply } var _tr2 = MySt() var _tr3 = MySt() struct MyTranspStruct {} @_transparent extension MyTranspStruct { init(input : MySt) {} mutating func tr1() {} var tr2: MySt { get { return _tr2 } set { _tr2 = newValue } } } extension MyTranspStruct { @_transparent var tr3: MySt { get { return _tr3 } set { _tr3 = newValue } } } func testStructExtension() { var c : MyTranspStruct = MyTranspStruct(input: _x) c.tr1() var s : MySt = c.tr2 var t : MySt = c.tr3 // CHECK-APPLY: sil hidden @_TF21transparent_attribute13testStructExtensionFT_T_ // CHECK: [[INIT:%[0-9]+]] = function_ref @_TFV21transparent_attribute14MyTranspStructC // CHECK: apply [[INIT]] // CHECK: [[TR1:%[0-9]+]] = function_ref @_TFV21transparent_attribute14MyTranspStruct3tr1 // CHECK: apply [[TR1]] // CHECK: [[TR2:%[0-9]+]] = function_ref @_TFV21transparent_attribute14MyTranspStructg3tr2VS_4MySt // CHECK: apply [[TR2]] // CHECK: [[TR3:%[0-9]+]] = function_ref @_TFV21transparent_attribute14MyTranspStructg3tr3VS_4MySt // CHECK: apply [[TR3]] } enum MyEnum { case onetransp case twotransp } @_transparent extension MyEnum { func tr3() {} } func testEnumExtension() { MyEnum.onetransp.tr3() // CHECK-APPLY: sil hidden @_TF21transparent_attribute17testEnumExtensionFT_T_ // CHECK: [[TR3:%[0-9]+]] = function_ref @_TFO21transparent_attribute6MyEnum3tr3 // CHECK: [[INIT:%[0-9]+]] = function_ref @_TFO21transparent_attribute6MyEnum9onetransp // CHECK: apply [[INIT]] // CHECK: apply [[TR3]] } struct testVarDecl { @_transparent var max: Int { get { return 0xFF } mutating set { max = 0xFF } } func testVarDeclFoo () { var z: Int = max // CHECK-APPLY: sil hidden @_TFV21transparent_attribute11testVarDecl14testVarDeclFoo // CHECK: [[TR4:%[0-9]+]] = function_ref @_TFV21transparent_attribute11testVarDeclg3maxSi // CHECK: apply [[TR4]] } } struct testVarDeclShortenedSyntax { @_transparent static var max: Int { return 0xFF }; func testVarDeclShortenedSyntaxfoo () { var z: Int = testVarDeclShortenedSyntax.max // CHECK-APPLY: sil hidden @_TFV21transparent_attribute26testVarDeclShortenedSyntax29testVarDeclShortenedSyntaxfoo // CHECK: [[TR5:%[0-9]+]] = function_ref @_TZFV21transparent_attribute26testVarDeclShortenedSyntaxg3maxSi // CHECK: apply [[TR5]] } }; @_transparent var transparentOnGlobalVar: Int { get { return 0xFF } } // CHECK: sil hidden [transparent] @_TF21transparent_attributeg22transparentOnGlobalVarSi // Local functions in transparent context have public linkage. @_transparent func foo() { // CHECK-LABEL: sil @_TFF21transparent_attribute3fooFT_T_L_3barFT_T_ : $@convention(thin) () -> () func bar() {} bar() // CHECK-LABEL: sil @_TFF21transparent_attribute3fooFT_T_U_FT_T_ : $@convention(thin) () -> () { let f: () -> () = {} f() // CHECK-LABEL: sil @_TFF21transparent_attribute3fooFT_T_L_3zimFT_T_ : $@convention(thin) () -> () { func zim() { // CHECK-LABEL: sil @_TFFF21transparent_attribute3fooFT_T_L_3zimFT_T_L_4zangFT_T_ : $@convention(thin) () -> () { func zang() { } zang() } zim() }
apache-2.0
b1ef6b930b9fba636059064d0b7a0f94
26.812808
118
0.683847
3.46593
false
true
false
false
XeresRazor/SwiftRaytracer
src/pathtracer/Traceable.swift
1
813
// // Traceable.swift // Raytracer // // Created by David Green on 4/6/16. // Copyright © 2016 David Green. All rights reserved. // import simd public struct HitRecord { var time: Double var point: double4 var normal: double4 var u: Double var v: Double var material: Material? init() { time = 0 point = double4() normal = double4() u = 0.0 v = 0.0 } init(_ t: Double, _ p: double4, _ n: double4, u newU: Double = 0.0, v newV: Double = 0.0) { time = t point = p normal = n u = newU v = newV } } public class Traceable { public func trace(r: Ray, minimumT tMin: Double, maximumT tMax: Double) -> HitRecord? { fatalError("trace() must be overridden") } public func boundingBox(t0: Double, t1: Double) -> AABB? { fatalError("boundingBox() must be overridden") } }
mit
3901606c5fe3f3fd3164eecc1d257691
17.454545
92
0.635468
2.790378
false
false
false
false
zane001/ZMTuan
ZMTuan/Others/PublicClass/Public.swift
1
810
// // Public.swift // ZMTuan // // Created by zm on 4/11/16. // Copyright © 2016 zm. All rights reserved. // import UIKit // 获得RGB颜色 func RGBA(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor { return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } func RGB(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor { return RGBA(r, g: g, b: b, a: 1.0) } let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height // 导航栏的颜色 let navigationBarColor = RGB(33, g: 192, b: 174) // 间隔线的颜色 let separaterColor = RGB(200, g: 199, b: 204) // 经纬度 let LATITUDE_DEFAULT = 39.974487 let LONGITUDE_DEFAULT = 116.412976 // iOS版本 let IOS_VERSION = UIDevice.currentDevice().systemVersion
mit
92e8ccc0c30db9e74f597bbc8a8bdb30
20.942857
73
0.672751
2.819853
false
false
false
false
RockyAo/Dictionary
Dictionary/Classes/Setting/ViewModel/SettingViewModel.swift
1
996
// // SettingViewModel.swift // Dictionary // // Created by Rocky on 2017/6/16. // Copyright © 2017年 Rocky. All rights reserved. // import Foundation import RxSwift import RxCocoa import Action struct SettingViewModel { let versionDriver:Driver<String> fileprivate let service = DatabaseService() init() { versionDriver = Observable.create({ (observer) -> Disposable in let infoDict = Bundle.main.infoDictionary guard let versionNo = infoDict?["CFBundleShortVersionString"] else{ fatalError() } let stringNumber = "\(versionNo)" observer.onNext(stringNumber) observer.onCompleted() return Disposables.create() }) .asDriver(onErrorJustReturn: "") } func clearLocalDataAction() { service.deleteAll() } }
agpl-3.0
b1c728235c6f9d1929bec048e893b40f
20.586957
79
0.543807
5.486188
false
false
false
false
wongzigii/Butterfly
Example/Butterfly-Demo/SettingsViewController.swift
1
1724
// // SettingsViewController.swift // Butterfly-Demo // // Created by Wongzigii on 6/30/15. // Copyright (c) 2015 Wongzigii. All rights reserved. // import UIKit let onLabelText = "Butterfly start listening motion." let offLabelText = "Butterfly end listening motion." class SettingsViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SettingsCell", forIndexPath: indexPath) as! SettingsCell cell.switcher.setOn(self.butterflyIsListening(), animated: false) cell.label.text = self.butterflyIsListening() ? onLabelText : offLabelText return cell } func butterflyIsListening() -> Bool { if ButterflyManager.sharedManager.isListeningShake == true { return true } else { return false } } } class SettingsCell: UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var switcher: UISwitch! @IBAction func swichButtonState(sender: UISwitch) { //var delegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if sender.on == true { ButterflyManager.sharedManager.startListeningShake() self.label.text = onLabelText }else { ButterflyManager.sharedManager.stopListeningShake() self.label.text = offLabelText } } }
mit
cc196c296a734cdd28b2354033486c8a
29.785714
120
0.671694
4.9683
false
false
false
false
samfcmc/Swiftris
Swiftris/Swiftris.swift
1
7020
// // Swiftris.swift // Swiftris // // Created by Samuel Coelho on 10/07/15. // Copyright (c) 2015 Samuel Coelho. All rights reserved. // let NumColumns = 10 let NumRows = 20 // Start location of each shape let StartingColumn = 4 let StartingRow = 0 let PreviewColumn = 12 let PreviouRow = 1 let PointsPerLine = 10 let LevelThreshold = 1000 class Swiftris{ var blockArray: Array2D<Block> var nextShape: Shape? var fallingShape: Shape? var delegate: SwiftrisDelegate? var score: Int var level: Int init() { score = 0 level = 1 fallingShape = nil nextShape = nil blockArray = Array2D<Block>(columns: NumColumns, rows: NumRows) } func beginGame() { if nextShape == nil { nextShape = Shape.random(StartingColumn, startingRow: StartingRow) } delegate?.gameDidBegin(self) } func newShape() -> (fallingShape: Shape?, nextShape: Shape?) { fallingShape = nextShape nextShape = Shape.random(PreviewColumn, startingRow: PreviouRow) fallingShape?.moveTo(StartingColumn, row: StartingRow) if detectIlegalPlacement() { nextShape = fallingShape nextShape!.moveTo(PreviewColumn, row: PreviouRow) endGame() return (nil, nil) } return (fallingShape, nextShape) } func detectIlegalPlacement() -> Bool { if let shape = fallingShape { for block in shape.blocks { if block.column < 0 || block.column >= NumColumns || block.row < 0 || block.row >= NumRows { return true } else if blockArray[block.column, block.row] != nil { return true } } } return false } func dropShape() { if let shape = fallingShape { while detectIlegalPlacement() == false { shape.lowerShapeByOneRow() } shape.raiseShapeByOneRow() delegate?.gameShapeDidDrop(self) } } func letShapeFall() { if let shape = fallingShape { shape.lowerShapeByOneRow() if detectIlegalPlacement() { shape.raiseShapeByOneRow() if detectIlegalPlacement() { endGame() } else { settleShape() } } else { delegate?.gameShapeDidMove(self) if detectTouch() { settleShape() } } } } func rotateShape() { if let shape = fallingShape { shape.rotateClockwise() if detectIlegalPlacement() { shape.roateCounterClockwise() } else { delegate?.gameShapeDidMove(self) } } } func moveShapeLeft() { if let shape = fallingShape { shape.shiftLeftByOneColumn() if detectIlegalPlacement() { shape.shiftRightByOneColumn() return } delegate?.gameShapeDidMove(self) } } func moveShapeRight() { if let shape = fallingShape { shape.shiftRightByOneColumn() if detectIlegalPlacement() { shape.shiftLeftByOneColumn() return } delegate?.gameShapeDidMove(self) } } func settleShape() { if let shape = fallingShape { for block in shape.blocks { blockArray[block.column, block.row] = block } fallingShape = nil delegate?.gameShapeDidLand(self) } } func detectTouch() -> Bool { if let shape = fallingShape { for bottomBlock in shape.bottomBlocks { if bottomBlock.row == NumRows - 1 || blockArray[bottomBlock.column, bottomBlock.row + 1] != nil { return true } } } return false } func endGame() { score = 0 level = 1 delegate?.gameDidEnt(self) } func removeCompletedLines() -> (linesRemoved: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>) { var removedLines = Array<Array<Block>>() for var row = NumRows - 1; row > 0; row-- { var rowOfBlocks = Array<Block>() for column in 0..<NumColumns { if let block = blockArray[column, row] { rowOfBlocks.append(block) } } if rowOfBlocks.count == NumColumns { removedLines.append(rowOfBlocks) for block in rowOfBlocks { blockArray[block.column, block.row] = nil } } } if removedLines.count == 0 { return ([], []) } let pointsEarned = removedLines.count * PointsPerLine * level score += pointsEarned if score >= level * LevelThreshold { level += 1 delegate?.gameDidLevelUp(self) } var fallenBlocks = Array<Array<Block>>() for column in 0..<NumColumns { var fallenBlocksArray = Array<Block>() for var row = removedLines[0][0].row - 1; row > 0; row-- { if let block = blockArray[column, row] { var newRow = row while (newRow < NumRows - 1 && blockArray[column, newRow + 1] == nil) { newRow++ } block.row = newRow blockArray[column, row] = nil blockArray[column, newRow] = block fallenBlocksArray.append(block) } } if fallenBlocksArray.count > 0 { fallenBlocks.append(fallenBlocksArray) } } return (removedLines, fallenBlocks) } func removeAllBlocks() -> Array<Array<Block>> { var allBlocks = Array<Array<Block>>() for row in 0..<NumRows { var rowOfBlocks = Array<Block>() for column in 0..<NumColumns { if let block = blockArray[column, row] { rowOfBlocks.append(block) blockArray[column, row] = nil } } allBlocks.append(rowOfBlocks) } return allBlocks } } protocol SwiftrisDelegate { func gameDidEnt(swiftris: Swiftris) func gameDidBegin(swiftris: Swiftris) func gameShapeDidLand(swiftris: Swiftris) func gameShapeDidMove(swiftris: Swiftris) func gameShapeDidDrop(swiftris: Swiftris) func gameDidLevelUp(swiftris: Swiftris) }
mit
e9642631c5ae88cc57b700acf60cf3b8
27.893004
107
0.503704
5.12035
false
false
false
false
sdrpa/fdps
Sources/FDPClient.swift
1
1764
/** Created by Sinisa Drpa on 2/18/17. FDPS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License or any later version. FDPS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FDPS. If not, see <http://www.gnu.org/licenses/> */ import ATCKit import Foundation import JSON public final class FDPClient { private let socketClient: SocketClient public var flightsUpdate: ((Message.FlightsUpdate) -> Void)? public init(server: String, port: Int) { self.socketClient = SocketClient(server: server, port: Int32(port)) self.socketClient.run { [weak self] readData in guard let jsonObject = try? JSONSerialization.jsonObject(with: readData, options: []) else { return } //print("jsonObject: \(jsonObject)\n\(Date())") guard let json = jsonObject as? JSON, let rawValue = json["messageType"] as? Int, let messageType = MessageType(rawValue: rawValue) else { return } switch messageType { case .flightsUpdate: guard let message = Message.FlightsUpdate(json: json) else { return } self?.flightsUpdate?(message) case .airspaceUpdate: print("Received airspace update") } } } }
gpl-3.0
cc28286bee3492e0475e7a73a78f0640
34.28
104
0.631519
4.716578
false
false
false
false
colemancda/HTTP-Server
Representor/HTTP/HTTPTransition.swift
1
926
public struct HTTPTransition : TransitionType { public typealias Builder = HTTPTransitionBuilder public let uri: String public let method: String public let suggestedContentTypes: [String] public let attributes: InputProperties public let parameters: InputProperties public init(uri: String, attributes: InputProperties? = nil, parameters: InputProperties? = nil) { self.uri = uri self.attributes = attributes ?? [:] self.parameters = parameters ?? [:] self.method = "GET" self.suggestedContentTypes = [] } public init(uri: String, _ build: Builder -> Void) { let builder = Builder() build(builder) self.uri = uri self.attributes = builder.attributes self.parameters = builder.parameters self.method = builder.method self.suggestedContentTypes = builder.suggestedContentTypes } }
mit
35e69edc95bd505be159386f0b0d81e6
25.485714
102
0.657667
4.978495
false
false
false
false
tutsplus/iOSFromScratch-NavigationControllers
Library/AuthorsViewController.swift
1
2476
// // AuthorsViewController.swift // Library // // Created by Bart Jacobs on 06/12/15. // Copyright © 2015 Envato Tuts+. All rights reserved. // import UIKit class AuthorsViewController: UITableViewController { let CellIdentifier = "Cell Identifier" let SegueBooksViewController = "BooksViewController" var authors = [AnyObject]() // MARK: - // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Set Title title = "Authors" let filePath = NSBundle.mainBundle().pathForResource("Books", ofType: "plist") if let path = filePath { authors = NSArray(contentsOfFile: path) as! [AnyObject] } tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == SegueBooksViewController { if let indexPath = tableView.indexPathForSelectedRow, let author = authors[indexPath.row] as? [String: AnyObject] { let destinationViewController = segue.destinationViewController as! BooksViewController destinationViewController.author = author } } } // MARK: - // MARK: Table View Data Source Methods override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return authors.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Dequeue Resuable Cell let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) if let author = authors[indexPath.row] as? [String: AnyObject], let name = author["Author"] as? String { // Configure Cell cell.textLabel?.text = name } return cell; } // MARK: - // MARK: Table View Delegate Methods override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Perform Segue performSegueWithIdentifier(SegueBooksViewController, sender: self) tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
bsd-2-clause
8e0146aeaa44e1cee31828ceebbb031e
32
128
0.648889
5.536913
false
false
false
false
Aufree/ESTMusicIndicator
Example/ESTMusicIndicator/Controllers/MusicListViewController.swift
1
3520
// // MusicListViewController.swift // ESTMusicIndicator // // Created by Aufree on 12/28/15. // Copyright © 2015 The EST Group. All rights reserved. // import UIKit class MusicListViewController: UITableViewController, UIGestureRecognizerDelegate { var indicatorView: ESTMusicIndicatorView! var titles: [String]? var startAnimating: Bool = false var currentNumber = 0 override func viewDidLoad() { super.viewDidLoad() title = "Music indicator demo" titles = ["千尋のワルツ", "You Are My Sunshine", "Valder Fields", "Five Hundred Miles", "Old Memory", "A Little Story", "夢のしずく", "空の欠片", "旅立ちの日に…", "letter song", "Five Hundred Miles", "Old Memory", "A Little Story", "夢のしずく", "空の欠片", "旅立ちの日に…", "letter song"] tableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) createIndicatorView() } func createIndicatorView() { let screenSize: CGRect = UIScreen.main.bounds indicatorView = ESTMusicIndicatorView.init(frame: CGRect(origin: CGPoint(x: (screenSize.width - 50), y: 0), size: CGSize(width: 50, height: 44))) indicatorView.hidesWhenStopped = false indicatorView.tintColor = UIColor.red navigationController?.navigationBar.addSubview(indicatorView) let tap = UITapGestureRecognizer(target: self, action: #selector(MusicListViewController.didTapIndicator(_:))) tap.delegate = self indicatorView.addGestureRecognizer(tap) } @objc func didTapIndicator(_ sender: UITapGestureRecognizer? = nil) { startAnimating = !startAnimating if startAnimating { indicatorView.state = .playing } else { indicatorView.state = .stopped } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles!.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 57; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "musicListCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MusicListCell cell.musicNumber = indexPath.row + 1 cell.musicTitleLabel.text = titles![indexPath.row] cell.state = .stopped if cell.musicNumber == currentNumber { cell.state = .playing } return cell } // MARK: - Table view data delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { updateMusicIndicatorWithIndexPath(indexPath) tableView.deselectRow(at: indexPath, animated: true) } // MARK: - Update music indicator func updateMusicIndicatorWithIndexPath(_ indexPath: IndexPath) { for cell in tableView.visibleCells as! [MusicListCell] { cell.state = .stopped } let musicsCell = tableView.cellForRow(at: indexPath) as! MusicListCell musicsCell.state = .playing currentNumber = indexPath.row } }
mit
b9e95f48301c2a684ed82fbb8ad2f1e7
33.43
261
0.652629
4.808659
false
false
false
false
allbto/WayThere
ios/WayThere/WayThere/Classes/Utils/UIImage+ImageEffects.swift
2
13761
/* File: UIImage+ImageEffects.swift Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. Copyright © 2013 Apple Inc. All rights reserved. WWDC 2013 License NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013 Session. Please refer to the applicable WWDC 2013 Session for further information. IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EA1002 5/3/2013 */ import UIKit import Accelerate public extension UIImage { public func applyLightEffect() -> UIImage? { return applyBlurWithRadius(10, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8) } public func applyExtraLightEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } public func applyDarkEffect() -> UIImage? { return applyBlurWithRadius(4, tintColor: UIColor(white: 0.11, alpha: 0.43), saturationDeltaFactor: 1.8) } public func applyBlurEffect() -> UIImage? { return applyBlurWithRadius(10, tintColor: UIColor.clearColor(), saturationDeltaFactor: 1.8) } public func applyTintEffectWithColor(tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = CGColorGetNumberOfComponents(tintColor.CGColor) if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } public func applyBlurWithRadius(blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. if (size.width < 1 || size.height < 1) { println("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } if self.CGImage == nil { println("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.CGImage == nil { println("*** error: maskImage must be backed by a CGImage: \(maskImage)") return nil } let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) let screenScale = UIScreen.mainScreen().scale let imageRect = CGRect(origin: CGPointZero, size: size) var effectImage = self let hasBlur = blurRadius > __FLT_EPSILON__ let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__ if hasBlur || hasSaturationChange { func createEffectBuffer(context: CGContext) -> vImage_Buffer { let data = CGBitmapContextGetData(context) let width = vImagePixelCount(CGBitmapContextGetWidth(context)) let height = vImagePixelCount(CGBitmapContextGetHeight(context)) let rowBytes = CGBitmapContextGetBytesPerRow(context) return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectInContext = UIGraphicsGetCurrentContext() CGContextScaleCTM(effectInContext, 1.0, -1.0) CGContextTranslateCTM(effectInContext, 0, -size.height) CGContextDrawImage(effectInContext, imageRect, self.CGImage) var effectInBuffer = createEffectBuffer(effectInContext) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectOutContext = UIGraphicsGetCurrentContext() var effectOutBuffer = createEffectBuffer(effectOutContext) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = blurRadius * screenScale var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](count: matrixSize, repeatedValue: 0) for var i: Int = 0; i < matrixSize; ++i { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor)) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() CGContextScaleCTM(outputContext, 1.0, -1.0) CGContextTranslateCTM(outputContext, 0, -size.height) // Draw base image. CGContextDrawImage(outputContext, imageRect, self.CGImage) // Draw effect image. if hasBlur { CGContextSaveGState(outputContext) if let image = maskImage { CGContextClipToMask(outputContext, imageRect, image.CGImage); } CGContextDrawImage(outputContext, imageRect, effectImage.CGImage) CGContextRestoreGState(outputContext) } // Add in color tint. if let color = tintColor { CGContextSaveGState(outputContext) CGContextSetFillColorWithColor(outputContext, color.CGColor) CGContextFillRect(outputContext, imageRect) CGContextRestoreGState(outputContext) } // Output image is ready. let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } }
mit
1fecfddeee6393d0b7f45d1f5f719614
46.608997
205
0.663323
5.16054
false
false
false
false
kuangniaokuang/Cocktail-Pro
smartmixer/smartmixer/UserCenter/HistoryCell.swift
2
1295
// // HistoryCell.swift // smartmixer // // Created by 姚俊光 on 14/10/5. // Copyright (c) 2014年 smarthito. All rights reserved. // import UIKit //自定义一个搜索设置完毕开始搜索的消息 protocol HistoryCellDelegate:NSObjectProtocol{ func historyCell(sender:HistoryCell) func historyCell(sender:HistoryCell,show ShowCell:Bool) } class HistoryCell: UITableViewCell,UIScrollViewDelegate { //需要显示的图标 @IBOutlet var thumb:UIImageView! //需要显示的物品名字 @IBOutlet var name:UILabel! //需要显示的时间 @IBOutlet var time:UILabel! //滚动视图 @IBOutlet var scroll:UIScrollView! var delegate:HistoryCellDelegate! @IBAction func deleteitem(sender:UIButton){ if(delegate != nil){ self.delegate.historyCell(self) } } @IBAction func resetScroll(sender:UIButton){ if(scroll != nil){ if(scroll.contentOffset.x==0){ if(delegate != nil){ self.delegate.historyCell(self,show:true) } }else{ scroll.contentOffset.x = 0 } }else if(delegate != nil){ self.delegate.historyCell(self,show:true) } } }
apache-2.0
dc2ea45debf7789050e723ab76dc30fc
22.470588
61
0.599833
4.016779
false
false
false
false
nathawes/swift
test/attr/attr_native_dynamic.swift
15
13469
// RUN: %target-swift-frontend -swift-version 5 -typecheck -dump-ast %s | %FileCheck %s struct Strukt { // CHECK: (struct_decl {{.*}} "Strukt" // CHECK: (var_decl {{.*}} "dynamicStorageOnlyVar" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored readWriteImpl=stored // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=dynamicStorageOnlyVar // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=dynamicStorageOnlyVar // CHECK: (accessor_decl {{.*}} access=internal _modify_for=dynamicStorageOnlyVar dynamic var dynamicStorageOnlyVar : Int = 0 // CHECK: (var_decl {{.*}} "computedVar" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar dynamic var computedVar : Int { return 0 } // CHECK: (var_decl {{.*}} "computedVar2" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar2 dynamic var computedVar2 : Int { get { return 0 } } // CHECK: (var_decl {{.*}} "computedVarGetterSetter" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterSetter // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarGetterSetter // CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarGetterSetter dynamic var computedVarGetterSetter : Int { get { return 0 } set { } } // CHECK: (var_decl {{.*}} "computedVarGetterModify" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterModify // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarGetterModify // CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarGetterModify dynamic var computedVarGetterModify : Int { get { return 0 } _modify { } } // CHECK: (var_decl {{.*}} "computedVarReadSet" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadSet // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarReadSet // CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadSet // CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarReadSet dynamic var computedVarReadSet : Int { _read { } set { } } // CHECK: (var_decl {{.*}} "computedVarReadModify" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadModify // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarReadModify // CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadModify // CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarReadModify dynamic var computedVarReadModify : Int { _read { } _modify { } } // CHECK: (var_decl {{.*}} "storedWithObserver" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored_with_observers readWriteImpl=stored_with_didset // CHECK: (accessor_decl {{.*}}access=private dynamic didSet_for=storedWithObserver // CHECK: (accessor_decl {{.*}}access=internal dynamic get_for=storedWithObserver // CHECK: (accessor_decl {{.*}}access=internal set_for=storedWithObserver // CHECK: (accessor_decl {{.*}}access=internal _modify_for=storedWithObserver dynamic var storedWithObserver : Int { didSet { } } // CHECK: (func_decl {{.*}} access=internal dynamic dynamic func aMethod(arg: Int) -> Int { return arg } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:) dynamic subscript(_ index: Int) -> Int { get { return 1 } set { } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:) dynamic subscript(_ index: Float) -> Int { get { return 1 } _modify { } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:) dynamic subscript(_ index: Double) -> Int { _read { } _modify { } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:) dynamic subscript(_ index: Strukt) -> Int { _read { } set { } } } class Klass { // CHECK: (class_decl {{.*}} "Klass" // CHECK: (var_decl {{.*}} "dynamicStorageOnlyVar" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored readWriteImpl=stored // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=dynamicStorageOnlyVar // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=dynamicStorageOnlyVar // CHECK: (accessor_decl {{.*}} access=internal _modify_for=dynamicStorageOnlyVar dynamic var dynamicStorageOnlyVar : Int = 0 // CHECK: (var_decl {{.*}} "computedVar" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar dynamic var computedVar : Int { return 0 } // CHECK: (var_decl {{.*}} "computedVar2" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar2 dynamic var computedVar2 : Int { get { return 0 } } // CHECK: (var_decl {{.*}} "computedVarGetterSetter" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterSetter // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarGetterSetter // CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarGetterSetter dynamic var computedVarGetterSetter : Int { get { return 0 } set { } } // CHECK: (var_decl {{.*}} "computedVarGetterModify" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterModify // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarGetterModify // CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarGetterModify dynamic var computedVarGetterModify : Int { get { return 0 } _modify { } } // CHECK: (var_decl {{.*}} "computedVarReadSet" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadSet // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarReadSet // CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadSet // CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarReadSet dynamic var computedVarReadSet : Int { _read { } set { } } // CHECK: (var_decl {{.*}} "computedVarReadModify" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadModify // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarReadModify // CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadModify // CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarReadModify dynamic var computedVarReadModify : Int { _read { } _modify { } } // CHECK: (func_decl {{.*}} "aMethod(arg:)" {{.*}} access=internal dynamic dynamic func aMethod(arg: Int) -> Int { return arg } // CHECK-NOT: (func_decl {{.*}} "anotherMethod()" {{.*}} access=internal{{.*}} dynamic func anotherMethod() -> Int { return 3 } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=mutable_addressor readWriteImpl=mutable_addressor // CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:) dynamic subscript(_ index: Int) -> Int { unsafeAddress { fatalError() } unsafeMutableAddress { fatalError() } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=mutable_addressor readWriteImpl=mutable_addressor // CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:) dynamic subscript(_ index: Float) -> Int { get { return 1 } unsafeMutableAddress { fatalError() } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=mutable_addressor readWriteImpl=mutable_addressor // CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:) dynamic subscript(_ index: Double) -> Int { _read { } unsafeMutableAddress { fatalError() } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=setter readWriteImpl=materialize_to_temporary // CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:) dynamic subscript(_ index: Int8) -> Int { unsafeAddress { fatalError() } set { } } // CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=modify_coroutine readWriteImpl=modify_coroutine // CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:) // CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:) dynamic subscript(_ index: Int16) -> Int { unsafeAddress { fatalError() } _modify { } } } class SubKlass : Klass { // CHECK: (class_decl {{.*}} "SubKlass" // CHECK: (func_decl {{.*}} "aMethod(arg:)" interface type='(SubKlass) -> (Int) -> Int' access=internal {{.*}} dynamic override dynamic func aMethod(arg: Int) -> Int { return 23 } // CHECK: (func_decl {{.*}} "anotherMethod()" interface type='(SubKlass) -> () -> Int' access=internal {{.*}} dynamic override dynamic func anotherMethod() -> Int { return 23 } }
apache-2.0
d69d87c4d128db9daff00f23a61575ac
44.350168
190
0.67867
4.11896
false
false
false
false
a2/Gulliver
Gulliver/Source/Types/AddressBook.swift
1
7325
import AddressBook import Foundation import Lustre public func localizedLabel(label: String) -> String? { if let value = ABAddressBookCopyLocalizedLabel(label) { return value.takeRetainedValue() as String } else { return nil } } public func systemAddressBook() -> ObjectResult<AddressBook> { var error: Unmanaged<CFErrorRef>? = nil if let addressBook = ABAddressBookCreateWithOptions(nil, &error) { return success(AddressBook(state: addressBook.takeRetainedValue())) } else if let error = error { return failure(error.takeUnretainedValue()) } else { return failure("An unknown error occurred.") } } public final class AddressBook: AddressBookType { public typealias RecordState = ABRecordRef public typealias PersonState = ABRecordRef public typealias GroupState = ABRecordRef public typealias SourceState = ABRecordRef private class Observer: ExternalChangeObserver { var handler: (Void -> Void)? init(handler: Void -> Void) { self.handler = handler } deinit { assert(handler == nil, "AddressBook observer was not unregistered before deinitialization") } func stopObserving() { handler?() handler = nil } } public let state: ABAddressBookRef public init(state: ABAddressBookRef) { self.state = state } public static var authorizationStatus: AuthorizationStatus { return AuthorizationStatus(rawValue: ABAddressBookGetAuthorizationStatus())! } public func requestAccess(completionHandler: VoidResult -> Void) { ABAddressBookRequestAccessWithCompletion(state) { hasAccess, error in if hasAccess { completionHandler(success()) } else if let error = error { completionHandler(failure(error)) } else { completionHandler(failure("An unknown error occurred.")) } } } public var hasUnsavedChanges: Bool { return ABAddressBookHasUnsavedChanges(state) } public func save() -> VoidResult { var error: Unmanaged<CFErrorRef>? = nil if ABAddressBookSave(state, &error) { return success() } else if let error = error { return failure(error.takeUnretainedValue()) } else { return failure("An unknown error occurred.") } } @asmname("_GLVAddressBookRegisterExternalChangeHandler") private func RegisterExternalChangeHandler(addressBook: ABAddressBook, _ block: @objc_block (info: [NSObject : AnyObject]?) -> Void) -> Void -> Void public func observeExternalChanges(callback: ExternalChangeHandler) -> ExternalChangeObserver { let handler = RegisterExternalChangeHandler(state, callback) return Observer(handler: handler) } public func addRecord<R: _RecordType where R.State == RecordState>(record: R) -> VoidResult { var error: Unmanaged<CFErrorRef>? = nil if ABAddressBookAddRecord(state, record.state, &error) { return success() } else if let error = error { return failure(error.takeUnretainedValue()) } else { return failure("An unknown error occurred.") } } public func removeRecord<R: _RecordType where R.State == RecordState>(record: R) -> VoidResult { var error: Unmanaged<CFErrorRef>? = nil if ABAddressBookRemoveRecord(state, record.state, &error) { return success() } else if let error = error { return failure(error.takeUnretainedValue()) } else { return failure("An unknown error occurred.") } } // MARK: - People public var personCount: Int { return ABAddressBookGetPersonCount(state) } public func person<P: _PersonType where P.State == PersonState>(recordID: RecordID) -> P? { if let record = ABAddressBookGetPersonWithRecordID(state, recordID) { return P(state: record.takeUnretainedValue()) } else { return nil } } public func people<P: _PersonType where P.State == PersonState>(name: String) -> [P] { if let people = ABAddressBookCopyPeopleWithName(state, name) { let states = people.takeRetainedValue() as [ABRecordRef] return states.map({ P(state: $0) }) } else { return [] } } public func allPeople<P: _PersonType, S: _SourceType where P.State == PersonState, S.State == SourceState>(source: S) -> [P] { if let people = ABAddressBookCopyArrayOfAllPeopleInSource(state, source.state) { let records = people.takeRetainedValue() as [ABRecordRef] return records.map({ P(state: $0) }) } else { return [] } } public func allPeople<P: _PersonType, S: _SourceType where P.State == PersonState, S.State == SourceState>(source: S, sortOrdering: SortOrdering) -> [P] { if let people = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(state, source.state, sortOrdering.rawValue) { let states = people.takeRetainedValue() as [ABRecordRef] return states.map({ P(state: $0) }) } else { return [] } } // MARK: - Groups public var groupCount: Int { return ABAddressBookGetGroupCount(state) } public func group<G: _GroupType where G.State == GroupState>(recordID: RecordID) -> G? { if let record = ABAddressBookGetGroupWithRecordID(state, recordID) { return G(state: record.takeUnretainedValue()) } else { return nil } } public func allGroups<G: _GroupType where G.State == GroupState>() -> [G] { if let array = ABAddressBookCopyArrayOfAllGroups(state) { let groups = array.takeRetainedValue() as [ABRecordRef] return groups.map({ G(state: $0) }) } else { return [] } } public func allGroups<G: _GroupType, S: _SourceType where G.State == GroupState, S.State == SourceState>(source: S) -> [G] { if let records = ABAddressBookCopyArrayOfAllGroupsInSource(state, source.state) { let array = records.takeRetainedValue() as [ABRecordRef] return array.map({ G(state: $0) }) } else { return [] } } // MARK: - Sources public func defaultSource<S: _SourceType where S.State == SourceState>() -> S { let sourceState: ABRecordRef = ABAddressBookCopyDefaultSource(state).takeRetainedValue() return S(state: sourceState) } public func source<S: _SourceType where S.State == SourceState>(recordID: RecordID) -> S? { if let record = ABAddressBookGetSourceWithRecordID(state, recordID) { return S(state: record.takeUnretainedValue()) } else { return nil } } public func allSources<S: _SourceType where S.State == SourceState>() -> [S] { if let array = ABAddressBookCopyArrayOfAllSources(state) { let states = array.takeRetainedValue() as [ABRecordRef] return states.map({ S(state: $0) }) } else { return [] } } }
mit
b2d802434b3368b634a2315d9f61a42b
33.880952
158
0.619113
4.707584
false
false
false
false
QuaereVeritatem/TopHackIncStartup
TopHackIncStartUp/HomeViewController.swift
1
16490
// // HomeViewController.swift // //TophackIncEvent a.k.a. TechBolt // // Created by Robert Martin on 9/4/16. // Copyright © 2016 Robert Martin. All rights reserved. //TableView and custom TableviewCell Demo //TechCommunity tracker.. include website clickable link and date for events (or say year round) //Top Hackathons,Incubators,accelerators,bootcamps that programmers should know about //**** New Name: 'TechBolt' - connecting tech proffesionals to the events you care about //problems here: edit button and swipe to delete dont work ******* import UIKit //work on further increasing design as well..nav bar on homepage and double reload of homepage from table //make sure to put in comments before I upload to github //make sure indentations all matchup and are consistent //fix bugs class HomeViewController: UIViewController, UITableViewDataSource { var backEndlessUltraTopHack: [BackendlessTopHack] = [] // an array of a class var BackTopHack: BackendlessTopHack = BackendlessTopHack() var backEndlessUltraHackEvent = EventData.sharedInstance.besthackIncEvent //an array of hackIncEvent //var whereThePhotosAt: HackIncStartUp = HackIncStartUp() @IBOutlet weak var tableView: UITableView! @IBAction func addEvents(_ sender: UIBarButtonItem) { //already setup to go to next VC } @IBAction func editCurrentEvents(_ sender: UIBarButtonItem) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Use the edit button item provided by the table view controller. navigationItem.leftBarButtonItem = editButtonItem //if backendless data is nil then load example data // if (Backendless.sharedInstance().persistenceService.of(BackendlessTopHack.ofClass()) != nil) { //user not logged in (**user will always be logged in at this page!!!!!!!!!!!!!) if BackendlessManager.sharedInstance.isUserLoggedIn() { if backEndlessUltraTopHack.isEmpty { //load sample events into backendless //save each event as an event in backendless var index = 0 for i in backEndlessUltraHackEvent { BackTopHack.EventName = i.name print("Event name is \(BackTopHack.EventName)") BackTopHack.EventProgramType = i.progType.map { $0.rawValue } BackTopHack.Website = i.progUrl BackTopHack.EventAreaLoc = i.areaLoc.map { $0.rawValue } BackTopHack.EventLogo = i.logo BackTopHack.EventDate = i.dateOrTimeFrame.map { $0.rawValue } //to store a name(email) of user ***change this ASAP!!!! (needs to be backendless...email) BackTopHack.name = BackendlessManager.sharedInstance.EMAIL //this is to create a unique objectID to store event in backendless with let uuid = NSUUID().uuidString BackTopHack.objectId = uuid //must save logo picture in backend as well backEndlessUltraTopHack.append(BackTopHack) index = index + 1 }//end of for loop }//end of is backendlessTopHack empty // MARK : Problem here - JSON not serializing //trying NEW WAY NOW if let json = BackTopHack.toJSON() { print("The json thats been serialized from BackTopHack is \(json)") } // JSONParse.sharedInstance.makeJSON(array: backEndlessUltraTopHack) //now save it to backendless persistent save spot /* Backendless.sharedInstance().data.save( backEndlessUltraTopHack, response: { (entity: Any?) -> Void in let Event = entity as! BackendlessTopHack print("PersonOrEvent: \(Event.objectId!), PersonOrEvent: \(Event.name), photoUrl: \"\(Event.photoUrl!)") }, error: { (fault: Fault?) -> Void in print("PersonOrEvent failed to save: \(fault)") } ) */ // MARK: Problem starts here //backendless != nil so load backendless BackendlessManager.sharedInstance.loadEvents( completion: { _ in Backendless.sharedInstance().persistenceService.of(BackendlessTopHack.ofClass()) } ) // Add support for pull-to-refresh on the table view.(not really needed though) //self.refreshControl?.addTarget(self, action: #selector(refresh(sender:)), for: UIControlEvents.valueChanged) }//end of is user logged in }//end of function func refresh(sender: AnyObject) { // //if BackendlessManager.sharedInstance.isUserLoggedIn() { // // // BackendlessManager.sharedInstance.loadEvents( // // completion: { mealData in // // self.meals = mealData // self.tableView.reloadData() // self.refreshControl?.endRefreshing() // }, // // error: { // self.tableView.reloadData() // self.refreshControl?.endRefreshing() // } //) // //} } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //makes editing possible on table view (slides screen over to show minus signs) override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // print("numberOfRowsInSection, the count is \(EventData.sharedInstance.besthackIncEvent.count)") //return EventData.sharedInstance.besthackIncEvent.count print("numberOfRowsInSection, the new count is \(backEndlessUltraTopHack.count)") return EventData.sharedInstance.besthackIncEvent.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! TopCell let row = (indexPath as NSIndexPath).row cell.nameLabel.text = EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].name // cell.nameLabel.text = backEndlessUltraTopHack[(indexPath as NSIndexPath).row].EventName //the rest of these are optionals (check for nil) //program type portion of cell needs data from besthackIncEvent..data is of weird types for these 3 if EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].progType != nil { //this doesnt print just the string literal: find a way to pull string out of output cell.progType.text = String(describing: EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].progType!) } else { cell.progType.text = "" } if EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].areaLoc != nil { cell.locationLabel.text = String(describing: EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].areaLoc!) } else { cell.locationLabel.text = "" } if EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].dateOrTimeFrame != nil { cell.rankingLabel.text = String(describing: EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].dateOrTimeFrame!) //rankingLabel is date label name } else { cell.rankingLabel.text = "" } //loading picture/logo // if EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].logo != nil { if indexPath.row > 10 { //gonna grab first 11 from eventdata, the other pics from loadImage // if backEndlessUltraTopHack[indexPath.row].thumbnailUrl != nil { // MARK: This line needs to call HackIncStartUp for thumbnail image with name..backEndlessUltraTopHack[indexPath.row].thumbnailUrl! (and notsaving thumbnails??) // loadImageFromUrl(cell: TopCell(), thumbnailUrl: backEndlessUltraTopHack[indexPath.row].thumbnailUrl!) loadImageFromUrl(cell: TopCell(), thumbnailUrl: "https://api.backendless.com/c28e4e1c-8c05-7a6b-ff1f-47592cafb000/v1/files/photos/046E5C21-7271-21E1-FFDB-4970E6A83B00/thumb_3FBFE09F-A344-45ED-B1D0-7F9C72868DF8.jpg") //print("loadImageFromUrl backendless top hack is \(backEndlessUltraTopHack[indexPath.row].thumbnailUrl!)") } else { cell.IncAccHackPic.image = UIImage(named: EventData.sharedInstance.besthackIncEvent[(indexPath as NSIndexPath).row].logo!)} /* } else { cell.IncAccHackPic.image = UIImage(named: "defaultLogo1") } */ var shortUrl: String = EventData.sharedInstance.besthackIncEvent[row].progUrl! // MARK : Problem website not showing is here //test for nil ***if NO https/http is entered by user, website isnt shown on cell-FIX! if EventData.sharedInstance.besthackIncEvent[row].progUrl != nil { let fullUrl = EventData.sharedInstance.besthackIncEvent[row].progUrl cell.websiteUrl = fullUrl // If the URL has "http://" or "https://" in it - remove it! if fullUrl!.lowercased().range(of: "http://") != nil { shortUrl = fullUrl!.replacingOccurrences(of: "http://", with: "") } else if fullUrl!.lowercased().range(of: "https://") != nil { shortUrl = fullUrl!.replacingOccurrences(of: "https://", with: "") } } else { //website entered is nil let fullUrl = EventData.sharedInstance.besthackIncEvent[row].progUrl cell.websiteUrl = fullUrl shortUrl = "" } //if shortUrl == fullUrl then dont show text as a hyperlink!!!! ******* cell.websiteBtn.setTitle(shortUrl, for: UIControlState()) return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { // if editingStyle == .delete { if (editingStyle == UITableViewCellEditingStyle.delete) { if BackendlessManager.sharedInstance.isUserLoggedIn() { // Find the EventData(old MealData) in the data source that we wish to delete. // let mealToRemove = meals[indexPath.row] // var ETR = [BackendlessTopHack]() // MARK : Crashes to here when deleting events ******* // let EventToRemove = ETR[indexPath.row] EventData.sharedInstance.besthackIncEvent.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) //this has to be of type BackendlessTopHack(persontoremove) /* BackendlessManager.sharedInstance.removeEvent(EventToRemove: EventToRemove, completion: { // It was removed from the database, now delete the row from the data source. EventData.sharedInstance.besthackIncEvent.remove(at: (indexPath as NSIndexPath).row) //tableView.deleteRows(at: [indexPath], with: .fade) //animation looks better tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) }, error: { // It was NOT removed - tell the user and DON'T delete the row from the data source. let alertController = UIAlertController(title: "Remove Failed", message: "Oops! We couldn't remove your Event at this time.", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } ) //end of parameter */ } else{ // Delete the row from the data source EventData.sharedInstance.besthackIncEvent.remove(at: (indexPath as NSIndexPath).row) // Save the meals.(events) // saveMealsToArchiver() tableView.deleteRows(at: [indexPath], with: .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 } } @nonobjc func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { if (self.tableView.isEditing) { return UITableViewCellEditingStyle.delete } return UITableViewCellEditingStyle.none } func loadImageFromUrl(cell: TopCell, thumbnailUrl: String) { let url = URL(string: thumbnailUrl)! let session = URLSession.shared let task = session.dataTask(with: url, completionHandler: { (data, response, error) in if error == nil { do { let data = try Data(contentsOf: url, options: []) DispatchQueue.main.async { // We got the image data! Use it to create a UIImage for our cell's // UIImageView. Then, stop the activity spinner. cell.IncAccHackPic.image = UIImage(data: data) //cell.activityIndicator.stopAnimating() } } catch { print("NSData Error: \(error)") } } else { print("NSURLSession Error: \(error)") } }) task.resume() } //generic function that can compare two values regardless of type! func areValuesEqual<T: Equatable>(firstValue: T, secondValue: T) -> Bool { return firstValue == secondValue } //this function will iterate through an array and find and return the element equal to the second value func compareAllValuesInArray<T: Equatable>(firstValue: [T], secondValue: T) -> String { for i in firstValue { if secondValue == i { return i as! String } } return "no elements are equal to the second Value" } //this variable gets the quotes part of the EventData.sharedInstance.besthackIncEvent variable func gettingTheQuotesPart<T: Equatable>(variable: T) -> String { var quotePart = "" var fullPart = variable return quotePart } }
mit
bc3e0a304ae4b53d3d8f8c5d03399100
44.424242
227
0.578992
5.170586
false
false
false
false
PREAlbert/rulerSwift
rulerSwift/rulerView.swift
2
6128
// // rulerView.swift // rulerSwift // // Created by Albert on 16/6/4. // Copyright © 2016年 Albert. All rights reserved. // import UIKit @objc protocol FSRulerDelegate { //声明方法 @objc optional func fsRuler(_ rulerScrollView: FSRulerScrollView) } class rulerView: UIView, FSRulerDelegate, UIScrollViewDelegate { weak var delegete: FSRulerDelegate? var rulerScrollView: FSRulerScrollView? let DISTANCELEFTANDRIGHT :CGFloat = 8 //标尺左右距离 let DISTANCEVALUE: CGFloat = 8 //刻度实际长度 let DISTANCETOPANDBOTTOM: CGFloat = 20 //标尺上下距离 override init(frame: CGRect) { super.init(frame: frame); self.rulerScrollView = self.getRulerScrollView() self.rulerScrollView?.rulerHeight = NSInteger(frame.size.height) self.rulerScrollView?.rulerWidth = NSInteger(frame.size.width) // self.rulerScrollView?.rulerWidth = CGFloat } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)!; fatalError("init(coder:) has not been implemented") } /* * count * average = 刻度最大值 * @param count 10个小刻度为一个大刻度,大刻度的数量 * @param average 每个小刻度的值,最小精度 0.1 * @param currentValue 直尺初始化的刻度值 * @param mode 是否最小模式 */ func showRulerScrollViewWithCount(_ count: NSInteger, average: NSNumber, currentValue: Float, smallMode: Bool) { self.rulerScrollView?.rulerAverage = average self.rulerScrollView?.rulerCount = count self.rulerScrollView?.rulerValue = currentValue self.rulerScrollView?.mode = smallMode self.rulerScrollView?.drawRuler() self.addSubview(self.rulerScrollView!) self.drawline() } func drawline() { let pathLine: CGMutablePath = CGMutablePath() let shapeLayerLine: CAShapeLayer = CAShapeLayer.init() shapeLayerLine.strokeColor = UIColor.red().cgColor shapeLayerLine.fillColor = UIColor.red().cgColor shapeLayerLine.lineWidth = 1.0 shapeLayerLine.lineCap = kCALineCapSquare pathLine.moveTo(nil, x: self.frame.size.width / 2, y: self.frame.size.height - DISTANCETOPANDBOTTOM - 20) pathLine.addLineTo(nil, x: self.frame.size.width / 2, y: DISTANCETOPANDBOTTOM + 8) shapeLayerLine.path = pathLine self.layer.addSublayer(shapeLayerLine) } func getRulerScrollView() -> FSRulerScrollView { let scrollView: FSRulerScrollView = FSRulerScrollView(frame: CGRect.zero) scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false return scrollView } //MARK: ScrollView Delegete func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollView: FSRulerScrollView = (scrollView as? FSRulerScrollView)! let offSetX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT let rulerValue: Float = Float(offSetX / DISTANCEVALUE) * (scrollView.rulerAverage?.floatValue)! if rulerValue < 0 { return } else if (rulerValue > Float(scrollView.rulerCount!) * (scrollView.rulerAverage?.floatValue)!) { return } if ((self.delegete) != nil) { if ((scrollView.mode) != nil) { scrollView.rulerValue = rulerValue } scrollView.mode = false self.delegete?.fsRuler!(scrollView) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.animationRebound((scrollView as? FSRulerScrollView)!) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.animationRebound((scrollView as? FSRulerScrollView)!) } func animationRebound(_ scrollView: FSRulerScrollView) { let offSetX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT var oX = CGFloat(offSetX / DISTANCEVALUE) * CGFloat((scrollView.rulerAverage)!) if (self.valueIsInteger(number: scrollView.rulerAverage!)) { oX = self.notRounding(price: oX, afterPoint: 0) } else { oX = self.notRounding(price: oX, afterPoint: 1) } let offX = (oX / CGFloat((scrollView.rulerAverage?.floatValue)!)) * DISTANCEVALUE + DISTANCELEFTANDRIGHT - self.frame.size.width / 2 UIView.animate(withDuration: 0.2) { () -> Void in scrollView.contentOffset = CGPoint(x: offX, y: 0) } scrollView.contentOffset = CGPoint(x: offX, y: 0) } //MARK: ToolMethod func notRounding(price: CGFloat, afterPoint: NSInteger) -> CGFloat{ let roundingBehavior: NSDecimalNumberHandler = NSDecimalNumberHandler.init(roundingMode: NSDecimalNumber.RoundingMode.roundPlain, scale: Int16(afterPoint), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) let ouncesDecimal: NSDecimalNumber = NSDecimalNumber.init(value: Int(price)) let roundedOunces: NSDecimalNumber = ouncesDecimal.rounding(accordingToBehavior: roundingBehavior) return CGFloat(roundedOunces.floatValue) } func valueIsInteger(number: NSNumber) -> Bool { let value: NSString = String(format: "%f",number.floatValue) if value.length > 0 { let stringArray: NSArray = value.components(separatedBy: ".") let valueEnd: NSString = stringArray.object(at: 1) as! NSString var temp: String let count: NSInteger = valueEnd.length for index in 0...count { temp = valueEnd.substring(with: NSRange.init(location: index, length: 1)) if temp == "0" { return false } } } return true } }
mit
5c2465586a04946d2fb08bf75d6595a0
35.260606
265
0.635467
4.35444
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Stack/739_Daily Temperatures.swift
1
2588
// 739_Daily Temperatures // https://leetcode.com/problems/daily-temperatures/ // // Created by Honghao Zhang on 10/20/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. // // 给出每天的气温,找出每天需要等多少天才能更暖和 import Foundation class Num739 { // MARK: - 用Stack // 还是从后向前扫描,用stack来保持一个比当前气温大的数组(stack存的是index) // 每次添加新的气温时,把比它小的气温都pop掉 func dailyTemperatures_Stack(_ T: [Int]) -> [Int] { var higherTempIndexStack: [Int] = [] var answer: [Int] = Array(repeating: 0, count: T.count) for i in (0..<T.count).reversed() { let currentTemp = T[i] while !higherTempIndexStack.isEmpty { let next = T[higherTempIndexStack.last!] if next <= currentTemp { higherTempIndexStack.removeLast() } else { break } } // now higher temp stack stores the next higher temp answer[i] = (higherTempIndexStack.last ?? i) - i higherTempIndexStack.append(i) } return answer } // MARK: - 从后向前扫描,用next来存后面的气温 // 因为已知气温范围,对于每天的气温,去next里查更高气温的index,并记录最小的天数 func dailyTemperatures(_ T: [Int]) -> [Int] { var result: [Int] = Array(repeating: 0, count: T.count) // temp to index var next: [Int] = Array(repeating: -1, count: 101) for i in (0..<T.count).reversed() { let currentTemp = T[i] var days = Int.max // find the next warmer temp // if this is the highest temp, continue if currentTemp == 100 { next[T[i]] = i continue } else { for temp in (currentTemp + 1)...100 { if next[temp] > i { days = min(next[temp] - i, days) } } // If there's no future warmer day if days != Int.max { result[i] = days } } next[T[i]] = i } return result } }
mit
453908f4e08aedf4f26df66664037b5c
27.597561
236
0.602132
3.266017
false
false
false
false
justbaum30/NoteifyMe
NoteifyMe/EditNoteViewController.swift
1
2838
// // EditNoteViewController.swift // NoteifyMe // // Created by Justin Baumgartner on 1/5/15. // Copyright (c) 2015 Justin Baumgartner. All rights reserved. // import UIKit import NoteifyMeCommons class EditNoteViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { // MARK: Properties var editingNote: Note? let colorArray = ["Gray", "Blue", "Green", "Orange", "Yellow", "Red"] @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var contentTextView: UITextView! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var colorPicker: UIPickerView! // MARK: Lifecycle methods override func viewDidLoad() { super.viewDidLoad() styleTextView() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) setupEditMode() } // MARK: Actions @IBAction func saveNote(sender: AnyObject) { if (editingNote == nil) { let note = Note(title: titleTextField.text, content: contentTextView.text, date: datePicker.date, color: Note.Color(rawValue: colorPicker.selectedRowInComponent(0))!) NoteBusinessService.addNote(note) } else { editingNote?.title = titleTextField.text editingNote?.content = contentTextView.text editingNote?.date = datePicker.date editingNote?.color = Note.Color(rawValue: colorPicker.selectedRowInComponent(0))! NoteBusinessService.saveNote(editingNote!) } navigationController?.popViewControllerAnimated(true) } @IBAction func cancel(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) } // MARK: UIPickerView func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return colorArray.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return colorArray[row] } // MARK: Private helper methods private func setupEditMode() { if let note = editingNote { titleTextField.text = note.title contentTextView.text = note.content datePicker.date = note.date colorPicker.selectRow(note.color.rawValue, inComponent: 0, animated: false) } } private func styleTextView() { contentTextView.layer.borderColor = UIColor(red: 0xe8/255.0, green: 0xe8/255.0, blue: 0xe8/255.0, alpha: 1.0).CGColor contentTextView.layer.borderWidth = 1.0 contentTextView.layer.cornerRadius = 5.0 } }
mit
0cae61a228d2f3d9a540ed1baf01559b
30.533333
178
0.650106
4.927083
false
false
false
false
openbuild-sheffield/jolt
Sources/OpenbuildExtensionPerfect/struct.RequestValidationTypeString.swift
1
3346
import Foundation import OpenbuildExtensionCore public struct RequestValidationTypeString: RequestValidationString { public var min: Int? public var max: Int? public var regex: String? public var email: Bool? public var isString: String? public init(){} //Used for validating something exists... public init(isString: String){ self.isString = isString } public init(email: Bool){ self.email = email } public init(min: Int, max: Int){ self.min = min self.max = max } public init(regex: String){ self.regex = regex } public init(min: Int, max: Int, regex: String){ self.min = min self.max = max self.regex = regex } public func validate(value: Any?, required: Bool) -> [String: Any] { var errors: [String: Any] = [:] if value == nil && required { errors["required"] = "Is a required value." } if value != nil { var isString = false var realString: String? = nil if let stringValue = value! as? String { isString = true realString = stringValue } if isString { if self.min != nil && realString!.characters.count < self.min! { errors["min"] = "Should be equal to \(self.min!) characters or higher." } if self.max != nil && realString!.characters.count > self.max! { errors["max"] = "Should be equal to \(self.max!) characters or lower." } if self.regex != nil && (realString! !=~ self.regex!) { errors["regex"] = "Should match \(self.regex!)." } if self.email != nil && self.email! == true { if realString!.isEmail == false { errors["email"] = "Should be a valid email address." } } if self.isString != nil && (realString! != self.isString!) { errors["match"] = "Should be equal to '\(self.isString!)'" } } else { errors["is_string"] = "Should be a string." } } return errors } public func cast(value: Any?) -> String?{ if value == nil { return nil } if let stringValue = value! as? String { if self.email != nil && self.email! == true { return stringValue.lowercased() } else { return stringValue } } return nil } public func describeRAML() -> [String] { var description = [String]() //FIXME / TODO ? email is not a valid type but.... if self.email != nil && self.email! { description.append("type: email") } else { description.append("type: string") } if self.min != nil { description.append("minLength: \(self.min!)") } if self.max != nil { description.append("maxLength: \(self.max!)") } if self.regex != nil { description.append("pattern: \(self.regex!)") } return description } }
gpl-2.0
60fd0ef660d6970a8886461ff8b9e8e7
23.430657
91
0.485953
4.660167
false
false
false
false
Syntertainment/SYNQueue
SYNQueue/SYNQueue/SYNQueueTask.swift
2
10915
// // SYNQueueTask.swift // SYNQueue // import Foundation public typealias SYNTaskCallback = (SYNQueueTask) -> Void public typealias SYNTaskCompleteCallback = (NSError?, SYNQueueTask) -> Void public typealias JSONDictionary = [String: AnyObject?] /** * Represents a task to be executed on a SYNQueue */ @objc public class SYNQueueTask : NSOperation { static let MIN_RETRY_DELAY = 0.2 static let MAX_RETRY_DELAY = 60.0 public let queue: SYNQueue public let taskID: String public let taskType: String public let data: AnyObject? public let created: NSDate public var started: NSDate? public var retries: Int let dependencyStrs: [String] var lastError: NSError? var _executing: Bool = false var _finished: Bool = false public override var name: String? { get { return taskID } set { } } public override var asynchronous: Bool { return true } public override var executing: Bool { get { return _executing } set { willChangeValueForKey("isExecuting") _executing = newValue didChangeValueForKey("isExecuting") } } public override var finished: Bool { get { return _finished } set { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } /** Initializes a new SYNQueueTask with the following options - parameter queue: The queue that will execute the task - parameter taskID: A unique identifier for the task, must be unique across app terminations, otherwise dependencies will not work correctly - parameter taskType: A type that will be used to group tasks together, tasks have to be generic with respect to their type - parameter dependencyStrs: Identifiers for tasks that are dependencies of this task - parameter data: The data that the task needs to operate on - parameter created: When the task was created - parameter started: When the task started executing - parameter retries: Number of times this task has been retried after failing - parameter queuePriority: The priority - parameter qualityOfService: The quality of service - returns: A new SYNQueueTask */ private init(queue: SYNQueue, taskID: String? = nil, taskType: String, dependencyStrs: [String] = [], data: AnyObject? = nil, created: NSDate = NSDate(), started: NSDate? = nil, retries: Int = 0, queuePriority: NSOperationQueuePriority = .Normal, qualityOfService: NSQualityOfService = .Utility) { self.queue = queue self.taskID = taskID ?? NSUUID().UUIDString self.taskType = taskType self.dependencyStrs = dependencyStrs self.data = data self.created = created self.started = started self.retries = retries super.init() self.queuePriority = queuePriority self.qualityOfService = qualityOfService } /** Initializes a new SYNQueueTask with the following options - parameter queue: The queue that will execute the task - parameter taskType: A type that will be used to group tasks together, tasks have to be generic with respect to their type - parameter data: The data that the task needs to operate on - parameter retries: Number of times this task has been retried after failing - parameter queuePriority: The priority - parameter qualityOfService: The quality of service - returns: A new SYNQueueTask */ public convenience init(queue: SYNQueue, type: String, data: AnyObject? = nil, retries: Int = 0, priority: NSOperationQueuePriority = .Normal, quality: NSQualityOfService = .Utility) { self.init(queue: queue, taskType: type, data: data, retries: retries, queuePriority: priority, qualityOfService: quality) } // For objective-c compatibility of convenience initializer // See: http://sidhantgandhi.com/swift-default-parameter-values-in-convenience-initializers/ public convenience init(queue: SYNQueue, taskType: String) { self.init(queue: queue, type: taskType) } /** Initializes a SYNQueueTask from a dictionary - parameter dictionary: A dictionary that contains the data to reconstruct a task - parameter queue: The queue that the task will execute on - returns: A new SYNQueueTask */ public convenience init?(dictionary: JSONDictionary, queue: SYNQueue) { if let taskID = dictionary["taskID"] as? String, let taskType = dictionary["taskType"] as? String, let dependencyStrs = dictionary["dependencies"] as? [String]? ?? [], let queuePriority = dictionary["queuePriority"] as? Int, let qualityOfService = dictionary["qualityOfService"] as? Int, let data: AnyObject? = dictionary["data"] as AnyObject??, let createdStr = dictionary["created"] as? String, let startedStr: String? = dictionary["started"] as? String ?? nil, let retries = dictionary["retries"] as? Int? ?? 0 { let created = NSDate(dateString: createdStr) ?? NSDate() let started = (startedStr != nil) ? NSDate(dateString: startedStr!) : nil let priority = NSOperationQueuePriority(rawValue: queuePriority) ?? .Normal let qos = NSQualityOfService(rawValue: qualityOfService) ?? .Utility self.init(queue: queue, taskID: taskID, taskType: taskType, dependencyStrs: dependencyStrs, data: data, created: created, started: started, retries: retries, queuePriority: priority, qualityOfService: qos) } else { self.init(queue: queue, taskID: "", taskType: "") return nil } } /** Initializes a SYNQueueTask from JSON - parameter json: JSON from which the reconstruct the task - parameter queue: The queue that the task will execute on - returns: A new SYNQueueTask */ public convenience init?(json: String, queue: SYNQueue) { do { if let dict = try fromJSON(json) as? [String: AnyObject] { self.init(dictionary: dict, queue: queue) } else { return nil } } catch { return nil } } /** Setup the dependencies for the task - parameter allTasks: Array of SYNQueueTasks that are dependencies of this task */ public func setupDependencies(allTasks: [SYNQueueTask]) { dependencyStrs.forEach { (taskID: String) -> Void in let found = allTasks.filter({ taskID == $0.name }) if let task = found.first { self.addDependency(task) } else { let name = self.name ?? "(unknown)" self.queue.log(.Warning, "Discarding missing dependency \(taskID) from \(name)") } } } /** Deconstruct the task to a dictionary, used to serialize the task - returns: A Dictionary representation of the task */ public func toDictionary() -> [String: AnyObject?] { var dict = [String: AnyObject?]() dict["taskID"] = self.taskID dict["taskType"] = self.taskType dict["dependencies"] = self.dependencyStrs dict["queuePriority"] = self.queuePriority.rawValue dict["qualityOfService"] = self.qualityOfService.rawValue dict["data"] = self.data dict["created"] = self.created.toISOString() dict["started"] = (self.started != nil) ? self.started!.toISOString() : nil dict["retries"] = self.retries return dict } /** Deconstruct the task to a JSON string, used to serialize the task - returns: A JSON string representation of the task */ public func toJSONString() -> String? { // Serialize this task to a dictionary let dict = toDictionary() // Convert the dictionary to an NSDictionary by replacing nil values // with NSNull let nsdict = NSMutableDictionary(capacity: dict.count) for (key, value) in dict { nsdict[key] = value ?? NSNull() } do { let json = try toJSON(nsdict) return json } catch { return nil } } /** Starts executing the task */ public override func start() { super.start() executing = true run() } /** Cancels the task */ public override func cancel() { lastError = NSError(domain: "SYNQueue", code: -1, userInfo: [NSLocalizedDescriptionKey: "Task \(taskID) was cancelled"]) super.cancel() queue.log(.Debug, "Canceled task \(taskID)") finished = true } func run() { if cancelled && !finished { finished = true } if finished { return } queue.runTask(self) } /** Call this to mark the task as completed, even if it failed. If it failed, we will use exponential backoff to keep retrying the task until max number of retries is reached. Once this happens, we cancel the task. - parameter error: If the task failed, pass an error to indicate why */ public func completed(error: NSError?) { // Check to make sure we're even executing, if not // just ignore the completed call if (!executing) { queue.log(.Debug, "Completion called on already completed task \(taskID)") return } if let error = error { lastError = error queue.log(.Warning, "Task \(taskID) failed with error: \(error)") // Check if we've exceeded the max allowed retries if ++retries >= queue.maxRetries { queue.log(.Error, "Max retries exceeded for task \(taskID)") cancel() return } // Wait a bit (exponential backoff) and retry this task let exp = Double(min(queue.maxRetries ?? 0, retries)) let seconds:NSTimeInterval = min(SYNQueueTask.MAX_RETRY_DELAY, SYNQueueTask.MIN_RETRY_DELAY * pow(2.0, exp - 1)) queue.log(.Debug, "Waiting \(seconds) seconds to retry task \(taskID)") runInBackgroundAfter(seconds) { self.run() } } else { lastError = nil queue.log(.Debug, "Task \(taskID) completed") finished = true } } }
mit
9da1fb4b5a731772c239e713c372204e
35.875
188
0.600825
4.905618
false
false
false
false
realtime-framework/RealtimeMessaging-iOS-Swift3-Push
Pod/Classes/RealtimePushNotifications.swift
1
8608
// // RealtimePushNotifications.swift // OrtcClient // // Created by joao caixinha on 21/01/16. // Copyright © 2016 Realtime. All rights reserved. // import Foundation import UIKit import UserNotifications import RealtimeMessaging_iOS_Swift3 /** * OrtcClientPushNotificationsDelegate process custom push notification with payload */ public protocol OrtcClientPushNotificationsDelegate{ /** * Process custom push notifications with payload. * If receive custom push and not declared in AppDelegate class trow's excpetion * - parameter channel: from witch channel the notification was send. * - parameter message: the remote notification title * - parameter payload: a dictionary containig the payload data */ func onPushNotificationWithPayload(_ channel:String, message:String, payload:NSDictionary?) } /** * UIResponder extenssion for auto configure application to use remote notifications */ extension UIResponder: OrtcClientPushNotificationsDelegate{ /** Overrides UIResponder initialize method */ override open class func initialize() { NotificationCenter.default.addObserver(self.self, selector: #selector(UIResponder.registForNotifications), name: NSNotification.Name.UIApplicationDidFinishLaunching, object: nil) } open static func registForNotifications() -> Bool { #if os(iOS) if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in // actions based on whether notifications were authorized or not } UIApplication.shared.registerForRemoteNotifications() }else{ if UIApplication.shared.responds(to: #selector(UIApplication.registerUserNotificationSettings(_:))) { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types:[.alert, .badge, .sound], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) UIApplication.shared.registerForRemoteNotifications() }else { UIApplication.shared.registerForRemoteNotifications(matching: [.sound, .alert, .badge]) } } #endif #if os(tvOS) if #available(tvOS 10.0, *) { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in // actions based on whether notifications were authorized or not } UIApplication.shared.registerForRemoteNotifications() } #endif return true } open func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { var newToken: String = (deviceToken as NSData).description newToken = newToken.trimmingCharacters(in: CharacterSet(charactersIn: "<>")) newToken = newToken.replacingOccurrences(of: " ", with: "") print("\n\n - didRegisterForRemoteNotificationsWithDeviceToken:\n\((deviceToken as NSData).description)\n") OrtcClient.setDEVICE_TOKEN(newToken) } open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void){ completionHandler(UIBackgroundFetchResult.newData) self.application(application, didReceiveRemoteNotification: userInfo) } open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { let NOTIFICATIONS_KEY = "Local_Storage_Notifications" if (userInfo["C"] as? NSString) != nil && (userInfo["M"] as? NSString) != nil && (userInfo["A"] as? NSString) != nil { if (((userInfo["aps"] as? NSDictionary)?["alert"]) is String) { var recRegex: NSRegularExpression? do{ recRegex = try NSRegularExpression(pattern: "^#(.*?):", options:NSRegularExpression.Options.caseInsensitive) }catch{ } let recMatch: NSTextCheckingResult? = recRegex?.firstMatch(in: userInfo["M"] as! String, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (userInfo["M"] as! NSString).length)) var strRangeSeqId: NSRange? if recMatch != nil{ strRangeSeqId = recMatch!.rangeAt(1) } var seqId:NSString? var message:NSString? if (recMatch != nil && strRangeSeqId?.location != NSNotFound) { seqId = (userInfo["M"] as! NSString).substring(with: strRangeSeqId!) as NSString let parts:[String] = (userInfo["M"] as! NSString).components(separatedBy: "#\(seqId!):") message = parts[1] as NSString } var ortcMessage: String if seqId != nil && seqId != "" { ortcMessage = "a[\"{\\\"ch\\\":\\\"\(userInfo["C"] as! String)\\\",\\\"s\\\":\\\"\(seqId! as! String)\\\",\\\"m\\\":\\\"\(message! as! String)\\\"}\"]" }else{ ortcMessage = "a[\"{\\\"ch\\\":\\\"\(userInfo["C"] as! String)\\\",\\\"m\\\":\\\"\(userInfo["M"] as! String)\\\"}\"]" } var notificationsDict: NSMutableDictionary? if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ notificationsDict = NSMutableDictionary(dictionary: UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) as! NSDictionary) } if notificationsDict == nil { notificationsDict = NSMutableDictionary() } var notificationsArray: NSMutableDictionary? if notificationsDict?.object(forKey: userInfo["A"] as! String) != nil{ notificationsArray = NSMutableDictionary(dictionary: notificationsDict?.object(forKey: userInfo["A"] as! String) as! NSMutableDictionary) } if notificationsArray == nil{ notificationsArray = NSMutableDictionary() } notificationsArray!.setObject(false, forKey: ortcMessage as NSCopying) notificationsDict!.setObject(notificationsArray!, forKey: (userInfo["A"] as! String as NSCopying)) UserDefaults.standard.set(notificationsDict!, forKey: NOTIFICATIONS_KEY) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: "ApnsNotification"), object: nil, userInfo: userInfo) } else if((UIApplication.shared.delegate?.responds(to: #selector(onPushNotificationWithPayload(_:message:payload:)))) != nil){ (UIApplication.shared.delegate as! OrtcClientPushNotificationsDelegate).onPushNotificationWithPayload(userInfo["C"] as! String, message: userInfo["M"] as! String, payload: userInfo["aps"] as? NSDictionary) } } } open func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { NSLog("Failed to register with error : %@", error) NotificationCenter.default.post(name: Notification.Name(rawValue: "ApnsRegisterError"), object: nil, userInfo: [ "ApnsRegisterError" : error ] ) } /** * Process custom push notifications with payload. * If receive custom push and not declared in AppDelegate class trow's excpetion * - parameter channel: from witch channel the notification was send. * - parameter message: the remote notification title * - parameter payload: a dictionary containig the payload data */ open func onPushNotificationWithPayload(_ channel:String, message:String, payload:NSDictionary?){ preconditionFailure("Must override onPushNotificationWithPayload method on AppDelegate") } }
mit
8f1a727453e3c0c8636a6e7e81ca969a
47.353933
225
0.611711
5.552903
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/MultiSectionTableViewController.swift
1
5110
// // MultiSectionTableViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/28/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class MultiSectionTableViewController: UITableViewController { var sectionNames = [String]() var sectionData = [[String]]() override func viewDidLoad() { super.viewDidLoad() let s = try! String(contentsOfFile: Bundle.main.path(forResource: "states", ofType: "txt")!, encoding: String.Encoding.utf8) let states = s.components(separatedBy: "\n") var previous = "" for aState in states { // get the first letter let c = String(aState.characters.prefix(1)) // only add a letter to sectionNames when it's a different letter if c != previous { previous = c self.sectionNames.append(c.uppercased()) // and in that case also add new subarray to our array of subarrays self.sectionData.append([String]()) } sectionData[sectionData.count-1].append(aState) } self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "Header") self.tableView.sectionIndexColor = UIColor.white self.tableView.sectionIndexBackgroundColor = UIColor.red self.tableView.sectionIndexTrackingBackgroundColor = UIColor.blue } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return self.sectionNames.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sectionData[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let s = self.sectionData[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row] cell.textLabel!.text = s // this part is not in the book, it's just for fun var stateName = s stateName = stateName.lowercased() stateName = stateName.replacingOccurrences(of: " ", with:"") stateName = "flag_\(stateName).gif" let im = UIImage(named: stateName) cell.imageView!.image = im return cell } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let h = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header")! if h.tintColor != UIColor.red { print("configuring a new header view") // only called about 7 times h.tintColor = UIColor.red // invisible marker, tee-hee h.backgroundView = UIView() h.backgroundView?.backgroundColor = UIColor.black let lab = UILabel() lab.tag = 1 lab.font = UIFont(name:"Georgia-Bold", size:22) lab.textColor = UIColor.green lab.backgroundColor = UIColor.clear h.contentView.addSubview(lab) let v = UIImageView() v.tag = 2 v.backgroundColor = UIColor.black v.image = UIImage(named:"us_flag_small.gif") h.contentView.addSubview(v) lab.translatesAutoresizingMaskIntoConstraints = false v.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[lab(25)]-10-[v(40)]", options:[], metrics:nil, views:["v":v, "lab":lab]), NSLayoutConstraint.constraints(withVisualFormat: "V:|[v]|", options:[], metrics:nil, views:["v":v]), NSLayoutConstraint.constraints(withVisualFormat: "V:|[lab]|", options:[], metrics:nil, views:["lab":lab]) ].joined().map{$0}) // uncomment to see bug where button does not inherit superview's tint color // let b = UIButton(type:.System) // b.setTitle("Howdy", forState:.Normal) // b.sizeToFit() // print(b.tintColor) // h.addSubview(b) } let lab = h.contentView.viewWithTag(1) as! UILabel lab.text = self.sectionNames[section] return h } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 22 //return UITableViewAutomaticDimension } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return self.sectionNames } }
apache-2.0
585fcd9ed153cadae43dee7ce1fb10a8
39.228346
132
0.608534
5.088645
false
false
false
false
StanZabroda/Hydra
Hydra/HRGroupsController.swift
1
5255
// // HRGroupsController.swift // Hydra // // Created by Evgeny Evgrafov on 9/22/15. // Copyright © 2015 Evgeny Evgrafov. All rights reserved. // import UIKit import Nuke class HRGroupsController: UITableViewController { var groupsArray = Array<HRGroupModel>() var loading = false override func loadView() { super.loadView() } override func viewDidLoad() { super.viewDidLoad() self.title = "Groups" self.tableView.rowHeight = 70 self.tableView.tableFooterView = UIView(frame: CGRectZero) self.loadGroups() self.tableView.registerClass(HRGroupCell.self, forCellReuseIdentifier: "HRGroupCell") self.tableView.allowsMultipleSelectionDuringEditing = false self.addLeftBarButton() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } // MARK: - load all audio func loadGroups() { if loading == false { loading = true let getGroups = VKRequest(method: "groups.get", andParameters: ["extended":1,"fields":"counters,photo_100,photo_200","offset":self.groupsArray.count], andHttpMethod: "GET") getGroups.executeWithResultBlock({ (response) -> Void in let json = response.json as! Dictionary<String,AnyObject> let items = json["items"] as! Array<Dictionary<String,AnyObject>> for groupDict in items { let jsonGroupItem = JSON(groupDict) let groupItemModel = HRGroupModel(json: jsonGroupItem) self.groupsArray.append(groupItemModel) } self.tableView.reloadData() self.loading = false }, errorBlock: { (error) -> Void in log.error("error loading friends") }) } } // mark: - tableView delegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.groupsArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let group = self.groupsArray[indexPath.row] let cell:HRGroupCell = self.tableView.dequeueReusableCellWithIdentifier("HRGroupCell", forIndexPath: indexPath) as! HRGroupCell cell.groupName.text = group.name var request = ImageRequest(URL: NSURL(string: group.photo_200)!) request.targetSize = CGSizeMake(cell.groupAvatar.frame.width*screenScaleFactor, cell.groupAvatar.frame.height*screenScaleFactor) request.contentMode = .AspectFill Nuke.taskWithRequest(request) { let imagekek = $0.image // Image is resized cell.groupAvatar.image = imagekek?.roundImage() }.resume() return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) // let friend = self.friendsArray[indexPath.row] // // if friend.can_see_audio == true { // // let friendAudioController = HRFriendAudioController() // friendAudioController.friendModel = friend // friendAudioController.title = "\(friend.first_name!) \(friend.last_name!)" // // self.navigationController?.pushViewController(friendAudioController, animated: true) // // } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { //add code here for when you hit delete } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.groupsArray.count - 3 { self.loadGroups() } } //MARK :- stuff func addLeftBarButton() { let button = UIBarButtonItem(image: UIImage(named: "menuHumb"), style: UIBarButtonItemStyle.Plain, target: self, action: "openMenu") self.navigationItem.leftBarButtonItem = button } func openMenu() { HRInterfaceManager.sharedInstance.openMenu() } }
mit
0bcb313d1689dbfc92c918e2c96ab3ad
29.195402
184
0.576323
5.565678
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/WMFTwoFactorPasswordViewController.swift
1
14536
import UIKit fileprivate enum WMFTwoFactorNextFirstResponderDirection: Int { case forward = 1 case reverse = -1 } fileprivate enum WMFTwoFactorTokenDisplayMode { case shortNumeric case longAlphaNumeric } class WMFTwoFactorPasswordViewController: WMFScrollViewController, UITextFieldDelegate, WMFDeleteBackwardReportingTextFieldDelegate, Themeable { @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var subTitleLabel: UILabel! @IBOutlet fileprivate var tokenLabel: UILabel! @IBOutlet fileprivate var tokenAlertLabel: UILabel! @IBOutlet fileprivate var oathTokenFields: [ThemeableTextField]! @IBOutlet fileprivate var oathTokenFieldsStackView: UIStackView! @IBOutlet fileprivate var displayModeToggle: UILabel! @IBOutlet fileprivate var backupOathTokenField: ThemeableTextField! @IBOutlet fileprivate var loginButton: WMFAuthButton! fileprivate var theme = Theme.standard public var funnel: WMFLoginFunnel? public var userName:String? public var password:String? public var captchaID:String? public var captchaWord:String? @objc func displayModeToggleTapped(_ recognizer: UITapGestureRecognizer) { guard recognizer.state == .ended else { return } switch displayMode { case .longAlphaNumeric: displayMode = .shortNumeric case .shortNumeric: displayMode = .longAlphaNumeric } } fileprivate var displayMode: WMFTwoFactorTokenDisplayMode = .shortNumeric { didSet { switch displayMode { case .longAlphaNumeric: backupOathTokenField.isHidden = false oathTokenFieldsStackView.isHidden = true tokenLabel.text = WMFLocalizedString("field-backup-token-title", value:"Backup code", comment:"Title for backup token field") displayModeToggle.text = WMFLocalizedString("two-factor-login-with-regular-code", value:"Use verification code", comment:"Button text for showing text fields for normal two factor login") case .shortNumeric: backupOathTokenField.isHidden = true oathTokenFieldsStackView.isHidden = false tokenLabel.text = WMFLocalizedString("field-token-title", value:"Verification code", comment:"Title for token field") displayModeToggle.text = WMFLocalizedString("two-factor-login-with-backup-code", value:"Use one of your backup codes", comment:"Button text for showing text field for backup code two factor login") } oathTokenFields.forEach {$0.text = nil} backupOathTokenField.text = nil if isViewLoaded && (view.window != nil) { makeAppropriateFieldFirstResponder() } } } fileprivate func makeAppropriateFieldFirstResponder() { switch displayMode { case .longAlphaNumeric: backupOathTokenField?.becomeFirstResponder() case .shortNumeric: oathTokenFields.first?.becomeFirstResponder() } } @IBAction fileprivate func loginButtonTapped(withSender sender: UIButton) { save() } fileprivate func areRequiredFieldsPopulated() -> Bool { switch displayMode { case .longAlphaNumeric: guard backupOathTokenField.text.wmf_safeCharacterCount > 0 else { return false } return true case .shortNumeric: return oathTokenFields.first(where: { $0.text.wmf_safeCharacterCount == 0 }) == nil } } @IBAction func textFieldDidChange(_ sender: ThemeableTextField) { enableProgressiveButton(areRequiredFieldsPopulated()) guard displayMode == .shortNumeric, sender.text.wmf_safeCharacterCount > 0 else { return } makeNextTextFieldFirstResponder(currentTextField: sender, direction: .forward) } fileprivate func makeNextTextFieldFirstResponder(currentTextField: ThemeableTextField, direction: WMFTwoFactorNextFirstResponderDirection) { guard let index = oathTokenFields.firstIndex(of: currentTextField) else { return } let nextIndex = index + direction.rawValue guard nextIndex > -1, nextIndex < oathTokenFields.count else { return } oathTokenFields[nextIndex].becomeFirstResponder() } func wmf_deleteBackward(_ sender: WMFDeleteBackwardReportingTextField) { guard displayMode == .shortNumeric, sender.text.wmf_safeCharacterCount == 0 else { return } makeNextTextFieldFirstResponder(currentTextField: sender, direction: .reverse) } func enableProgressiveButton(_ highlight: Bool) { loginButton.isEnabled = highlight } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) enableProgressiveButton(false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) makeAppropriateFieldFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) enableProgressiveButton(false) } fileprivate func allowedCharacterSet() -> CharacterSet { switch displayMode { case .longAlphaNumeric: return CharacterSet.init(charactersIn: " ").union(CharacterSet.alphanumerics) case .shortNumeric: return CharacterSet.decimalDigits } } fileprivate func maxTextFieldCharacterCount() -> Int { // Presently backup tokens are 16 digit, but may contain spaces and their length // may change in future, so for now just set a sensible upper limit. switch displayMode { case .longAlphaNumeric: return 24 case .shortNumeric: return 1 } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Disallow invalid characters. guard string.rangeOfCharacter(from: allowedCharacterSet().inverted) == nil else { return false } // Always allow backspace. guard string != "" else { return true } // Support numeric code pasting when showing individual digit UITextFields - i.e. when displayMode == .shortNumeric. // If displayMode == .shortNumeric 'string' has been verified to be comprised of decimal digits by this point. // Backup code (when displayMode == .longAlphaNumeric) pasting already works as-is because it uses a single UITextField. if displayMode == .shortNumeric && string.count == oathTokenFields.count { for (field, char) in zip(oathTokenFields, string) { field.text = String(char) } enableProgressiveButton(areRequiredFieldsPopulated()) return false } // Enforce max count. let countIfAllowed = textField.text.wmf_safeCharacterCount + string.count return (countIfAllowed <= maxTextFieldCharacterCount()) } func textFieldDidBeginEditing(_ textField: UITextField) { tokenAlertLabel.isHidden = true // In the storyboard we've set the text fields' to "Clear when editing begins", but // the "Editing changed" handler "textFieldDidChange" isn't called when this clearing // happens, so update progressive buttons' enabled state here too. enableProgressiveButton(areRequiredFieldsPopulated()) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard displayMode == .longAlphaNumeric else { return true } save() return true } override func viewDidLoad() { super.viewDidLoad() oathTokenFields.sort { $0.tag < $1.tag } oathTokenFields.forEach { $0.rightViewMode = .never $0.textAlignment = .center } // Cast fields once here to set 'deleteBackwardDelegate' rather than casting everywhere else UITextField is expected. if let fields = oathTokenFields as? [WMFDeleteBackwardReportingTextField] { fields.forEach {$0.deleteBackwardDelegate = self} } else { assertionFailure("Underlying oathTokenFields from storyboard were expected to be of type 'WMFDeleteBackwardReportingTextField'.") } navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:))) navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel loginButton.setTitle(WMFLocalizedString("two-factor-login-continue", value:"Continue log in", comment:"Button text for finishing two factor login"), for: .normal) titleLabel.text = WMFLocalizedString("two-factor-login-title", value:"Log in to your account", comment:"Title for two factor login interface") subTitleLabel.text = WMFLocalizedString("two-factor-login-instructions", value:"Please enter two factor verification code", comment:"Instructions for two factor login interface") displayMode = .shortNumeric displayModeToggle.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(displayModeToggleTapped(_:)))) view.wmf_configureSubviewsForDynamicType() apply(theme: theme) } @objc func closeButtonPushed(_ : UIBarButtonItem) { dismiss(animated: true, completion: nil) } fileprivate func token() -> String { switch displayMode { case .longAlphaNumeric: return backupOathTokenField.text! case .shortNumeric: return oathTokenFields.reduce("", { $0 + ($1.text ?? "") }) } } fileprivate func save() { wmf_hideKeyboard() tokenAlertLabel.isHidden = true enableProgressiveButton(false) guard let userName = userName, let password = password else { return } WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-logging-in", value:"Logging in...", comment:"Alert shown after account successfully created and the user is being logged in automatically. {{Identical|Logging in}}"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) MWKDataStore.shared().authenticationManager.login(username: userName, password: password, retypePassword: nil, oathToken: token(), captchaID: captchaID, captchaWord: captchaWord) { (loginResult) in switch loginResult { case .success: let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), userName) WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) let presenter = self.presentingViewController self.dismiss(animated: true, completion: { presenter?.wmf_showEnableReadingListSyncPanel(theme: self.theme, oncePerLogin: true) }) self.funnel?.logSuccess() case .failure(let error): if let error = error as? WMFAccountLoginError { switch error { case .temporaryPasswordNeedsChange: WMFAlertManager.sharedInstance.dismissAlert() self.showChangeTempPasswordViewController() return case .wrongToken: self.tokenAlertLabel.text = error.localizedDescription self.tokenAlertLabel.isHidden = false self.funnel?.logError(error.localizedDescription) WMFAlertManager.sharedInstance.dismissAlert() return default: break } self.enableProgressiveButton(true) WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) self.funnel?.logError(error.localizedDescription) self.oathTokenFields.forEach {$0.text = nil} self.backupOathTokenField.text = nil self.makeAppropriateFieldFirstResponder() } default: break } } } func showChangeTempPasswordViewController() { guard let presenter = presentingViewController, let changePasswordVC = WMFChangePasswordViewController.wmf_initialViewControllerFromClassStoryboard() else { assertionFailure("Expected view controller(s) not found") return } changePasswordVC.apply(theme: theme) dismiss(animated: true, completion: { changePasswordVC.userName = self.userName let navigationController = WMFThemeableNavigationController(rootViewController: changePasswordVC, theme: self.theme) presenter.present(navigationController, animated: true, completion: nil) }) } func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground view.tintColor = theme.colors.link tokenAlertLabel.textColor = theme.colors.error var fields = oathTokenFields ?? [] fields.append(backupOathTokenField) for textField in fields { textField.apply(theme: theme) } titleLabel.textColor = theme.colors.primaryText tokenLabel.textColor = theme.colors.secondaryText displayModeToggle.textColor = theme.colors.link subTitleLabel.textColor = theme.colors.secondaryText } }
mit
4ec9613245bbde944a703c5b3839a1ac
40.770115
313
0.642611
6.099874
false
false
false
false
saeta/penguin
Sources/PenguinParallel/NonblockingThreadPool/NonblockingCondition.swift
1
15844
// Copyright 2020 Penguin Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Allows to wait for arbitrary predicates in non-blocking algorithms. /// /// You can think of `NonblockingCondition` as a condition variable, but the predicate to wait upon /// does not need to be protected by a mutex. Using `NonblockingCondition` in a non-blocking /// algorithm (instead of spinning) allows threads to go sleep, saving potentially significant /// amounts of CPU resources. /// /// To use `NonblockingCondition`, your algorithm should look like the following: /// /// ``` /// let nbc = NonblockingCondition(...) /// /// // Waiting thread: /// if predicate { return doWork() } /// nbc.preWait(threadId) /// if predicate { /// nbc.cancelWait(threadId) /// return doWork() /// } /// nbc.commitWait(threadId) // Puts current thread to sleep until notified. /// /// // Notifying thread: /// predicate = true /// nbc.notify() // or nbc.notifyAll() /// ``` /// /// Notifying is cheap if there are no waiting threads. preWait and commitWait are not cheap, but /// they should only be executed if the preceding predicate check failed. This yields an efficient /// system in the general case where there is low contention. final public class NonblockingCondition<Environment: ConcurrencyPlatform> { // Algorithm outline: // // There are two main variables: the predicate (which is managed by the user of // NonblockingCondition), and state. The operation closely resembles the Dekker algorithm: // https://en.wikipedia.org/wiki/Dekker%27s_algorithm. // // The waiting thread sets state, and checks predicate. The notifying thread sets the predicate // and then checks state. Due to the seq_cst fences in between these operations, it is guaranteed // that either the waiter will see the predicate change and won't block, or the notifying thread // will see the state change, and will unblock the waiter, or both. But it is impossible that both // threads don't see each other's changes, as that would lead to a deadlock. // // This implementation is heavily inspired by event_count.h from the Eigen library. /// The atomic storage backing the state of this non blocking condition. private var stateStorage: AtomicUInt64 /// Per-thread state, including the condition variable used to sleep the corresponding thread. fileprivate let threads: ThreadsState /// Threads begin in the notSignaled state. When they are about to go to sleep, they enter the /// waiting state. When they should wake up, the state changes to the signaled state. enum PerThreadState { case notSignaled case waiting case signaled } /// Per-thread state. struct PerThread { /// `next` encodes a stack of waiting threads. var nextStorage = AtomicUInt64() /// epoch is regularly incremented, and is used to avoid the ABA problem. var epoch: UInt64 = 0 /// The current state of the corresponding thread. var state: PerThreadState = .notSignaled /// Condition used to sleep the corresponding thread. let cond = Environment.ConditionMutex() /// Padding to ensure no false sharing of the atomic values. let padding: (UInt64, UInt64) = (0, 0) // Unused; can't use @_alignment to ensure spacing. init() { nextStorage.setRelaxed(NonblockingConditionState.stackMask) } var next: UInt64 { mutating get { nextStorage.valueRelaxed } set { nextStorage.setRelaxed(newValue) } } } /// A buffer containing elements. /// /// Note: we cannot use an Array, as value semantics is inappropriate for this algorithm. final class ThreadsState: ManagedBuffer<Void, PerThread> { class func make(_ threadCount: Int) -> Self { let obj = Self.create(minimumCapacity: threadCount) { _ in () } obj.withUnsafeMutablePointerToElements { elems in for ptr in elems..<(elems + obj.capacity) { ptr.initialize(to: PerThread()) } } return obj as! Self } deinit { withUnsafeMutablePointerToElements { _ = $0.deinitialize(count: capacity) } } subscript(index: Int) -> PerThread { _read { yield withUnsafeMutablePointerToElements { $0[index] } } _modify { let ptr = withUnsafeMutablePointerToElements { $0 + index } yield &ptr.pointee } } } /// Initializes NonblockingCondition for use by up to `threadCount` waiters. public init(threadCount: Int) { stateStorage = AtomicUInt64() stateStorage.setRelaxed(NonblockingConditionState.stackMask) // Empty stack. threads = ThreadsState.make(threadCount) } deinit { let state = loadAcquire() precondition(state.stackIsEmpty, "\(state)") precondition(state.preWaitCount == 0, "\(state)") precondition(state.signalCount == 0, "\(state)") } /// Wakes up waiters. /// /// `notify` is optimized to be cheap in the common case where there are no threads to wake up. public func notify(all: Bool = false) { threadFenceSeqCst() var state = loadAcquire() while true { state.checkSelf() if state.stackIsEmpty && state.preWaitCount == state.signalCount { return } // Fast path. var newState = state if all { newState.notifyAll() } else if state.signalCount < state.preWaitCount { newState.incrementSignalCount() } else if !state.stackIsEmpty { // Pop a waiter from the stack and unpark it. let next = threads[state.stackTop].next newState.popStack(newNext: next) } newState.checkSelf() if cmpxchgAcqRel(originalState: &state, newState: newState) { if !all && state.signalCount < state.preWaitCount { return // There is already an unblocked pre-wait thread. Nothing more to do! } if state.stackIsEmpty { return } // Nothing more to do. if !all { // Set the next pointer in stack top to the empty stack, because we only want to wake up // one thread. threads[state.stackTop].next = NonblockingConditionState.stackMask } unparkStack(state.stackTop) return } } } /// Signals an intent to wait. public func preWait() { var state = loadRelaxed() while true { state.checkSelf() let newState = state.incrementPreWaitCount() newState.checkSelf() if compxchgSeqCst(originalState: &state, newState: newState) { return } } } /// Cancels an intent to wait (i.e. the awaited condition occurred.) public func cancelWait() { var state = loadRelaxed() while true { state.checkSelf(mustHavePreWait: true) var newState = state.decrementPreWaitCount() // Because we don't know if the thread was notified or not, we should not consume a signal // token unconditionally. Instead, if the number of preWait tokens was equal to the number of // signal tokens, then we know that we must consume a signal token. if state.signalCount == state.preWaitCount { newState.decrementSignalCount() } newState.checkSelf() if cmpxchgAcqRel(originalState: &state, newState: newState) { return } } } /// Puts the current thread to sleep until a notification occurs. public func commitWait(_ threadId: Int) { assert( (threads[threadId].epoch & ~NonblockingConditionState.epochMask) == 0, "State for \(threadId) is invalid.") threads[threadId].state = .notSignaled let epoch = threads[threadId].epoch var state = loadSeqCst() while true { state.checkSelf(mustHavePreWait: true) let newState: NonblockingConditionState if state.hasSignal { newState = state.consumeSignal() } else { newState = state.updateForWaitCommit(threadId, epoch: epoch) threads[threadId].next = state.nextToken } newState.checkSelf() if cmpxchgAcqRel(originalState: &state, newState: newState) { if !state.hasSignal { // No signal, so we must wait. threads[threadId].epoch += NonblockingConditionState.epochIncrement park(threadId) } return } } } /// Parks the current thread of execution (identifed as `threadId`) until notified. private func park(_ threadId: Int) { threads[threadId].cond.lock() threads[threadId].cond.await { if threads[threadId].state == .signaled { return true } threads[threadId].state = .waiting return false } threads[threadId].cond.unlock() } /// Unparks the stack of thread ids, starting at `threadId`. private func unparkStack(_ threadId: Int) { var index = threadId // NonblockingConditionState.stackMask is the sentinal for the bottom of the stack. while index != NonblockingConditionState.stackMask { threads[index].cond.lock() threads[index].state = .signaled let nextIndex = Int(threads[index].next & NonblockingConditionState.stackMask) threads[index].next = NonblockingConditionState.stackMask // Set to empty. threads[index].cond.unlock() index = nextIndex } } private func loadRelaxed() -> NonblockingConditionState { NonblockingConditionState(stateStorage.valueRelaxed) } private func loadAcquire() -> NonblockingConditionState { NonblockingConditionState(stateStorage.valueAcquire) } private func loadSeqCst() -> NonblockingConditionState { NonblockingConditionState(stateStorage.valueSeqCst) } private func cmpxchgAcqRel( originalState: inout NonblockingConditionState, newState: NonblockingConditionState ) -> Bool { stateStorage.cmpxchgAcqRel(original: &originalState.underlying, newValue: newState.underlying) } private func compxchgSeqCst( originalState: inout NonblockingConditionState, newState: NonblockingConditionState ) -> Bool { stateStorage.cmpxchgSeqCst(original: &originalState.underlying, newValue: newState.underlying) } } /// A single UInt64 encoding the critical state of the `NonblockingCondition`. /// /// UInt64 Format: /// - low counterBits points to the top of the stack of parked waiters (index in the threads /// array). /// - next counterBits is the count of waiters in the preWait state. /// - next counterBits is the count of pending signals. /// - remaining bits are ABA counter for the stack, and are incremented when a new value is pushed /// onto the stack. fileprivate struct NonblockingConditionState { var underlying: UInt64 init(_ underlying: UInt64) { self.underlying = underlying } /// Perform a number of consistency checks to maintain invariants. /// /// Note: this function should be optimized away in release builds. func checkSelf( mustHavePreWait: Bool = false, oldState: Self? = nil, file: StaticString = #file, line: UInt = #line, function: StaticString = #function ) { assert(Self.epochBits >= 20, "not enough bits to prevent the ABA problem!") assert( preWaitCount >= signalCount, "preWaitCount < signalCount \(self) (discovered in \(function) at: \(file):\(line)\(oldState != nil ? " oldState: \(oldState!)" : ""))" ) assert( !mustHavePreWait || preWaitCount > 0, "preWaitCount was 0: \(self) (discovered in \(function) at: \(file):\(line)\(oldState != nil ? " oldState: \(oldState!)" : ""))" ) } /// The thread at the top of the stack. var stackTop: Int { Int(underlying & Self.stackMask) } var stackIsEmpty: Bool { (underlying & Self.stackMask) == Self.stackMask } /// The number of threads in the pre-wait state. var preWaitCount: UInt64 { (underlying & Self.waiterMask) >> Self.waiterShift } /// Increments the pre-wait count by one. func incrementPreWaitCount() -> Self { Self(underlying + Self.waiterIncrement) } /// Reduce the pre-wait count by one. func decrementPreWaitCount() -> Self { Self(underlying - Self.waiterIncrement) } /// The number of signals queued in the condition. var signalCount: UInt64 { (underlying & Self.signalMask) >> Self.signalShift } /// True iff there is a singal waiting. var hasSignal: Bool { (underlying & Self.signalMask) != 0 } mutating func incrementSignalCount() { underlying += Self.signalIncrement } mutating func decrementSignalCount() { underlying -= Self.signalIncrement } /// Consumes a preWait token and a signal token. func consumeSignal() -> Self { Self(underlying - (Self.waiterIncrement + Self.signalIncrement)) } /// Consumes a prewait counter, and adds `threadId` to the waiter stack. func updateForWaitCommit(_ threadId: Int, epoch: UInt64) -> Self { assert(threadId >= 0, "\(threadId)") assert(threadId < Self.stackMask, "\(threadId)") assert(!hasSignal, "\(self)") // We set the stack pointer to `threadId`, decrement the `waiter` count, and set the ABA epoch. let tmp = (underlying & Self.waiterMask) - Self.waiterIncrement return Self(tmp + UInt64(threadId) + epoch) } mutating func notifyAll() { // Empty wait stack and set signal to # of pre wait threads, keep the preWait count the same. underlying = (underlying & Self.waiterMask) | (preWaitCount << Self.signalShift) | Self.stackMask assert(stackIsEmpty, "\(self)") assert(signalCount == preWaitCount, "\(self)") } mutating func popStack(newNext: UInt64) { underlying = (underlying & (Self.waiterMask | Self.signalMask)) | newNext } /// Token to be used in the implicit stack. var nextToken: UInt64 { underlying & (Self.stackMask | Self.epochMask) } var epoch: UInt64 { underlying & Self.epochMask } static let counterBits: UInt64 = 14 static let counterMask: UInt64 = (1 << counterBits) - 1 static let stackMask: UInt64 = counterMask static let waiterShift: UInt64 = counterBits static let waiterMask: UInt64 = counterMask << waiterShift static let waiterIncrement: UInt64 = 1 << waiterShift static let signalShift: UInt64 = 2 * counterBits static let signalMask: UInt64 = counterMask << signalShift static let signalIncrement: UInt64 = 1 << signalShift static let epochShift: UInt64 = 3 * counterBits static let epochBits: UInt64 = 64 - epochShift static let epochMask: UInt64 = ((1 << epochBits) - 1) << epochShift static let epochIncrement: UInt64 = 1 << epochShift } extension NonblockingConditionState: CustomStringConvertible { public var description: String { "NonblockingConditionState(stackTop: \(stackTop), preWaitCount: \(preWaitCount), signalCount: \(signalCount), epoch: \(epoch >> Self.epochShift))" } } extension NonblockingCondition.PerThread { mutating func makeDescription() -> String { "PerThread(state: \(state), epoch: \(epoch >> NonblockingConditionState.epochShift), next: \(next))" } } extension NonblockingCondition.ThreadsState: CustomStringConvertible { public var description: String { var s = "[" withUnsafeMutablePointerToElements { elems in for i in 0..<capacity { s.append("\n \(i): \(elems[i].makeDescription())") } } s.append("\n]") return s } } extension NonblockingCondition: CustomDebugStringConvertible { public var debugDescription: String { "NonblockingCondition(state: \(loadRelaxed()), threads: \(threads))" } }
apache-2.0
78560ab0b0f340d334eb5f88cdd2893e
35.173516
150
0.686317
4.181578
false
false
false
false
TheTekton/Malibu
MalibuTests/Specs/Tasks/SessionDataTaskSpec.swift
1
675
@testable import Malibu import Quick import Nimble import When class SessionDataTaskSpec: QuickSpec { override func spec() { describe("SessionDataTask") { var task: SessionDataTask! let session = NSURLSession() let URLRequest = try! GETRequest().toURLRequest() let ride = Ride() describe("#init") { beforeEach { task = SessionDataTask(session: session, URLRequest: URLRequest, ride: ride) } it("sets properties") { expect(task.session).to(equal(session)) expect(task.URLRequest).to(equal(URLRequest)) expect(task.ride === ride).to(beTrue()) } } } } }
mit
5dbdf2f80ec956270b74f75809067232
23.107143
86
0.608889
4.440789
false
false
false
false
sammyd/Concurrency-VideoSeries
prototyping/Compression.playground/Contents.swift
1
699
import Foundation import XCPlayground import Compressor let filename = "sample_09_small" let outputURL = XCPlaygroundSharedDataDirectoryURL.URLByAppendingPathComponent("\(filename).compressed") //let inputImage = NSImage(named: "dark_road_small.jpg")! //let imagePath = NSBundle.mainBundle().pathForResource("dark_road_small", ofType: "jpg") let imageData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource(filename, ofType: "jpg")!) Compressor.saveDataAsCompressedFile(imageData!, path: outputURL.path!) //let uncompressed = Compressor.loadCompressedFile(NSBundle.mainBundle().pathForResource("dark_road_small", ofType: "compressed")!) //let image = UIImage(data: uncompressed!)
mit
29a8cb8aa11039417374d1797d7206a5
37.833333
131
0.788269
4.424051
false
false
false
false
jtbandes/swift
test/stdlib/TestJSONEncoder.swift
2
29728
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Swift import Foundation // MARK: - Test Suite #if FOUNDATION_XCTEST import XCTest class TestJSONEncoderSuper : XCTestCase { } #else import StdlibUnittest class TestJSONEncoderSuper { } #endif class TestJSONEncoder : TestJSONEncoderSuper { // MARK: - Encoding Top-Level Empty Types func testEncodingTopLevelEmptyStruct() { let empty = EmptyStruct() _testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary) } func testEncodingTopLevelEmptyClass() { let empty = EmptyClass() _testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary) } // MARK: - Encoding Top-Level Single-Value Types func testEncodingTopLevelSingleValueEnum() { _testEncodeFailure(of: Switch.off) _testEncodeFailure(of: Switch.on) } func testEncodingTopLevelSingleValueStruct() { _testEncodeFailure(of: Timestamp(3141592653)) } func testEncodingTopLevelSingleValueClass() { _testEncodeFailure(of: Counter()) } // MARK: - Encoding Top-Level Structured Types func testEncodingTopLevelStructuredStruct() { // Address is a struct type with multiple fields. let address = Address.testValue _testRoundTrip(of: address) } func testEncodingTopLevelStructuredClass() { // Person is a class with multiple fields. let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"[email protected]\"}".data(using: .utf8)! let person = Person.testValue _testRoundTrip(of: person, expectedJSON: expectedJSON) } func testEncodingTopLevelDeepStructuredType() { // Company is a type with fields which are Codable themselves. let company = Company.testValue _testRoundTrip(of: company) } // MARK: - Date Strategy Tests func testEncodingDate() { // We can't encode a top-level Date, so it'll be wrapped in an array. _testRoundTrip(of: TopLevelWrapper(Date())) } func testEncodingDateSecondsSince1970() { // Cannot encode an arbitrary number of seconds since we've lost precision since 1970. let seconds = 1000.0 let expectedJSON = "[1000]".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in an array. _testRoundTrip(of: TopLevelWrapper(Date(timeIntervalSince1970: seconds)), expectedJSON: expectedJSON, dateEncodingStrategy: .secondsSince1970, dateDecodingStrategy: .secondsSince1970) } func testEncodingDateMillisecondsSince1970() { // Cannot encode an arbitrary number of seconds since we've lost precision since 1970. let seconds = 1000.0 let expectedJSON = "[1000000]".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in an array. _testRoundTrip(of: TopLevelWrapper(Date(timeIntervalSince1970: seconds)), expectedJSON: expectedJSON, dateEncodingStrategy: .millisecondsSince1970, dateDecodingStrategy: .millisecondsSince1970) } func testEncodingDateISO8601() { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime let timestamp = Date(timeIntervalSince1970: 1000) let expectedJSON = "[\"\(formatter.string(from: timestamp))\"]".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in an array. _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .iso8601, dateDecodingStrategy: .iso8601) } } func testEncodingDateFormatted() { let formatter = DateFormatter() formatter.dateStyle = .full formatter.timeStyle = .full let timestamp = Date(timeIntervalSince1970: 1000) let expectedJSON = "[\"\(formatter.string(from: timestamp))\"]".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in an array. _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .formatted(formatter), dateDecodingStrategy: .formatted(formatter)) } func testEncodingDateCustom() { let timestamp = Date() // We'll encode a number instead of a date. let encode = { (_ data: Date, _ encoder: Encoder) throws -> Void in var container = encoder.singleValueContainer() try container.encode(42) } let decode = { (_: Decoder) throws -> Date in return timestamp } // We can't encode a top-level Date, so it'll be wrapped in an array. let expectedJSON = "[42]".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .custom(encode), dateDecodingStrategy: .custom(decode)) } func testEncodingDateCustomEmpty() { let timestamp = Date() // Encoding nothing should encode an empty keyed container ({}). let encode = { (_: Date, _: Encoder) throws -> Void in } let decode = { (_: Decoder) throws -> Date in return timestamp } // We can't encode a top-level Date, so it'll be wrapped in an array. let expectedJSON = "[{}]".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .custom(encode), dateDecodingStrategy: .custom(decode)) } // MARK: - Data Strategy Tests func testEncodingBase64Data() { let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF]) // We can't encode a top-level Data, so it'll be wrapped in an array. let expectedJSON = "[\"3q2+7w==\"]".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(data), expectedJSON: expectedJSON) } func testEncodingCustomData() { // We'll encode a number instead of data. let encode = { (_ data: Data, _ encoder: Encoder) throws -> Void in var container = encoder.singleValueContainer() try container.encode(42) } let decode = { (_: Decoder) throws -> Data in return Data() } // We can't encode a top-level Data, so it'll be wrapped in an array. let expectedJSON = "[42]".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(Data()), expectedJSON: expectedJSON, dataEncodingStrategy: .custom(encode), dataDecodingStrategy: .custom(decode)) } func testEncodingCustomDataEmpty() { // Encoding nothing should encode an empty keyed container ({}). let encode = { (_: Data, _: Encoder) throws -> Void in } let decode = { (_: Decoder) throws -> Data in return Data() } // We can't encode a top-level Data, so it'll be wrapped in an array. let expectedJSON = "[{}]".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(Data()), expectedJSON: expectedJSON, dataEncodingStrategy: .custom(encode), dataDecodingStrategy: .custom(decode)) } // MARK: - Non-Conforming Floating Point Strategy Tests func testEncodingNonConformingFloats() { _testEncodeFailure(of: TopLevelWrapper(Float.infinity)) _testEncodeFailure(of: TopLevelWrapper(-Float.infinity)) _testEncodeFailure(of: TopLevelWrapper(Float.nan)) _testEncodeFailure(of: TopLevelWrapper(Double.infinity)) _testEncodeFailure(of: TopLevelWrapper(-Double.infinity)) _testEncodeFailure(of: TopLevelWrapper(Double.nan)) } func testEncodingNonConformingFloatStrings() { let encodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN") let decodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN") _testRoundTrip(of: TopLevelWrapper(Float.infinity), expectedJSON: "[\"INF\"]".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: TopLevelWrapper(-Float.infinity), expectedJSON: "[\"-INF\"]".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) // Since Float.nan != Float.nan, we have to use a placeholder that'll encode NaN but actually round-trip. _testRoundTrip(of: TopLevelWrapper(FloatNaNPlaceholder()), expectedJSON: "[\"NaN\"]".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: TopLevelWrapper(Double.infinity), expectedJSON: "[\"INF\"]".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: TopLevelWrapper(-Double.infinity), expectedJSON: "[\"-INF\"]".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) // Since Double.nan != Double.nan, we have to use a placeholder that'll encode NaN but actually round-trip. _testRoundTrip(of: TopLevelWrapper(DoubleNaNPlaceholder()), expectedJSON: "[\"NaN\"]".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) } // MARK: - Encoder Features func testNestedContainerCodingPaths() { let encoder = JSONEncoder() do { let _ = try encoder.encode(NestedContainersTestType()) } catch let error as NSError { expectUnreachable("Caught error during encoding nested container types: \(error)") } } func testSuperEncoderCodingPaths() { let encoder = JSONEncoder() do { let _ = try encoder.encode(NestedContainersTestType(testSuperEncoder: true)) } catch let error as NSError { expectUnreachable("Caught error during encoding nested container types: \(error)") } } // MARK: - Helper Functions private var _jsonEmptyDictionary: Data { return "{}".data(using: .utf8)! } private func _testEncodeFailure<T : Encodable>(of value: T) { do { let _ = try JSONEncoder().encode(value) expectUnreachable("Encode of top-level \(T.self) was expected to fail.") } catch {} } private func _testRoundTrip<T>(of value: T, expectedJSON json: Data? = nil, dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64Encode, dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64Decode, nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw, nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .throw) where T : Codable, T : Equatable { var payload: Data! = nil do { let encoder = JSONEncoder() encoder.dateEncodingStrategy = dateEncodingStrategy encoder.dataEncodingStrategy = dataEncodingStrategy encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy payload = try encoder.encode(value) } catch { expectUnreachable("Failed to encode \(T.self) to JSON.") } if let expectedJSON = json { expectEqual(expectedJSON, payload, "Produced JSON not identical to expected JSON.") } do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy decoder.dataDecodingStrategy = dataDecodingStrategy decoder.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy let decoded = try decoder.decode(T.self, from: payload) expectEqual(decoded, value, "\(T.self) did not round-trip to an equal value.") } catch { expectUnreachable("Failed to decode \(T.self) from JSON.") } } } // MARK: - Helper Global Functions func expectEqualPaths(_ lhs: [CodingKey?], _ rhs: [CodingKey?], _ prefix: String) { if lhs.count != rhs.count { expectUnreachable("\(prefix) [CodingKey?].count mismatch: \(lhs.count) != \(rhs.count)") return } for (k1, k2) in zip(lhs, rhs) { switch (k1, k2) { case (.none, .none): continue case (.some(let _k1), .none): expectUnreachable("\(prefix) CodingKey mismatch: \(type(of: _k1)) != nil") return case (.none, .some(let _k2)): expectUnreachable("\(prefix) CodingKey mismatch: nil != \(type(of: _k2))") return default: break } let key1 = k1! let key2 = k2! switch (key1.intValue, key2.intValue) { case (.none, .none): break case (.some(let i1), .none): expectUnreachable("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != nil") return case (.none, .some(let i2)): expectUnreachable("\(prefix) CodingKey.intValue mismatch: nil != \(type(of: key2))(\(i2))") return case (.some(let i1), .some(let i2)): guard i1 == i2 else { expectUnreachable("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != \(type(of: key2))(\(i2))") return } break } expectEqual(key1.stringValue, key2.stringValue, "\(prefix) CodingKey.stringValue mismatch: \(type(of: key1))('\(key1.stringValue)') != \(type(of: key2))('\(key2.stringValue)')") } } // MARK: - Test Types /* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */ // MARK: - Empty Types fileprivate struct EmptyStruct : Codable, Equatable { static func ==(_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool { return true } } fileprivate class EmptyClass : Codable, Equatable { static func ==(_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool { return true } } // MARK: - Single-Value Types /// A simple on-off switch type that encodes as a single Bool value. fileprivate enum Switch : Codable { case off case on init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() switch try container.decode(Bool.self) { case false: self = .off case true: self = .on } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .off: try container.encode(false) case .on: try container.encode(true) } } } /// A simple timestamp type that encodes as a single Double value. fileprivate struct Timestamp : Codable { let value: Double init(_ value: Double) { self.value = value } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() value = try container.decode(Double.self) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.value) } } /// A simple referential counter type that encodes as a single Int value. fileprivate final class Counter : Codable { var count: Int = 0 init() {} init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() count = try container.decode(Int.self) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.count) } } // MARK: - Structured Types /// A simple address type that encodes as a dictionary of values. fileprivate struct Address : Codable, Equatable { let street: String let city: String let state: String let zipCode: Int let country: String init(street: String, city: String, state: String, zipCode: Int, country: String) { self.street = street self.city = city self.state = state self.zipCode = zipCode self.country = country } static func ==(_ lhs: Address, _ rhs: Address) -> Bool { return lhs.street == rhs.street && lhs.city == rhs.city && lhs.state == rhs.state && lhs.zipCode == rhs.zipCode && lhs.country == rhs.country } static var testValue: Address { return Address(street: "1 Infinite Loop", city: "Cupertino", state: "CA", zipCode: 95014, country: "United States") } } /// A simple person class that encodes as a dictionary of values. fileprivate class Person : Codable, Equatable { let name: String let email: String // FIXME: This property is present only in order to test the expected result of Codable synthesis in the compiler. // We want to test against expected encoded output (to ensure this generates an encodeIfPresent call), but we need an output format for that. // Once we have a VerifyingEncoder for compiler unit tests, we should move this test there. let website: URL? init(name: String, email: String, website: URL? = nil) { self.name = name self.email = email self.website = website } static func ==(_ lhs: Person, _ rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.email == rhs.email && lhs.website == rhs.website } static var testValue: Person { return Person(name: "Johnny Appleseed", email: "[email protected]") } } /// A simple company struct which encodes as a dictionary of nested values. fileprivate struct Company : Codable, Equatable { let address: Address var employees: [Person] init(address: Address, employees: [Person]) { self.address = address self.employees = employees } static func ==(_ lhs: Company, _ rhs: Company) -> Bool { return lhs.address == rhs.address && lhs.employees == rhs.employees } static var testValue: Company { return Company(address: Address.testValue, employees: [Person.testValue]) } } // MARK: - Helper Types /// Wraps a type T so that it can be encoded at the top level of a payload. fileprivate struct TopLevelWrapper<T> : Codable, Equatable where T : Codable, T : Equatable { let value: T init(_ value: T) { self.value = value } func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(value) } init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() value = try container.decode(T.self) assert(container.isAtEnd) } static func ==(_ lhs: TopLevelWrapper<T>, _ rhs: TopLevelWrapper<T>) -> Bool { return lhs.value == rhs.value } } fileprivate struct FloatNaNPlaceholder : Codable, Equatable { init() {} func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(Float.nan) } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let float = try container.decode(Float.self) if !float.isNaN { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN.")) } } static func ==(_ lhs: FloatNaNPlaceholder, _ rhs: FloatNaNPlaceholder) -> Bool { return true } } fileprivate struct DoubleNaNPlaceholder : Codable, Equatable { init() {} func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(Double.nan) } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let double = try container.decode(Double.self) if !double.isNaN { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN.")) } } static func ==(_ lhs: DoubleNaNPlaceholder, _ rhs: DoubleNaNPlaceholder) -> Bool { return true } } struct NestedContainersTestType : Encodable { let testSuperEncoder: Bool init(testSuperEncoder: Bool = false) { self.testSuperEncoder = testSuperEncoder } enum TopLevelCodingKeys : Int, CodingKey { case a case b case c } enum IntermediateCodingKeys : Int, CodingKey { case one case two } func encode(to encoder: Encoder) throws { if self.testSuperEncoder { var topLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self) expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.") expectEqualPaths(topLevelContainer.codingPath, [], "New first-level keyed container has non-empty codingPath.") let superEncoder = topLevelContainer.superEncoder(forKey: .a) expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.") expectEqualPaths(topLevelContainer.codingPath, [], "First-level keyed container's codingPath changed.") expectEqualPaths(superEncoder.codingPath, [TopLevelCodingKeys.a], "New superEncoder had unexpected codingPath.") _testNestedContainers(in: superEncoder, baseCodingPath: [TopLevelCodingKeys.a]) } else { _testNestedContainers(in: encoder, baseCodingPath: []) } } func _testNestedContainers(in encoder: Encoder, baseCodingPath: [CodingKey?]) { expectEqualPaths(encoder.codingPath, baseCodingPath, "New encoder has non-empty codingPath.") // codingPath should not change upon fetching a non-nested container. var firstLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "New first-level keyed container has non-empty codingPath.") // Nested Keyed Container do { // Nested container for key should have a new key pushed on. var secondLevelContainer = firstLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .a) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "New second-level keyed container had unexpected codingPath.") // Inserting a keyed container should not change existing coding paths. let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .one) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.one], "New third-level keyed container had unexpected codingPath.") // Inserting an unkeyed container should not change existing coding paths. let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer(forKey: .two) expectEqualPaths(encoder.codingPath, baseCodingPath + [], "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath + [], "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.two], "New third-level unkeyed container had unexpected codingPath.") } // Nested Unkeyed Container do { // Nested container for key should have a new key pushed on. var secondLevelContainer = firstLevelContainer.nestedUnkeyedContainer(forKey: .a) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "New second-level keyed container had unexpected codingPath.") // Appending a keyed container should not change existing coding paths. let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level unkeyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, nil], "New third-level keyed container had unexpected codingPath.") // Appending an unkeyed container should not change existing coding paths. let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer() expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level unkeyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, nil], "New third-level unkeyed container had unexpected codingPath.") } } } // MARK: - Run Tests #if !FOUNDATION_XCTEST var JSONEncoderTests = TestSuite("TestJSONEncoder") JSONEncoderTests.test("testEncodingTopLevelEmptyStruct") { TestJSONEncoder().testEncodingTopLevelEmptyStruct() } JSONEncoderTests.test("testEncodingTopLevelEmptyClass") { TestJSONEncoder().testEncodingTopLevelEmptyClass() } JSONEncoderTests.test("testEncodingTopLevelSingleValueEnum") { TestJSONEncoder().testEncodingTopLevelSingleValueEnum() } JSONEncoderTests.test("testEncodingTopLevelSingleValueStruct") { TestJSONEncoder().testEncodingTopLevelSingleValueStruct() } JSONEncoderTests.test("testEncodingTopLevelSingleValueClass") { TestJSONEncoder().testEncodingTopLevelSingleValueClass() } JSONEncoderTests.test("testEncodingTopLevelStructuredStruct") { TestJSONEncoder().testEncodingTopLevelStructuredStruct() } JSONEncoderTests.test("testEncodingTopLevelStructuredClass") { TestJSONEncoder().testEncodingTopLevelStructuredClass() } JSONEncoderTests.test("testEncodingTopLevelStructuredClass") { TestJSONEncoder().testEncodingTopLevelStructuredClass() } JSONEncoderTests.test("testEncodingTopLevelDeepStructuredType") { TestJSONEncoder().testEncodingTopLevelDeepStructuredType()} JSONEncoderTests.test("testEncodingDate") { TestJSONEncoder().testEncodingDate() } JSONEncoderTests.test("testEncodingDateSecondsSince1970") { TestJSONEncoder().testEncodingDateSecondsSince1970() } JSONEncoderTests.test("testEncodingDateMillisecondsSince1970") { TestJSONEncoder().testEncodingDateMillisecondsSince1970() } JSONEncoderTests.test("testEncodingDateISO8601") { TestJSONEncoder().testEncodingDateISO8601() } JSONEncoderTests.test("testEncodingDateFormatted") { TestJSONEncoder().testEncodingDateFormatted() } JSONEncoderTests.test("testEncodingDateCustom") { TestJSONEncoder().testEncodingDateCustom() } JSONEncoderTests.test("testEncodingDateCustomEmpty") { TestJSONEncoder().testEncodingDateCustomEmpty() } JSONEncoderTests.test("testEncodingBase64Data") { TestJSONEncoder().testEncodingBase64Data() } JSONEncoderTests.test("testEncodingCustomData") { TestJSONEncoder().testEncodingCustomData() } JSONEncoderTests.test("testEncodingCustomDataEmpty") { TestJSONEncoder().testEncodingCustomDataEmpty() } JSONEncoderTests.test("testEncodingNonConformingFloats") { TestJSONEncoder().testEncodingNonConformingFloats() } JSONEncoderTests.test("testEncodingNonConformingFloatStrings") { TestJSONEncoder().testEncodingNonConformingFloatStrings() } JSONEncoderTests.test("testNestedContainerCodingPaths") { TestJSONEncoder().testNestedContainerCodingPaths() } JSONEncoderTests.test("testSuperEncoderCodingPaths") { TestJSONEncoder().testSuperEncoderCodingPaths() } runAllTests() #endif
apache-2.0
4ef4b3ee3a4c0b8d0969894f3e91b61d
41.347578
194
0.694093
5.163801
false
true
false
false
Arcovv/CleanArchitectureRxSwift
CoreDataPlatform/Entities/CDComment+Ext.swift
2
1254
// // CDComment+Ext.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Foundation import CoreData import Domain import QueryKit import RxSwift extension CDComment { static var body: Attribute<String> { return Attribute("body")} static var email: Attribute<String> { return Attribute("email")} static var name: Attribute<String> { return Attribute("name")} static var postId: Attribute<String> { return Attribute("postId")} static var uid: Attribute<String> { return Attribute("uid")} } extension CDComment: DomainConvertibleType { func asDomain() -> Comment { return Comment(body: body!, email: email!, name: name!, postId: postId!, uid: uid!) } } extension CDComment: Persistable { static var entityName: String { return "CDComment" } } extension Comment: CoreDataRepresentable { typealias CoreDataType = CDComment func update(entity: CDComment) { entity.uid = uid entity.name = name entity.body = body entity.email = email entity.postId = postId } }
mit
de9758fd77b735ce45ccc792306a34b3
24.571429
70
0.628093
4.491039
false
false
false
false
Eonil/EditorLegacy
Modules/Editor/Sources/ProtoUIComponents/EditorCommonWindowController2.swift
1
2626
// // EditorCommonWindowController2.swift // Editor // // Created by Hoon H. on 12/23/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation import AppKit /// **DEPRECATED, DO NOT USE THIS** /// /// A window controller which provides saner behaviors. /// /// - This creates and binds `contentViewController` itself using `instantiateWindow` method. /// You can override instantiation of it. /// /// - This sends `windowDidLoad` message at proper timing. /// /// Do not override any initialiser. Instead, override `windowDidLoad` to setup thigns. /// This is intentional design to prevent weird OBJC instance replacement behavior. /// /// IB is unsupported. @availability(*,deprecated=0) class EditorCommonWindowController2 : NSWindowController { /// No support for IB. @availability(*,unavailable) @availability(*,deprecated=0) required init?(coder: NSCoder) { fatalError() } @availability(*,unavailable) @availability(*,deprecated=0) override init(window: NSWindow?) { super.init(window: window) self.loadWindow() self.windowDidLoad() } /// Don't call this. Intended for internal use only. // @availability(*,unavailable) final override func loadWindow() { super.window = instantiateWindow() } /// Designed to be overridable. /// You must call super-implementation. override func windowDidLoad() { super.windowDidLoad() super.window!.contentViewController = instantiateContentViewController() } // // override var windowNibPath:String! { // get { // return nil // } // } // override var windowNibName:String! { // get { // return nil // } // } /// Designed to be overridable. func instantiateWindow() -> NSWindow { let w1 = NSWindow() w1.styleMask |= NSResizableWindowMask | NSTitledWindowMask | NSMiniaturizableWindowMask | NSClosableWindowMask return w1 } /// Designed to be overridable. func instantiateContentViewController() -> NSViewController { return EmptyViewController(nibName: nil, bundle: nil)! } final override var contentViewController:NSViewController? { get { return super.window!.contentViewController } @availability(*,unavailable) set(v) { fatalError("You cannot set `contentViewController`. Instead, override `instantiateContentViewController` method to customise its class.") // super.contentViewController = v } } } private extension EditorCommonWindowController2 { /// A view controller to suppress NIB searching error. @objc private class EmptyViewController: NSViewController { private override func loadView() { super.view = NSView(); } } }
mit
3e6e9370904655c67a29f756190e8ffd
21.067227
140
0.714014
3.73542
false
false
false
false
Axure/TicTacToeGame
myTicTacToe/GameModel.swift
1
8256
// // GameModel.swift // myTicTacToe // // Created by 郑虎 on 15 年 3. 11.. // Copyright (c) 2015年 郑虎. All rights reserved. // import UIKit protocol GameModelProtocol : class { func placeAPiece(location : (Int, Int), side : Side) func sideChanged(side : Side) func win(side : Side, point : (Int, Int), direction: Direction) } class GameModel : NSObject { let dimension : Int let threshold : Int var finished = false var side : Side { didSet { delegate.sideChanged(side) } } var gameboard : SquareGameboard<PieceObject> let delegate : GameModelProtocol var queue : [PlaceCommand] var timer : NSTimer let maxCommands = 5 let queueDelay = 0.1 init(dimension d: Int, threshold t: Int, delegate: GameModelProtocol) { dimension = d threshold = t side = Side.Black self.delegate = delegate queue = [PlaceCommand]() timer = NSTimer() gameboard = SquareGameboard(dimension: d, initialValue: .Empty) super.init() } func reset() { side = Side.Black gameboard.setAll(.Empty) queue.removeAll(keepCapacity: true) timer.invalidate() } func queueMove(side : Side, location : (Int, Int), completion : (Bool) -> ()) { if queue.count > maxCommands { return } let command = PlaceCommand(s : side, l : location ,c : completion) queue.append(command) if (!timer.valid) { timerFired(timer) } } func timerFired(timer: NSTimer) { if queue.count == 0 { return } // Go through the queue until a valid command is run or the queue is empty var changed = false while queue.count > 0 { let command = queue[0] queue.removeAtIndex(0) changed = performMove(command.location, side: command.side) command.completion(changed) if changed { // If the command doesn't change anything, we immediately run the next one break } } if changed { self.timer = NSTimer.scheduledTimerWithTimeInterval(queueDelay, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: false) } } func placeAPiece(location : (Int, Int), side : Side) { let (x, y) = location switch gameboard[x, y] { case .Empty: gameboard[x, y] = PieceObject.Piece(side) delegate.placeAPiece(location, side : side) default: break } } func insertTileAtRandomLocation(value: Int) { let openSpots = gameboardEmptySpots() if openSpots.count == 0 { // No more open spots; don't even bother return } // Randomly select an open spot, and put a new tile there let idx = Int(arc4random_uniform(UInt32(openSpots.count-1))) let (x, y) = openSpots[idx] placeAPiece((x, y), side: side) } func gameboardEmptySpots() -> [(Int, Int)] { var buffer = Array<(Int, Int)>() for i in 0..<dimension { for j in 0..<dimension { switch gameboard[i, j] { case .Empty: buffer += [(i, j)] default: break } } } return buffer } func performMove(location : (Int, Int), side : Side) -> Bool { if !finished { let (x, y) = location switch gameboard[x, y] { case PieceObject.Empty: gameboard[x, y] = PieceObject.Piece(side) delegate.placeAPiece(location, side: side) self.side.alt() switch self.side { case Side.Black: println("Black!") default: println("White!") } println(sideHasWon(side)) return true default: return false } } return false } // This is the very first, brutal and primitive version // Further versions should contain analysis of the situation // The model should be upgraded. // It's actually KMP isn't it.. // Maybe we should invent a new data structure for this simple and specific problem // The points should record more things I think... // Maybe a new algorithm for updating and inserting.. // Maybe we should put it off func win(side : Side, point : (Int, Int), direction: Direction) { delegate.win(side, point: point, direction: direction) } func sideHasWon(side : Side) -> (result: Bool, point: (Int, Int), direction: Direction) { // for i in 0..<dimension { // We need a scan algorithm... // We need ALGORITHM! var point : (Int ,Int) for i in 0..<dimension - threshold + 1 { for j in 0..<dimension - threshold + 1 { // ba jindu chaoqian gangan caishi weiyi zhengtu... // zhenglu, zhengdao! } } // var result : Bool let a = aPointHasWon(side, point: (0, 0), direction: Direction.Skew) if (a.result) { return a } let b = aPointHasWon(side, point: (dimension - 1, 0), direction: Direction.Subskew) if (b.result) { return b } for i in 0..<dimension { for j in 0..<dimension - threshold + 1 { let a = aPointHasWon(side, point: (i, j), direction: Direction.Horizontal) if (a.result) { return a } } } for i in 0..<dimension - threshold + 1 { for j in 0..<dimension { let a = aPointHasWon(side, point: (i, j), direction: Direction.Vertical) if (a.result) { return a } } } // Scan vertically return (false, (-1, -1), Direction.Skew) } func aPointHasWon(side: Side, point: (x: Int, y: Int), direction: Direction) -> (result: Bool, point: (Int, Int), direction: Direction) { var (x, y) = point var _result: Bool for i in 0..<threshold { switch(gameboard[x, y]) { case .Piece(Side.Black): if side != Side.Black { return (false, (-1, -1), Direction.Skew) } case .Piece(Side.White): if side != Side.White { return (false, (-1, -1), Direction.Skew) } default: return (false, (-1, -1), Direction.Skew) } switch(direction) { case Direction.Horizontal: y++ case Direction.Vertical: x++ case Direction.Skew: x++ y++ case Direction.Subskew: x-- y++ } } return (true, point, direction) } // How to highlight the pieces leading to victory? // It is more about knowledge and less about intelligence. // Diligence and will // A new function for winning // After a winner is detected, the gameboard is frozen and an action is fired // We need to display the animation for winner, for only once // After the board is frozen, any further moves will be banned. }
mit
8775561cc63f356718e92aec58c308d0
25.423077
141
0.477438
4.773596
false
false
false
false
mshhmzh/firefox-ios
Sync/Synchronizers/IndependentRecordSynchronizer.swift
3
8199
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred private let log = Logger.syncLogger public typealias ByteCount = Int class Uploader { /** * Upload just about anything that can be turned into something we can upload. */ func sequentialPosts<T>(items: [T], by: Int, lastTimestamp: Timestamp, storageOp: ([T], Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { // This needs to be a real Array, not an ArraySlice, // for the types to line up. let chunks = chunk(items, by: by).map { Array($0) } let start = deferMaybe(lastTimestamp) let perChunk: ([T], Timestamp) -> DeferredTimestamp = { (records, timestamp) in // TODO: detect interruptions -- clients uploading records during our sync -- // by using ifUnmodifiedSince. We can detect uploaded records since our download // (chain the download timestamp into this function), and we can detect uploads // that race with our own (chain download timestamps across 'walk' steps). // If we do that, we can also advance our last fetch timestamp after each chunk. log.debug("Uploading \(records.count) records.") return storageOp(records, timestamp) } return walk(chunks, start: start, f: perChunk) } } public class IndependentRecordSynchronizer: TimestampedSingleCollectionSynchronizer { /** * Just like the usual applyIncomingToStorage, but doesn't fast-forward the timestamp. */ func applyIncomingRecords<T>(records: [T], apply: T -> Success) -> Success { if records.isEmpty { log.debug("No records; done applying.") return succeed() } return walk(records, f: apply) } func applyIncomingToStorage<T>(records: [T], fetched: Timestamp, apply: T -> Success) -> Success { func done() -> Success { log.debug("Bumping fetch timestamp to \(fetched).") self.lastFetched = fetched return succeed() } if records.isEmpty { log.debug("No records; done applying.") return done() } return walk(records, f: apply) >>> done } } extension TimestampedSingleCollectionSynchronizer { /** * On each chunk that we upload, we pass along the server modified timestamp to the next, * chained through the provided `onUpload` function. * * The last chunk passes this modified timestamp out, and we assign it to lastFetched. * * The idea of this is twofold: * * 1. It does the fast-forwarding that every other Sync client does. * * 2. It allows us to (eventually) pass the last collection modified time as If-Unmodified-Since * on each upload batch, as we do between the download and the upload phase. * This alone allows us to detect conflicts from racing clients. * * In order to implement the latter, we'd need to chain the date from getSince in place of the * 0 in the call to uploadOutgoingFromStorage in each synchronizer. */ func uploadRecords<T>(records: [Record<T>], by: Int, lastTimestamp: Timestamp, storageClient: Sync15CollectionClient<T>, onUpload: POSTResult -> DeferredTimestamp) -> DeferredTimestamp { if records.isEmpty { log.debug("No modified records to upload.") return deferMaybe(lastTimestamp) } let storageOp: ([Record<T>], Timestamp) -> DeferredTimestamp = { records, timestamp in // TODO: use I-U-S. // Each time we do the storage operation, we might receive a backoff notification. // For a success response, this will be on the subsequent request, which means we don't // have to worry about handling successes and failures mixed with backoffs here. return storageClient.post(records, ifUnmodifiedSince: nil) >>== { onUpload($0.value) } } log.debug("Uploading \(records.count) modified records.") // Chain the last upload timestamp right into our lastFetched timestamp. // This is what Sync clients tend to do, but we can probably do better. // Upload 50 records at a time. return Uploader().sequentialPosts(records, by: by, lastTimestamp: lastTimestamp, storageOp: storageOp) >>== effect(self.setTimestamp) } func uploadRecordsInChunks<T>(records: [Record<T>], lastTimestamp: Timestamp, storageClient: Sync15CollectionClient<T>, onUpload: POSTResult -> DeferredTimestamp) -> DeferredTimestamp { // Obvious sanity. precondition(Sync15StorageClient.maxRecordSizeBytes <= Sync15StorageClient.maxPayloadSizeBytes) if records.isEmpty { log.debug("No modified records to upload.") return deferMaybe(lastTimestamp) } var failedGUID: GUID? = nil var largest: ByteCount = 0 // Schwartzian transform -- decorate, sort, undecorate. func decorate(record: Record<T>) -> (String, ByteCount)? { guard failedGUID == nil else { // If we hit an over-sized record, or fail to serialize, we stop processing // everything: we don't want to upload only some of the user's bookmarks. return nil } guard let string = storageClient.serializeRecord(record) else { failedGUID = record.id return nil } let size = string.utf8.count if size > largest { largest = size if size > Sync15StorageClient.maxRecordSizeBytes { // If we hit this case, we cannot ever successfully sync until the user // takes action. Let's hope they do. failedGUID = record.id return nil } } return (string, size) } // Put small records first. let sorted = records.flatMap(decorate).sort { $0.1 < $1.1 } if let failed = failedGUID { return deferMaybe(RecordTooLargeError(size: largest, guid: failed)) } // Cut this up into chunks of a maximum size. var batches: [[String]] = [] var batch: [String] = [] var bytes = 0 var count = 0 sorted.forEach { (string, size) in let expectedBytes = bytes + size + 1 // Include newlines. if expectedBytes > Sync15StorageClient.maxPayloadSizeBytes || count >= Sync15StorageClient.maxPayloadItemCount { batches.append(batch) batch = [] bytes = 0 count = 0 } batch.append(string) bytes += size + 1 count += 1 } // Catch the last one. if !batch.isEmpty { batches.append(batch) } log.debug("Uploading \(records.count) modified records in \(batches.count) batches.") let perChunk: ([String], Timestamp) -> DeferredTimestamp = { (lines, timestamp) in log.debug("Uploading \(lines.count) records.") // TODO: use I-U-S. // Each time we do the storage operation, we might receive a backoff notification. // For a success response, this will be on the subsequent request, which means we don't // have to worry about handling successes and failures mixed with backoffs here. return storageClient.post(lines, ifUnmodifiedSince: nil) >>== { onUpload($0.value) } } let start = deferMaybe(lastTimestamp) return walk(batches, start: start, f: perChunk) // Chain the last upload timestamp right into our lastFetched timestamp. // This is what Sync clients tend to do, but we can probably do better. >>== effect(self.setTimestamp) } }
mpl-2.0
3bdf623f67e85734742fa46eb37e0661
39.394089
190
0.612026
4.854352
false
false
false
false
asp2insp/Twittercism
Twittercism/ProfileViewController.swift
1
7249
// // ProfileViewController.swift // Twittercism // // Created by Josiah Gaskin on 5/18/15. // Copyright (c) 2015 Josiah Gaskin. All rights reserved. // import Foundation import UIKit import TwitterKit let TIMELINE = Getter(keyPath: ["timeline", "tweets"]) let TARGET_TIMELINE = Getter(keyPath: ["timeline", "target_screen_name"]) class ProfileViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate { @IBOutlet weak var loginButtonPlaceholder: UIView! @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var loginButton: TWTRLogInButton! @IBOutlet weak var headerHeight: NSLayoutConstraint! @IBOutlet weak var headerView: UIView! let BASE_HEADER_HEIGHT : CGFloat = 200.0 @IBOutlet weak var headerBackground: UIImageView! @IBOutlet weak var headerProfile: UIImageView! @IBOutlet weak var headerDisplayName: UILabel! @IBOutlet weak var headerHandle: UILabel! @IBOutlet weak var headerStats: UISegmentedControl! @IBOutlet weak var tableView: UITableView! let PROFILE = Getter(keyPath: ["timeline", "user"]) var reactor : Reactor! var keys : [UInt] = [] override func viewDidLoad() { super.viewDidLoad() reactor = TwitterApi.sharedInstance.reactor tableView.registerNib(UINib(nibName: "Tweet", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "tweet") // headerView.setTranslatesAutoresizingMaskIntoConstraints(false) // tableView.tableHeaderView = nil // tableView.addSubview(headerView) // let views = [ // "tableView": tableView, // "headerView": headerView // ] // tableView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[headerView(==tableView)]|", options: nil, metrics: nil, views: views)) // headerHeight.constant = BASE_HEADER_HEIGHT // tableView.contentOffset = CGPoint(x: 0, y: -headerHeight.constant) loginButton = TWTRLogInButton(logInCompletion: { (session: TWTRSession!, error: NSError!) in if error != nil { NSLog(error.localizedDescription) } else { self.placeLogoutButton() NSLog("Logged in \(session.userName)!") } }) loginButton.center = CGPointMake(self.view.center.x, loginButtonPlaceholder.bounds.size.height / 2); loginButtonPlaceholder.addSubview(loginButton) if Twitter.sharedInstance().session() != nil { placeLogoutButton() } else { placeLoginButton() } logoutButton.layer.cornerRadius = 5; logoutButton.clipsToBounds = true; } override func viewDidAppear(animated: Bool) { TwitterApi.loadTimeline(reactor.evaluateToSwift(TARGET_TIMELINE) as! String) super.viewDidAppear(animated) keys.append(reactor.observe(TIMELINE, handler: { (newState) -> () in self.tableView.reloadData() })) keys.append(reactor.observe(PROFILE, handler: { (newState) -> () in self.refreshProfile() })) // keys.append(reactor.observe(WriteTweetViewController.REPLY, handler: { (newState) -> () in // self.performSegueWithIdentifier("reply", sender: self) // })) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) reactor.unobserve(keys) } func refreshProfile() { let profile = reactor.evaluate(PROFILE) let screenName = profile.getIn(["screen_name"]).toSwift() as? String ?? "unknown" headerHandle.text = "@\(screenName)" headerDisplayName.text = profile.getIn(["name"]).toSwift() as? String ?? "Unknown" if let profileUrl = profile.getIn(["profile_image_url_https"]).toSwift() as? String { let largerUrl = profileUrl.stringByReplacingOccurrencesOfString("normal", withString: "bigger") headerProfile.setImageWithURL(NSURL(string: largerUrl)) } if let backgroundUrl = profile.getIn(["profile_background_image_url_https"]).toSwift() as? String { headerBackground.setImageWithURL(NSURL(string: backgroundUrl)) } let tweetCount = profile.getIn(["statuses_count"]).toSwift() as? Int ?? 0 let followingCount = profile.getIn(["friends_count"]).toSwift() as? Int ?? 0 let followersCount = profile.getIn(["followers_count"]).toSwift() as? Int ?? 0 headerStats.removeAllSegments() headerStats.insertSegmentWithTitle("\(followersCount) FOLLOWERS", atIndex: 0, animated: false) headerStats.insertSegmentWithTitle("\(followingCount) FOLLOWING", atIndex: 0, animated: false) headerStats.insertSegmentWithTitle("\(tweetCount) TWEETS", atIndex: 0, animated: false) self.title = headerDisplayName.text } func fetchTimeline() { TwitterApi.loadTimeline(reactor.evaluateToSwift(TARGET_TIMELINE) as! String) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // TODO: Infinite scroll } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return reactor.evaluate(TIMELINE).count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tweet", forIndexPath: indexPath) as! TweetView cell.tweet = reactor.evaluate(TIMELINE.extendKeyPath([indexPath.row])) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 160 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { reactor.dispatch("setDetail", payload: [ "index": indexPath.row, "source": "timeline" ]) self.performSegueWithIdentifier("TweetDetail", sender: self) } func scrollViewDidScroll(scrollView: UIScrollView) { // let offset = tableView.contentOffset.y // // if offset < -BASE_HEADER_HEIGHT { // headerHeight.constant = BASE_HEADER_HEIGHT - offset //// headerView.setNeedsLayout() // tableView.setNeedsLayout() // headerView.setNeedsLayout() // } else { // headerHeight.constant = BASE_HEADER_HEIGHT // } } // LOGIN/LOGOUT BUTTONS --- MOVE TO HAMBURGER func placeLogoutButton() { loginButton.hidden = true logoutButton.hidden = false } @IBAction func doLogout(sender: UIButton) { Twitter.sharedInstance().logOut() NSLog("Logged out") placeLoginButton() } func placeLoginButton() { logoutButton.hidden = true loginButton.hidden = false } }
mit
7e5493111876e96c80cf92b68b4bcc1b
37.770053
157
0.649331
4.96167
false
false
false
false
TZLike/GiftShow
GiftShow/GiftShow/Classes/CategoryPage/View/LeeCateReusableView.swift
1
1020
// // LeeCateReusableView.swift // GiftShow // // Created by admin on 16/10/26. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } class LeeCateReusableView: UICollectionReusableView { override func awakeFromNib() { super.awakeFromNib() // Initialization code } var model:LeeCategoryModel?{ didSet{ cateLabel.text = model?.name if model?.channels?.count <= 6 { moreBtn.isHidden = true }else { moreBtn.isHidden = false } } } @IBOutlet weak var moreBtn: UIButton! @IBOutlet weak var cateLabel: UILabel! }
apache-2.0
bad8728fb21b822b84bf3d43bc8c42c6
19.755102
64
0.565388
3.823308
false
false
false
false
chuckbrant/HelloWorld
main.swift
2
2259
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ // Kitura-Starter-Bluemix shows examples for creating custom routes. import Foundation import Kitura import KituraSys import KituraNet import LoggerAPI import HeliumLogger import CloudFoundryEnv // All web apps need a Router instance to define routes let router = Router() // Using the HeliumLogger implementation for Logger Log.logger = HeliumLogger() // Serve static content from "public" router.all("/static", middleware: StaticFileServer()) // Basic GET request router.get("/hello") { _, response, next in Log.debug("GET - /hello route handler...") response.headers["Content-Type"] = "text/plain; charset=utf-8" do { try response.status(.OK).send("Hello from Kitura-Starter-Bluemix!").end() } catch { Log.error("Failed to send response to client: \(error)") } } // Basic POST request router.post("/hello") { request, response, next in Log.debug("POST - /hello route handler...") response.headers["Content-Type"] = "text/plain; charset=utf-8" do { if let name = try request.readString() { try response.status(.OK).send("Hello \(name), from Kitura-Starter-Bluemix!").end() } else { try response.status(.OK).send("Kitura-Starter-Bluemix received a POST request!").end() } } catch { Log.error("Failed to send response to client: \(error)") } } // Start Kitura-Starter-Bluemix server do { let appEnv = try CloudFoundryEnv.getAppEnv() let port: Int = appEnv.port let server = HTTPServer.listen(port: port, delegate: router) Log.info("Server will be started on '\(appEnv.url)'.") Server.run() } catch CloudFoundryEnvError.InvalidValue { Log.error("Oops... something went wrong. Server did not start!") }
apache-2.0
25e8cfe39e3746122c399a862b86a90b
31.271429
92
0.717574
3.809444
false
false
false
false
tonyarnold/Bond
Sources/Bond/Observable Collections/TreeChangeset.swift
1
5366
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public protocol TreeChangesetProtocol: ChangesetProtocol where Collection: TreeProtocol, Operation == OrderedCollectionOperation<Collection.Children.Element, IndexPath>, Diff == OrderedCollectionDiff<IndexPath> { var asTreeChangeset: TreeChangeset<Collection> { get } } public final class TreeChangeset<Collection: TreeProtocol>: Changeset<Collection, OrderedCollectionOperation<Collection.Children.Element, IndexPath>, OrderedCollectionDiff<IndexPath>>, TreeChangesetProtocol { public override func calculateDiff(from patch: [OrderedCollectionOperation<Collection.Children.Element, IndexPath>]) -> Diff { return Diff(from: patch) } public override func calculatePatch(from diff: OrderedCollectionDiff<IndexPath>) -> [OrderedCollectionOperation<Collection.Children.Element, IndexPath>] { return diff.generatePatch(to: collection) } public var asTreeChangeset: TreeChangeset<Collection> { return self } } extension MutableChangesetContainerProtocol where Changeset: TreeChangesetProtocol, Changeset.Collection: RangeReplaceableTreeProtocol { public typealias ChildNode = Collection.Children.Element /// Access or update the element at `index`. public subscript(childAt indexPath: IndexPath) -> ChildNode { get { return collection[childAt: indexPath] } set { descriptiveUpdate { (collection) -> [Operation] in collection[childAt: indexPath] = newValue return [.update(at: indexPath, newElement: newValue)] } } } /// Append `newNode` at the end of the root node's children collection. public func append(_ newNode: ChildNode) { descriptiveUpdate { (collection) -> [Operation] in let index: IndexPath = [collection.children.count] collection.append(newNode) return [.insert(newNode, at: index)] } } /// Insert `newNode` at index `i`. public func insert(_ newNode: ChildNode, at index: IndexPath) { descriptiveUpdate { (collection) -> [Operation] in collection.insert(newNode, at: index) return [.insert(newNode, at: index)] } } public func insert(contentsOf newNodes: [ChildNode], at indexPath: IndexPath) { guard newNodes.count > 0 else { return } descriptiveUpdate { (collection) -> [Operation] in collection.insert(contentsOf: newNodes, at: indexPath) let indices = newNodes.indices.map { indexPath.advanced(by: $0, atLevel: indexPath.count-1) } return zip(newNodes, indices).map { Operation.insert($0, at: $1) } } } /// Move the element at index `i` to index `toIndex`. public func move(from fromIndex: IndexPath, to toIndex: IndexPath) { descriptiveUpdate { (collection) -> [Operation] in collection.move(from: fromIndex, to: toIndex) return [.move(from: fromIndex, to: toIndex)] } } public func move(from fromIndices: [IndexPath], to toIndex: IndexPath) { descriptiveUpdate { (collection) -> [Operation] in collection.move(from: fromIndices, to: toIndex) let movesDiff = fromIndices.enumerated().map { (from: $0.element, to: toIndex.advanced(by: $0.offset, atLevel: toIndex.count-1)) } return OrderedCollectionDiff<IndexPath>(inserts: [], deletes: [], updates: [], moves: movesDiff).generatePatch(to: collection) } } /// Remove and return the element at index i. @discardableResult public func remove(at index: IndexPath) -> ChildNode { return descriptiveUpdate { (collection) -> ([Operation], ChildNode) in let element = collection.remove(at: index) return ([.delete(at: index)], element) } } /// Remove all elements from the collection. public func removeAll() { descriptiveUpdate { (collection) -> [Operation] in let deletes = collection.children.indices.map { Operation.delete(at: [$0]) } collection.removeAll() return deletes } } }
mit
d2f9ad3e504cfb259c30acd0f96770a8
40.921875
208
0.673127
4.582408
false
false
false
false
crescentflare/ViewletCreator
ViewletCreatorIOS/ViewletCreator/Classes/ViewletLoader.swift
1
1362
// // ViewletLoader.swift // Viewlet creator Pod // // Library: loading viewlet properties // Load viewlet property definitions from JSON and parses them to attributes (to be used for creation or inflation) // import UIKit public class ViewletLoader { // --- // MARK: Singleton instance // --- private static let shared = ViewletLoader() // --- // MARK: Members // --- private var loadedJson: [String: [String: Any]] = [:] // --- // MARK: Initialization // --- private init() { } // --- // MARK: Loading // --- public static func attributesFrom(jsonFile: String) -> [String: Any]? { if let item = shared.loadedJson[jsonFile] { return item } let bundle = Bundle.main if let path = bundle.path(forResource: jsonFile, ofType: "json") { if let jsonData = try? NSData(contentsOfFile: path, options: .mappedIfSafe) as Data { if let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) { if let jsonDict = json as? [String: Any] { shared.loadedJson[jsonFile] = jsonDict return jsonDict } } } } return nil } }
mit
7d16dbb84fa3555a5944abb6740def8b
22.894737
116
0.5279
4.680412
false
false
false
false
devpunk/cartesian
cartesian/Model/DrawProject/State/MDrawProjectState.swift
1
838
import Foundation class MDrawProjectState { private(set) var current:MDrawProjectStateItem? //MARK: public func stateMoving(controller:CDrawProject) { current = MDrawProjectStateItemMove( controller:controller) } func stateEditing(controller:CDrawProject) { current = MDrawProjectStateItemEdit( controller:controller) } func stateStand(controller:CDrawProject) { current = MDrawProjectStateItemStand( controller:controller) } func stateText(controller:CDrawProject) { current = MDrawProjectStateItemText( controller:controller) } func stateLinking(controller:CDrawProject) { current = MDrawProjectStateItemLink( controller:controller) } }
mit
0b5dd83252d2505e89d12011f6706744
21.052632
51
0.637232
4.816092
false
false
false
false
Haneke/HanekeSwift
Haneke/Log.swift
2
940
// // Log.swift // Haneke // // Created by Hermes Pique on 11/10/14. // Copyright (c) 2014 Haneke. All rights reserved. // import Foundation struct Log { fileprivate static let Tag = "[HANEKE]" fileprivate enum Level : String { case Debug = "[DEBUG]" case Error = "[ERROR]" } fileprivate static func log(_ level: Level, _ message: @autoclosure () -> String, _ error: Error? = nil) { if let error = error { print("\(Tag)\(level.rawValue) \(message()) with error \(error)") } else { print("\(Tag)\(level.rawValue) \(message())") } } static func debug(message: @autoclosure () -> String, error: Error? = nil) { #if DEBUG log(.Debug, message(), error) #endif } static func error(message: @autoclosure () -> String, error: Error? = nil) { log(.Error, message(), error) } }
apache-2.0
517d6d5b1c4bcac8ef5fdfb5d2a67b31
23.736842
110
0.535106
4.034335
false
false
false
false
LoopKit/LoopKit
LoopKitUI/UIColor.swift
1
1321
// // UIColor.swift // LoopKitUI // // Copyright © 2018 LoopKit Authors. All rights reserved. // import UIKit private class FrameworkBundle { static let main = Bundle(for: FrameworkBundle.self) } private func BundleColor(_ name: String, compatibleWith traitCollection: UITraitCollection? = nil) -> UIColor? { return UIColor(named: name, in: FrameworkBundle.main, compatibleWith: traitCollection) } extension UIColor { @nonobjc static let lightenedInsulin = BundleColor("Lightened Insulin") ?? systemOrange @nonobjc static let darkenedInsulin = BundleColor("Darkened Insulin") ?? systemOrange static func interpolatingBetween(_ first: UIColor, _ second: UIColor, biasTowardSecondColor bias: CGFloat = 0.5) -> UIColor { let (r1, g1, b1, a1) = first.components let (r2, g2, b2, a2) = second.components return UIColor( red: (r2 - r1) * bias + r1, green: (g2 - g1) * bias + g1, blue: (b2 - b1) * bias + b1, alpha: (a2 - a1) * bias + a1 ) } var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var r, g, b, a: CGFloat (r, g, b, a) = (0, 0, 0, 0) getRed(&r, green: &g, blue: &b, alpha: &a) return (red: r, green: g, blue: b, alpha: a) } }
mit
a19f9b4f5a2050c3b7ad204744f92835
32.846154
129
0.613636
3.48285
false
false
false
false
google/android-auto-companion-calendarsync-ios
Sources/AndroidAutoCalendarSyncProtos/calendar.pb.swift
1
34182
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: third_party/java_src/android_libs/connecteddevice/java/com/google/android/connecteddevice/calendarsync/proto/calendar.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public struct Aae_Calendarsync_Calendar { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var title: String = String() public var uuid: String = String() public var color: Aae_Calendarsync_Color { get {return _color ?? Aae_Calendarsync_Color()} set {_color = newValue} } /// Returns true if `color` has been explicitly set. public var hasColor: Bool {return self._color != nil} /// Clears the value of `color`. Subsequent reads from it will return its default value. public mutating func clearColor() {self._color = nil} public var event: [Aae_Calendarsync_Event] = [] public var accountName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _color: Aae_Calendarsync_Color? = nil } public struct Aae_Calendarsync_Calendars { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var calendar: [Aae_Calendarsync_Calendar] = [] public var deviceTimeZone: Aae_Calendarsync_TimeZone { get {return _deviceTimeZone ?? Aae_Calendarsync_TimeZone()} set {_deviceTimeZone = newValue} } /// Returns true if `deviceTimeZone` has been explicitly set. public var hasDeviceTimeZone: Bool {return self._deviceTimeZone != nil} /// Clears the value of `deviceTimeZone`. Subsequent reads from it will return its default value. public mutating func clearDeviceTimeZone() {self._deviceTimeZone = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _deviceTimeZone: Aae_Calendarsync_TimeZone? = nil } public struct Aae_Calendarsync_Event { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var title: String { get {return _storage._title} set {_uniqueStorage()._title = newValue} } public var externalIdentifier: String { get {return _storage._externalIdentifier} set {_uniqueStorage()._externalIdentifier = newValue} } public var startDate: Aae_Calendarsync_Timestamp { get {return _storage._startDate ?? Aae_Calendarsync_Timestamp()} set {_uniqueStorage()._startDate = newValue} } /// Returns true if `startDate` has been explicitly set. public var hasStartDate: Bool {return _storage._startDate != nil} /// Clears the value of `startDate`. Subsequent reads from it will return its default value. public mutating func clearStartDate() {_uniqueStorage()._startDate = nil} public var endDate: Aae_Calendarsync_Timestamp { get {return _storage._endDate ?? Aae_Calendarsync_Timestamp()} set {_uniqueStorage()._endDate = newValue} } /// Returns true if `endDate` has been explicitly set. public var hasEndDate: Bool {return _storage._endDate != nil} /// Clears the value of `endDate`. Subsequent reads from it will return its default value. public mutating func clearEndDate() {_uniqueStorage()._endDate = nil} public var timeZone: Aae_Calendarsync_TimeZone { get {return _storage._timeZone ?? Aae_Calendarsync_TimeZone()} set {_uniqueStorage()._timeZone = newValue} } /// Returns true if `timeZone` has been explicitly set. public var hasTimeZone: Bool {return _storage._timeZone != nil} /// Clears the value of `timeZone`. Subsequent reads from it will return its default value. public mutating func clearTimeZone() {_uniqueStorage()._timeZone = nil} public var endTimeZone: Aae_Calendarsync_TimeZone { get {return _storage._endTimeZone ?? Aae_Calendarsync_TimeZone()} set {_uniqueStorage()._endTimeZone = newValue} } /// Returns true if `endTimeZone` has been explicitly set. public var hasEndTimeZone: Bool {return _storage._endTimeZone != nil} /// Clears the value of `endTimeZone`. Subsequent reads from it will return its default value. public mutating func clearEndTimeZone() {_uniqueStorage()._endTimeZone = nil} public var isAllDay: Bool { get {return _storage._isAllDay} set {_uniqueStorage()._isAllDay = newValue} } public var location: String { get {return _storage._location} set {_uniqueStorage()._location = newValue} } public var description_p: String { get {return _storage._description_p} set {_uniqueStorage()._description_p = newValue} } public var color: Aae_Calendarsync_Color { get {return _storage._color ?? Aae_Calendarsync_Color()} set {_uniqueStorage()._color = newValue} } /// Returns true if `color` has been explicitly set. public var hasColor: Bool {return _storage._color != nil} /// Clears the value of `color`. Subsequent reads from it will return its default value. public mutating func clearColor() {_uniqueStorage()._color = nil} public var status: Aae_Calendarsync_Event.Status { get {return _storage._status} set {_uniqueStorage()._status = newValue} } public var organizer: String { get {return _storage._organizer} set {_uniqueStorage()._organizer = newValue} } public var attendee: [Aae_Calendarsync_Attendee] { get {return _storage._attendee} set {_uniqueStorage()._attendee = newValue} } public var creationDate: Aae_Calendarsync_Timestamp { get {return _storage._creationDate ?? Aae_Calendarsync_Timestamp()} set {_uniqueStorage()._creationDate = newValue} } /// Returns true if `creationDate` has been explicitly set. public var hasCreationDate: Bool {return _storage._creationDate != nil} /// Clears the value of `creationDate`. Subsequent reads from it will return its default value. public mutating func clearCreationDate() {_uniqueStorage()._creationDate = nil} public var lastModifiedDate: Aae_Calendarsync_Timestamp { get {return _storage._lastModifiedDate ?? Aae_Calendarsync_Timestamp()} set {_uniqueStorage()._lastModifiedDate = newValue} } /// Returns true if `lastModifiedDate` has been explicitly set. public var hasLastModifiedDate: Bool {return _storage._lastModifiedDate != nil} /// Clears the value of `lastModifiedDate`. Subsequent reads from it will return its default value. public mutating func clearLastModifiedDate() {_uniqueStorage()._lastModifiedDate = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public enum Status: SwiftProtobuf.Enum { public typealias RawValue = Int case unspecifiedStatus // = 0 case tentative // = 1 case confirmed // = 2 case canceled // = 3 case UNRECOGNIZED(Int) public init() { self = .unspecifiedStatus } public init?(rawValue: Int) { switch rawValue { case 0: self = .unspecifiedStatus case 1: self = .tentative case 2: self = .confirmed case 3: self = .canceled default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unspecifiedStatus: return 0 case .tentative: return 1 case .confirmed: return 2 case .canceled: return 3 case .UNRECOGNIZED(let i): return i } } } public init() {} fileprivate var _storage = _StorageClass.defaultInstance } #if swift(>=4.2) extension Aae_Calendarsync_Event.Status: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Aae_Calendarsync_Event.Status] = [ .unspecifiedStatus, .tentative, .confirmed, .canceled, ] } #endif // swift(>=4.2) public struct Aae_Calendarsync_Color { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var argb: Int32 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Aae_Calendarsync_Attendee { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var name: String = String() public var email: String = String() public var status: Aae_Calendarsync_Attendee.Status = .unspecifiedStatus public var type: Aae_Calendarsync_Attendee.TypeEnum = .unspecifiedType public var unknownFields = SwiftProtobuf.UnknownStorage() public enum Status: SwiftProtobuf.Enum { public typealias RawValue = Int case unspecifiedStatus // = 0 case noneStatus // = 1 case accepted // = 2 case declined // = 3 case invited // = 4 case tentative // = 5 case UNRECOGNIZED(Int) public init() { self = .unspecifiedStatus } public init?(rawValue: Int) { switch rawValue { case 0: self = .unspecifiedStatus case 1: self = .noneStatus case 2: self = .accepted case 3: self = .declined case 4: self = .invited case 5: self = .tentative default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unspecifiedStatus: return 0 case .noneStatus: return 1 case .accepted: return 2 case .declined: return 3 case .invited: return 4 case .tentative: return 5 case .UNRECOGNIZED(let i): return i } } } public enum TypeEnum: SwiftProtobuf.Enum { public typealias RawValue = Int case unspecifiedType // = 0 case noneType // = 1 case `optional` // = 2 case `required` // = 3 case resource // = 4 case UNRECOGNIZED(Int) public init() { self = .unspecifiedType } public init?(rawValue: Int) { switch rawValue { case 0: self = .unspecifiedType case 1: self = .noneType case 2: self = .optional case 3: self = .required case 4: self = .resource default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unspecifiedType: return 0 case .noneType: return 1 case .optional: return 2 case .required: return 3 case .resource: return 4 case .UNRECOGNIZED(let i): return i } } } public init() {} } #if swift(>=4.2) extension Aae_Calendarsync_Attendee.Status: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Aae_Calendarsync_Attendee.Status] = [ .unspecifiedStatus, .noneStatus, .accepted, .declined, .invited, .tentative, ] } extension Aae_Calendarsync_Attendee.TypeEnum: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Aae_Calendarsync_Attendee.TypeEnum] = [ .unspecifiedType, .noneType, .optional, .required, .resource, ] } #endif // swift(>=4.2) public struct Aae_Calendarsync_Timestamp { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var seconds: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Aae_Calendarsync_TimeZone { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var name: String = String() public var secondsFromGmt: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "aae.calendarsync" extension Aae_Calendarsync_Calendar: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Calendar" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "title"), 2: .same(proto: "uuid"), 3: .same(proto: "color"), 4: .same(proto: "event"), 5: .standard(proto: "account_name"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.title) }() case 2: try { try decoder.decodeSingularStringField(value: &self.uuid) }() case 3: try { try decoder.decodeSingularMessageField(value: &self._color) }() case 4: try { try decoder.decodeRepeatedMessageField(value: &self.event) }() case 5: try { try decoder.decodeSingularStringField(value: &self.accountName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !self.title.isEmpty { try visitor.visitSingularStringField(value: self.title, fieldNumber: 1) } if !self.uuid.isEmpty { try visitor.visitSingularStringField(value: self.uuid, fieldNumber: 2) } try { if let v = self._color { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } }() if !self.event.isEmpty { try visitor.visitRepeatedMessageField(value: self.event, fieldNumber: 4) } if !self.accountName.isEmpty { try visitor.visitSingularStringField(value: self.accountName, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_Calendar, rhs: Aae_Calendarsync_Calendar) -> Bool { if lhs.title != rhs.title {return false} if lhs.uuid != rhs.uuid {return false} if lhs._color != rhs._color {return false} if lhs.event != rhs.event {return false} if lhs.accountName != rhs.accountName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Aae_Calendarsync_Calendars: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Calendars" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "calendar"), 2: .standard(proto: "device_time_zone"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.calendar) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._deviceTimeZone) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !self.calendar.isEmpty { try visitor.visitRepeatedMessageField(value: self.calendar, fieldNumber: 1) } try { if let v = self._deviceTimeZone { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } }() try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_Calendars, rhs: Aae_Calendarsync_Calendars) -> Bool { if lhs.calendar != rhs.calendar {return false} if lhs._deviceTimeZone != rhs._deviceTimeZone {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Aae_Calendarsync_Event: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Event" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "title"), 2: .standard(proto: "external_identifier"), 3: .standard(proto: "start_date"), 4: .standard(proto: "end_date"), 5: .standard(proto: "time_zone"), 6: .standard(proto: "end_time_zone"), 7: .standard(proto: "is_all_day"), 8: .same(proto: "location"), 9: .same(proto: "description"), 10: .same(proto: "color"), 11: .same(proto: "status"), 12: .same(proto: "organizer"), 13: .same(proto: "attendee"), 14: .standard(proto: "creation_date"), 15: .standard(proto: "last_modified_date"), ] fileprivate class _StorageClass { var _title: String = String() var _externalIdentifier: String = String() var _startDate: Aae_Calendarsync_Timestamp? = nil var _endDate: Aae_Calendarsync_Timestamp? = nil var _timeZone: Aae_Calendarsync_TimeZone? = nil var _endTimeZone: Aae_Calendarsync_TimeZone? = nil var _isAllDay: Bool = false var _location: String = String() var _description_p: String = String() var _color: Aae_Calendarsync_Color? = nil var _status: Aae_Calendarsync_Event.Status = .unspecifiedStatus var _organizer: String = String() var _attendee: [Aae_Calendarsync_Attendee] = [] var _creationDate: Aae_Calendarsync_Timestamp? = nil var _lastModifiedDate: Aae_Calendarsync_Timestamp? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _title = source._title _externalIdentifier = source._externalIdentifier _startDate = source._startDate _endDate = source._endDate _timeZone = source._timeZone _endTimeZone = source._endTimeZone _isAllDay = source._isAllDay _location = source._location _description_p = source._description_p _color = source._color _status = source._status _organizer = source._organizer _attendee = source._attendee _creationDate = source._creationDate _lastModifiedDate = source._lastModifiedDate } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &_storage._title) }() case 2: try { try decoder.decodeSingularStringField(value: &_storage._externalIdentifier) }() case 3: try { try decoder.decodeSingularMessageField(value: &_storage._startDate) }() case 4: try { try decoder.decodeSingularMessageField(value: &_storage._endDate) }() case 5: try { try decoder.decodeSingularMessageField(value: &_storage._timeZone) }() case 6: try { try decoder.decodeSingularMessageField(value: &_storage._endTimeZone) }() case 7: try { try decoder.decodeSingularBoolField(value: &_storage._isAllDay) }() case 8: try { try decoder.decodeSingularStringField(value: &_storage._location) }() case 9: try { try decoder.decodeSingularStringField(value: &_storage._description_p) }() case 10: try { try decoder.decodeSingularMessageField(value: &_storage._color) }() case 11: try { try decoder.decodeSingularEnumField(value: &_storage._status) }() case 12: try { try decoder.decodeSingularStringField(value: &_storage._organizer) }() case 13: try { try decoder.decodeRepeatedMessageField(value: &_storage._attendee) }() case 14: try { try decoder.decodeSingularMessageField(value: &_storage._creationDate) }() case 15: try { try decoder.decodeSingularMessageField(value: &_storage._lastModifiedDate) }() default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 if !_storage._title.isEmpty { try visitor.visitSingularStringField(value: _storage._title, fieldNumber: 1) } if !_storage._externalIdentifier.isEmpty { try visitor.visitSingularStringField(value: _storage._externalIdentifier, fieldNumber: 2) } try { if let v = _storage._startDate { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } }() try { if let v = _storage._endDate { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } }() try { if let v = _storage._timeZone { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } }() try { if let v = _storage._endTimeZone { try visitor.visitSingularMessageField(value: v, fieldNumber: 6) } }() if _storage._isAllDay != false { try visitor.visitSingularBoolField(value: _storage._isAllDay, fieldNumber: 7) } if !_storage._location.isEmpty { try visitor.visitSingularStringField(value: _storage._location, fieldNumber: 8) } if !_storage._description_p.isEmpty { try visitor.visitSingularStringField(value: _storage._description_p, fieldNumber: 9) } try { if let v = _storage._color { try visitor.visitSingularMessageField(value: v, fieldNumber: 10) } }() if _storage._status != .unspecifiedStatus { try visitor.visitSingularEnumField(value: _storage._status, fieldNumber: 11) } if !_storage._organizer.isEmpty { try visitor.visitSingularStringField(value: _storage._organizer, fieldNumber: 12) } if !_storage._attendee.isEmpty { try visitor.visitRepeatedMessageField(value: _storage._attendee, fieldNumber: 13) } try { if let v = _storage._creationDate { try visitor.visitSingularMessageField(value: v, fieldNumber: 14) } }() try { if let v = _storage._lastModifiedDate { try visitor.visitSingularMessageField(value: v, fieldNumber: 15) } }() } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_Event, rhs: Aae_Calendarsync_Event) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._title != rhs_storage._title {return false} if _storage._externalIdentifier != rhs_storage._externalIdentifier {return false} if _storage._startDate != rhs_storage._startDate {return false} if _storage._endDate != rhs_storage._endDate {return false} if _storage._timeZone != rhs_storage._timeZone {return false} if _storage._endTimeZone != rhs_storage._endTimeZone {return false} if _storage._isAllDay != rhs_storage._isAllDay {return false} if _storage._location != rhs_storage._location {return false} if _storage._description_p != rhs_storage._description_p {return false} if _storage._color != rhs_storage._color {return false} if _storage._status != rhs_storage._status {return false} if _storage._organizer != rhs_storage._organizer {return false} if _storage._attendee != rhs_storage._attendee {return false} if _storage._creationDate != rhs_storage._creationDate {return false} if _storage._lastModifiedDate != rhs_storage._lastModifiedDate {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Aae_Calendarsync_Event.Status: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNSPECIFIED_STATUS"), 1: .same(proto: "TENTATIVE"), 2: .same(proto: "CONFIRMED"), 3: .same(proto: "CANCELED"), ] } extension Aae_Calendarsync_Color: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Color" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "argb"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt32Field(value: &self.argb) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.argb != 0 { try visitor.visitSingularInt32Field(value: self.argb, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_Color, rhs: Aae_Calendarsync_Color) -> Bool { if lhs.argb != rhs.argb {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Aae_Calendarsync_Attendee: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Attendee" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .same(proto: "email"), 3: .same(proto: "status"), 4: .same(proto: "type"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() case 2: try { try decoder.decodeSingularStringField(value: &self.email) }() case 3: try { try decoder.decodeSingularEnumField(value: &self.status) }() case 4: try { try decoder.decodeSingularEnumField(value: &self.type) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } if !self.email.isEmpty { try visitor.visitSingularStringField(value: self.email, fieldNumber: 2) } if self.status != .unspecifiedStatus { try visitor.visitSingularEnumField(value: self.status, fieldNumber: 3) } if self.type != .unspecifiedType { try visitor.visitSingularEnumField(value: self.type, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_Attendee, rhs: Aae_Calendarsync_Attendee) -> Bool { if lhs.name != rhs.name {return false} if lhs.email != rhs.email {return false} if lhs.status != rhs.status {return false} if lhs.type != rhs.type {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Aae_Calendarsync_Attendee.Status: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNSPECIFIED_STATUS"), 1: .same(proto: "NONE_STATUS"), 2: .same(proto: "ACCEPTED"), 3: .same(proto: "DECLINED"), 4: .same(proto: "INVITED"), 5: .same(proto: "TENTATIVE"), ] } extension Aae_Calendarsync_Attendee.TypeEnum: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNSPECIFIED_TYPE"), 1: .same(proto: "NONE_TYPE"), 2: .same(proto: "OPTIONAL"), 3: .same(proto: "REQUIRED"), 4: .same(proto: "RESOURCE"), ] } extension Aae_Calendarsync_Timestamp: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Timestamp" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "seconds"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.seconds) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.seconds != 0 { try visitor.visitSingularInt64Field(value: self.seconds, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_Timestamp, rhs: Aae_Calendarsync_Timestamp) -> Bool { if lhs.seconds != rhs.seconds {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Aae_Calendarsync_TimeZone: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".TimeZone" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "name"), 2: .standard(proto: "seconds_from_gmt"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.name) }() case 2: try { try decoder.decodeSingularInt64Field(value: &self.secondsFromGmt) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 1) } if self.secondsFromGmt != 0 { try visitor.visitSingularInt64Field(value: self.secondsFromGmt, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Aae_Calendarsync_TimeZone, rhs: Aae_Calendarsync_TimeZone) -> Bool { if lhs.name != rhs.name {return false} if lhs.secondsFromGmt != rhs.secondsFromGmt {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
apache-2.0
169a84c3d049e7c713e41dd807ce6b7a
37.887372
138
0.693289
4.308293
false
false
false
false
davidrauch/mds
mds/Processing/Parser.swift
1
1847
import Foundation // A markdown header public struct Header { // The line at which the header appears in the document let line: Int // The depth (level) of the header let depth: Int // The text of the header let text: String } // The Parser class Parser { // The list of tokens to parse let tokens: [Token] // Where we are in the list of tokens var index = 0 /** Initializes a new parser with a list of tokens to parse - Parameters: - tokens: The list of tokens to parse - Returns: A Parser object */ init(tokens: [Token]) { self.tokens = tokens } /** Returns the current token without advancing the index - Returns: The current token */ private func peekToken() -> Token? { if index >= tokens.count { return nil } return tokens[index] } /** Return the current token and advances the index - Returns: The current token */ private func popToken() -> Token { let token = tokens[index] index = index + 1 return token } /** Parses a list of tokens - Returns: A list of Headers */ func parse() -> [Header] { var nodes = [Header]() // Iterate over all tokens while index < tokens.count { let token = popToken() switch token { // Keep all headers case .Header(let line, let depth, let text): nodes.append(Header(line: line, depth: depth, text: text)); // For text tokens, check the next token case .Text(let line, let text): if let nextToken = peekToken() { switch nextToken { case .UnderlineHeader1: nodes.append(Header(line: line, depth: 1, text: text)) _ = popToken() case .UnderlineHeader2: nodes.append(Header(line: line, depth: 2, text: text)) _ = popToken() default: () } } else { () } default: () } } return nodes } }
mit
cdeb341a9fa30d7048ec421fd639e2b5
17.287129
63
0.615593
3.364299
false
false
false
false
Fenrikur/ef-app_ios
Pods/Down/Source/Renderers/DownGroffRenderable.swift
1
2192
// // DownGroffRenderable.swift // Down // // Created by Rob Phillips on 5/31/16. // Copyright © 2016-2019 Glazed Donut, LLC. All rights reserved. // import Foundation import libcmark public protocol DownGroffRenderable: DownRenderable { func toGroff(_ options: DownOptions, width: Int32) throws -> String } extension DownGroffRenderable { /// Generates a groff man string from the `markdownString` property /// /// - Parameters: /// - options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - width: The width to break on, defaulting to 0 /// - Returns: groff man string /// - Throws: `DownErrors` depending on the scenario public func toGroff(_ options: DownOptions = .default, width: Int32 = 0) throws -> String { let ast = try DownASTRenderer.stringToAST(markdownString, options: options) let groff = try DownGroffRenderer.astToGroff(ast, options: options, width: width) cmark_node_free(ast) return groff } } public struct DownGroffRenderer { /// Generates a groff man string from the given abstract syntax tree /// /// **Note:** caller is responsible for calling `cmark_node_free(ast)` after this returns /// /// - Parameters: /// - ast: The `cmark_node` representing the abstract syntax tree /// - options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - width: The width to break on, defaulting to 0 /// - Returns: groff man string /// - Throws: `ASTRenderingError` if the AST could not be converted public static func astToGroff(_ ast: UnsafeMutablePointer<cmark_node>, options: DownOptions = .default, width: Int32 = 0) throws -> String { guard let cGroffString = cmark_render_man(ast, options.rawValue, width) else { throw DownErrors.astRenderingError } defer { free(cGroffString) } guard let groffString = String(cString: cGroffString, encoding: String.Encoding.utf8) else { throw DownErrors.astRenderingError } return groffString } }
mit
0bc73f37ae94d6463cf7597f5476cf19
37.438596
100
0.646737
4.110694
false
false
false
false
dirk/Speedy
Speedy/Group.swift
1
1247
public class Example { let name: String let block: () -> () init(_ name: String, _ block: () -> ()) { self.name = name self.block = block } } public class Group { enum Child { case ChildGroup(Group) case ChildExample(Example) func value() -> AnyObject { switch self { case let .ChildGroup(group): return group case let .ChildExample(example): return example } } } let name: String var children = [Child]() var parent: Group? = nil var beforeEachHooks = [Hook]() var afterEachHooks = [Hook]() var beforeAllHooks = [Hook]() var afterAllHooks = [Hook]() init(_ name: String) { self.name = name } func addChild(child: AnyObject) { switch child { case let group as Group: children.append(Child.ChildGroup(group)) case let example as Example: children.append(Child.ChildExample(example)) default: assert(false, "Unreachable!") } } func addHook(hook: Hook) { switch hook.kind { case .BeforeEach: beforeEachHooks.append(hook) case .AfterEach: afterEachHooks.append(hook) case .BeforeAll: beforeAllHooks.append(hook) case .AfterAll: afterAllHooks.append(hook) } } }
bsd-3-clause
1e6531226b86ae64ac81a827bf5be3c7
19.442623
53
0.615878
3.790274
false
false
false
false
DikeyKing/WeCenterMobile-iOS
WeCenterMobile/View/Answer/AnswerCell.swift
1
2174
// // AnswerCell.swift // WeCenterMobile // // Created by Darren Liu on 15/3/29. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class AnswerCell: UITableViewCell { var answer: Answer? @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var answerBodyLabel: MSRMultilineLabel! @IBOutlet weak var userAvatarView: MSRRoundedImageView! @IBOutlet weak var agreementCountLabel: UILabel! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var answerButton: UIButton! @IBOutlet weak var separator: UIView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var answerContainerView: UIView! override func awakeFromNib() { super.awakeFromNib() msr_scrollView?.delaysContentTouches = false let theme = SettingsManager.defaultManager.currentTheme for v in [containerView, agreementCountLabel] { v.msr_borderColor = theme.borderColorA } for v in [userButton, answerButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } for v in [agreementCountLabel, answerBodyLabel] { v.textColor = theme.subtitleTextColor } for v in [userContainerView, answerContainerView] { v.backgroundColor = theme.backgroundColorB } agreementCountLabel.backgroundColor = theme.backgroundColorA separator.backgroundColor = theme.borderColorA userNameLabel.textColor = theme.titleTextColor } func update(#answer: Answer, updateImage: Bool) { self.answer = answer userNameLabel.text = answer.user?.name ?? "匿名用户" answerBodyLabel.text = answer.body?.wc_plainString agreementCountLabel.text = "\(answer.agreementCount ?? 0)" userButton.msr_userInfo = answer.user answerButton.msr_userInfo = answer if updateImage { userAvatarView.wc_updateWithUser(answer.user) } setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
d2a2ade049857d535dcf3dd5566d67e6
34.47541
99
0.678835
5.079812
false
false
false
false
Legoless/ViewModelable
ViewModelable/ModelableViewController.swift
1
2634
// // ModelableViewController.swift // ViewModelable // // Created by Dal Rupnik on 06/06/16. // Copyright © 2016 Unified Sense. All rights reserved. // import UIKit open class ModelableViewController <T : ViewModel> : UIViewController, ViewModelObservable { public var viewModel : T = T() deinit { NotificationCenter.default.removeObserver(self) } open override func viewDidLoad() { super.viewDidLoad() viewModel.observer = self for childViewModel in viewModel.childViewModels { childViewModel.observer = self } viewModel.setup() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModel.load() } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewModel.unload() } public func viewModelDidSetup (_ viewModel: ViewModel) { guard let viewModel = viewModel as? T else { return } viewModelDidSetup(viewModel: viewModel) } public func viewModelWillLoad (_ viewModel: ViewModel) { guard let viewModel = viewModel as? T else { return } viewModelWillLoad(viewModel: viewModel) } public func viewModelDidLoad (_ viewModel: ViewModel) { guard let viewModel = viewModel as? T else { return } viewModelDidLoad(viewModel: viewModel) } public func viewModelDidUpdate (_ viewModel: ViewModel, updates: [String : Any]) { guard let viewModel = viewModel as? T else { return } viewModelDidUpdate(viewModel: viewModel, updates: updates) } public func viewModelWillUnload (_ viewModel: ViewModel) { guard let viewModel = viewModel as? T else { return } viewModelWillUnload(viewModel: viewModel) } public func viewModelDidUnload (_ viewModel: ViewModel) { guard let viewModel = viewModel as? T else { return } viewModelDidUnload(viewModel: viewModel) } open func viewModelDidSetup (viewModel: T) { } open func viewModelWillLoad (viewModel: T) { } open func viewModelDidLoad (viewModel: T) { } open func viewModelDidUpdate (viewModel: T, updates: [String : Any]) { } open func viewModelWillUnload (viewModel: T) { } open func viewModelDidUnload (viewModel: T) { } }
mit
8dd8675356f9c211a413b7c128936b76
23.607477
92
0.593999
5.234592
false
false
false
false
xianglin123/douyuzhibo
douyuzhibo/douyuzhibo/Classes/Tools/UIBarButtonItem+Ext.swift
1
738
// // UIBarButtonItem+Ext.swift // douyuzhibo // // Created by xianglin on 16/10/4. // Copyright © 2016年 xianglin. All rights reserved. // import UIKit extension UIBarButtonItem { convenience init(normalImageName : String , highImageName : String = "" , size : CGSize = CGSize.zero) { let btn = UIButton() btn.setImage(UIImage(named: normalImageName), for: UIControlState()) if highImageName != "" { btn.setImage(UIImage(named: highImageName), for: .highlighted) } if size == CGSize.zero { btn.sizeToFit() }else{ btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) } self.init(customView : btn) } }
apache-2.0
d7022a33338d118bb02e88c0d893577b
26.222222
108
0.587755
3.994565
false
false
false
false
lllyyy/LY
U17-master/U17/U17/Extension/UIColorExtension.swift
1
2133
// // UIColorExtension.swift // U17 // // Created by charles on 2017/7/31. // Copyright © 2017年 charles. All rights reserved. // import UIKit extension UIColor { convenience init(r:UInt32 ,g:UInt32 , b:UInt32 , a:CGFloat = 1.0) { self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a) } class var random: UIColor { return UIColor(r: arc4random_uniform(256), g: arc4random_uniform(256), b: arc4random_uniform(256)) } func image() -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(self.cgColor) context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } class func hex(hexString: String) -> UIColor { var cString: String = hexString.trimmingCharacters(in: .whitespacesAndNewlines) if cString.count < 6 { return UIColor.black } let index = cString.index(cString.endIndex, offsetBy: -6) let subString = cString[index...] if cString.hasPrefix("0X") { cString = String(subString) } if cString.hasPrefix("#") { cString = String(subString) } if cString.count != 6 { return UIColor.black } var range: NSRange = NSMakeRange(0, 2) let rString = (cString as NSString).substring(with: range) range.location = 2 let gString = (cString as NSString).substring(with: range) range.location = 4 let bString = (cString as NSString).substring(with: range) var r: UInt32 = 0x0 var g: UInt32 = 0x0 var b: UInt32 = 0x0 Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) return UIColor(r: r, g: g, b: b) } }
mit
0ab682ac1b0169b7d82bb4d9e30f06da
31.272727
87
0.578404
4.168297
false
false
false
false
clarenceji/Clarence-Ji
Clarence Ji/ViewController.swift
1
2974
// // ViewController.swift // Clarence Ji // // Created by Clarence Ji on 2/16/15. // Copyright (c) 2015 Clarence Ji. All rights reserved. // import UIKit class ViewController: UIViewController, UIViewControllerTransitioningDelegate { @IBOutlet var activityIndicator: UIActivityIndicatorView! @IBOutlet var imageView_Background: UIImageView! let transitionManager = CJViewTransition() override func viewDidLoad() { super.viewDidLoad() // Load Launch Image on First View var launchImageName = "" switch UIScreen.main.bounds.size.height { case 480: launchImageName = "[email protected]" case 568: launchImageName = "[email protected]" case 667: launchImageName = "[email protected]" case 736: launchImageName = "[email protected]" case 812: launchImageName = "SuperRetina_5.8.jpg" default: launchImageName = "LaunchImage" } imageView_Background.image = UIImage(named: launchImageName) // let currentDate = NSDate() let calendar = Calendar.current let components = (calendar as NSCalendar).components([.hour, .minute], from: Date()) let currentHour = components.hour if currentHour! >= 18 || currentHour! <= 6 { UserDefaults.standard.set(true, forKey: "DarkMode") } else { UserDefaults.standard.set(false, forKey: "DarkMode") } } override func viewDidAppear(_ animated: Bool) { CJAltimeter().getPressure { (success, reading) -> Void in if success { UserDefaults.standard.set(reading!, forKey: "AltimeterReading") UserDefaults.standard.set(true, forKey: "AltimeterReadingReady") } self.activityIndicator.stopAnimating() self.transitToNextView() } } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self.transitionManager } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self.transitionManager } func transitToNextView() { let nextView = self.storyboard!.instantiateViewController(withIdentifier: "CJNavView1") as! CJNavView1 nextView.transitioningDelegate = self nextView.modalPresentationStyle = .custom self.present(nextView, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } }
gpl-3.0
2d0a8a6cb3889912b5933bbf8b42db7f
32.795455
170
0.643578
5.190227
false
false
false
false
luckymore0520/leetcode
SearchForRange.playground/Contents.swift
1
1727
//: Playground - noun: a place where people can play import UIKit //Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. // //Your algorithm's runtime complexity must be in the order of O(log n). // //If the target is not found in the array, return [-1, -1]. // //For example, //Given [5, 7, 7, 8, 8, 10] and target value 8, //return [3, 4]. //二分 class Solution { func searchRange(_ nums: [Int], _ target: Int) -> [Int] { let location = binarySearch(nums, target, start: 0, end: nums.count-1) //左边的 var left = location while (true) { let result = binarySearch(nums, target, start: 0, end: left - 1) if (result == -1) { break; } else { left = result } } var right = location while (true) { let result = binarySearch(nums, target, start: right+1, end: nums.count-1) if (result == -1) { break; } else { right = result } } return [left,right] } func binarySearch(_ nums:[Int], _ target:Int, start:Int, end:Int) -> Int { if (start > end) { return -1 } let middle = (start + end) / 2 if (nums[middle] > target) { return binarySearch(nums, target, start: start, end: middle-1) } else if (nums[middle] < target) { return binarySearch(nums, target, start: middle + 1, end: end) } else { return middle } } } let solution = Solution() solution.searchRange([5,7,7,8,8,10], 7)
mit
9ee1bf573af6405347911144a54e7976
26.709677
118
0.516599
3.875847
false
false
false
false
e78l/swift-corelibs-foundation
TestFoundation/TestXMLParser.swift
2
8614
// 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 // enum XMLParserDelegateEvent { case startDocument case endDocument case didStartElement(String, String?, String?, [String: String]) case didEndElement(String, String?, String?) case foundCharacters(String) } extension XMLParserDelegateEvent: Equatable { public static func ==(lhs: XMLParserDelegateEvent, rhs: XMLParserDelegateEvent) -> Bool { switch (lhs, rhs) { case (.startDocument, startDocument): return true case (.endDocument, endDocument): return true case let (.didStartElement(lhsElement, lhsNamespace, lhsQname, lhsAttr), didStartElement(rhsElement, rhsNamespace, rhsQname, rhsAttr)): return lhsElement == rhsElement && lhsNamespace == rhsNamespace && lhsQname == rhsQname && lhsAttr == rhsAttr case let (.didEndElement(lhsElement, lhsNamespace, lhsQname), .didEndElement(rhsElement, rhsNamespace, rhsQname)): return lhsElement == rhsElement && lhsNamespace == rhsNamespace && lhsQname == rhsQname case let (.foundCharacters(lhsChar), .foundCharacters(rhsChar)): return lhsChar == rhsChar default: return false } } } class XMLParserDelegateEventStream: NSObject, XMLParserDelegate { var events: [XMLParserDelegateEvent] = [] func parserDidStartDocument(_ parser: XMLParser) { events.append(.startDocument) } func parserDidEndDocument(_ parser: XMLParser) { events.append(.endDocument) } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { events.append(.didStartElement(elementName, namespaceURI, qName, attributeDict)) } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { events.append(.didEndElement(elementName, namespaceURI, qName)) } func parser(_ parser: XMLParser, foundCharacters string: String) { events.append(.foundCharacters(string)) } } class TestXMLParser : XCTestCase { static var allTests: [(String, (TestXMLParser) -> () throws -> Void)] { return [ ("test_withData", test_withData), ("test_withDataEncodings", test_withDataEncodings), ("test_withDataOptions", test_withDataOptions), ("test_sr9758_abortParsing", test_sr9758_abortParsing), ("test_sr10157_swappedElementNames", test_sr10157_swappedElementNames), ] } // Helper method to embed the correct encoding in the XML header static func xmlUnderTest(encoding: String.Encoding? = nil) -> String { let xmlUnderTest = "<test attribute='value'><foo>bar</foo></test>" guard var encoding = encoding?.description else { return xmlUnderTest } if let open = encoding.range(of: "(") { let range: Range<String.Index> = open.upperBound..<encoding.endIndex encoding = String(encoding[range]) } if let close = encoding.range(of: ")") { encoding = String(encoding[..<close.lowerBound]) } return "<?xml version='1.0' encoding='\(encoding.uppercased())' standalone='no'?>\n\(xmlUnderTest)\n" } static func xmlUnderTestExpectedEvents(namespaces: Bool = false) -> [XMLParserDelegateEvent] { let uri: String? = namespaces ? "" : nil return [ .startDocument, .didStartElement("test", uri, namespaces ? "test" : nil, ["attribute": "value"]), .didStartElement("foo", uri, namespaces ? "foo" : nil, [:]), .foundCharacters("bar"), .didEndElement("foo", uri, namespaces ? "foo" : nil), .didEndElement("test", uri, namespaces ? "test" : nil), ] } func test_withData() { let xml = Array(TestXMLParser.xmlUnderTest().utf8CString) let data = xml.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<CChar>) -> Data in return buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout<CChar>.stride) { return Data(bytes: $0, count: buffer.count) } } let parser = XMLParser(data: data) let stream = XMLParserDelegateEventStream() parser.delegate = stream let res = parser.parse() XCTAssertEqual(stream.events, TestXMLParser.xmlUnderTestExpectedEvents()) XCTAssertTrue(res) } func test_withDataEncodings() { // If th <?xml header isn't present, any non-UTF8 encodings fail. This appears to be libxml2 behavior. // These don't work, it may just be an issue with the `encoding=xxx`. // - .nextstep, .utf32LittleEndian let encodings: [String.Encoding] = [.utf16LittleEndian, .utf16BigEndian, .utf32BigEndian, .ascii] for encoding in encodings { let xml = TestXMLParser.xmlUnderTest(encoding: encoding) let parser = XMLParser(data: xml.data(using: encoding)!) let stream = XMLParserDelegateEventStream() parser.delegate = stream let res = parser.parse() XCTAssertEqual(stream.events, TestXMLParser.xmlUnderTestExpectedEvents()) XCTAssertTrue(res) } } func test_withDataOptions() { let xml = TestXMLParser.xmlUnderTest() let parser = XMLParser(data: xml.data(using: .utf8)!) parser.shouldProcessNamespaces = true parser.shouldReportNamespacePrefixes = true parser.shouldResolveExternalEntities = true let stream = XMLParserDelegateEventStream() parser.delegate = stream let res = parser.parse() XCTAssertEqual(stream.events, TestXMLParser.xmlUnderTestExpectedEvents(namespaces: true) ) XCTAssertTrue(res) } func test_sr9758_abortParsing() { class Delegate: NSObject, XMLParserDelegate { func parserDidStartDocument(_ parser: XMLParser) { parser.abortParsing() } } let xml = TestXMLParser.xmlUnderTest(encoding: .utf8) let parser = XMLParser(data: xml.data(using: .utf8)!) let delegate = Delegate() parser.delegate = delegate XCTAssertFalse(parser.parse()) XCTAssertNotNil(parser.parserError) } func test_sr10157_swappedElementNames() { class ElementNameChecker: NSObject, XMLParserDelegate { let name: String init(_ name: String) { self.name = name } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) { if parser.shouldProcessNamespaces { XCTAssertEqual(self.name, qName) } else { XCTAssertEqual(self.name, elementName) } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if parser.shouldProcessNamespaces { XCTAssertEqual(self.name, qName) } else { XCTAssertEqual(self.name, elementName) } } func check() { let elementString = "<\(self.name) />" var parser = XMLParser(data: elementString.data(using: .utf8)!) parser.delegate = self XCTAssertTrue(parser.parse()) // Confirm that the parts of QName is also not swapped. parser = XMLParser(data: elementString.data(using: .utf8)!) parser.delegate = self parser.shouldProcessNamespaces = true XCTAssertTrue(parser.parse()) } } ElementNameChecker("noPrefix").check() ElementNameChecker("myPrefix:myLocalName").check() } }
apache-2.0
7cd2009eb81a2daf89e66e4435875452
41.433498
173
0.613536
4.961982
false
true
false
false
ben-ng/swift
benchmark/single-source/IterateData.swift
1
939
//===--- IterateData.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils import Foundation @inline(never) func generateData() -> Data { var data = Data(count: 16 * 1024) data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> () in for i in 0..<data.count { ptr[i] = UInt8(i % 23) } } return data } @inline(never) public func run_IterateData(_ N: Int) { let data = generateData() for _ in 0...10*N { _ = data.reduce(0, &+) } }
apache-2.0
5cab2923471ae1a6c581a7954b030150
26.617647
80
0.574015
4.064935
false
false
false
false
instacrate/tapcrate-api
Sources/api/Controllers/OrderController.swift
1
9730
// // OrderController.swift // polymr-api // // Created by Hakon Hanesand on 3/4/17. // // import HTTP import Vapor import Fluent import FluentProvider import Foundation extension StructuredData.Number: Hashable { public var hashValue: Int { switch self { case let .int(int): return int.hashValue case let .double(double): return double.hashValue case let .uint(uint): return uint.hashValue } } } extension StructuredData: Hashable { public var hashValue: Int { switch self { case let .bool(bool): return bool.hashValue case let .number(number): return number.hashValue case let .string(string): return string.hashValue case let .date(date): return date.hashValue case let .bytes(bytes): return bytes.makeString().hashValue case let .array(array): return array.reduce(0) { acc, item in 31 * acc + item.hashValue } case let .object(object): return object.reduce(0) { acc, item in 31 * acc + item.value.hashValue } case .null: return 0 } } } extension StructuredDataWrapper { public var hashValue: Int { return wrapped.hashValue } } extension Stripe { static func charge(order: inout Order) throws { guard let customer = try order.customer().first() else { throw Abort.custom(status: .badRequest, message: "no customer") } return try order.items().all().forEach { (item: Subscription) in guard let product = try item.product().first(), let maker = try item.maker().first(), let secret = maker.keys?.secret else { throw Abort.custom(status: .internalServerError, message: "malformed order item object") } let plan = try product.subscriptionPlanIdentifier() let customer = try maker.connectAccount(for: customer, with: order.card) let stripeSubscription = try Stripe.subscribe(user: customer, to: plan, oneTime: false, cut: maker.cut, metadata: [:], under: secret) item.subscribed = true item.subcriptionIdentifier = stripeSubscription.id try item.save() } } } final class OrderController: ResourceRepresentable { func index(_ request: Request) throws -> ResponseRepresentable { let type: SessionType = try request.extract() switch type { case .customer: let orders = try request.customer().orders().all() if orders.count == 0 { return try Node.array([]).makeResponse() } let orderIds = try orders.map { $0.id!.int! }.unique().converted(to: Array<Node>.self, in: jsonContext) let subscriptions = try Subscription.makeQuery().filter(.subset(Order.foreignIdKey, .in, orderIds)).all() let groupedSubscriptions = subscriptions.group() { return $0.order_id.int! } let addressIds = try orders.map { $0.customer_address_id.int! }.unique().converted(to: Array<Node>.self, in: jsonContext) let addresses = try CustomerAddress.makeQuery().filter(.subset(CustomerAddress.idKey, .in, addressIds)).all() let makerIds = try subscriptions.map { $0.maker_id.int! }.unique().converted(to: Array<Node>.self, in: jsonContext) let makers = try Maker.makeQuery().filter(.subset(Maker.idKey, .in, makerIds)).all() var result: [Node] = [] for order in orders { guard let subscriptions = groupedSubscriptions[order.id!.int!] else { continue } var subscriptionsNode: [Node] = [] for subscription in subscriptions { let maker = makers.filter { $0.id!.int! == subscription.maker_id.int }.first var subscriptionNode = try subscription.makeNode(in: jsonContext) try subscriptionNode.replace(relation: "maker", with: maker.makeNode(in: jsonContext)) subscriptionsNode.append(subscriptionNode) } var orderNode = try order.makeNode(in: jsonContext) orderNode["subscriptions"] = try subscriptionsNode.makeNode(in: jsonContext) let address = addresses.filter { $0.id!.int! == order.customer_address_id.int }.first try orderNode.replace(relation: "customer_address", with: address.makeNode(in: jsonContext)) result.append(orderNode) } return try result.makeResponse() case .maker: var query = try request.maker().subscriptions().makeQuery() if let fulfilled = request.query?["fulfilled"]?.bool { query = try query.filter("fulfilled", fulfilled) } let subscriptions = try query.all() if subscriptions.count == 0 { return try Node.array([]).makeResponse() } let groupedSubscriptions = subscriptions.group() { return $0.order_id.int! } let subIds = try Array(groupedSubscriptions.keys).converted(to: Array<Node>.self, in: jsonContext) let orders = try Order.makeQuery().filter(.subset(Order.idKey, .in, subIds)).all() let addressIds = try orders.map { $0.customer_address_id.int! }.unique().converted(to: Array<Node>.self, in: jsonContext) let addresses = try CustomerAddress.makeQuery().filter(.subset(CustomerAddress.idKey, .in, addressIds)).all() let customerIds = try orders.map { $0.customer_id.int! }.unique().converted(to: Array<Node>.self, in: jsonContext) let customers = try Customer.makeQuery().filter(.subset(Customer.idKey, .in, customerIds)).all() var result: [Node] = [] for order in orders { var orderNode = try order.makeNode(in: jsonContext) orderNode["subscriptions"] = try groupedSubscriptions[order.id!.int!].makeNode(in: jsonContext) let address = addresses.filter { $0.id!.int! == order.customer_address_id.int }.first try orderNode.replace(relation: "customer_address", with: address.makeNode(in: jsonContext)) let customer = customers.filter { $0.id!.int! == order.customer_id.int }.first try orderNode.replace(relation: "customer", with: customer.makeNode(in: jsonContext)) result.append(orderNode) } return try result.makeResponse() } } func show(_ request: Request, order: Order) throws -> ResponseRepresentable { let type: SessionType = try request.extract() try Order.ensure(action: .read, isAllowedOn: order, by: request) let subscriptions = try order.items().all() let address = try order.address().all()[0] var orderNode = try order.makeNode(in: jsonContext) let customer = try { () throws -> Customer in switch type { case .customer: return try request.customer() case .maker: return try order.customer().all()[0] } }() orderNode["subscriptions"] = try { () throws -> Node in switch type { case .customer: let makerIds: [Identifier] = try subscriptions.map { $0.maker_id.wrapped }.unique().converted(in: emptyContext) let makers: [[Maker]] = try collect(identifiers: makerIds, base: Subscription.self, relation: Relation(parent: Maker.self)) return try zip(subscriptions, makers).map { (arg: (Subscription, [Maker])) throws -> Node in let (subscription, makers) = arg var node = try subscription.makeNode(in: jsonContext) try node.replace(relation: "maker", with: makers.first.makeNode(in: jsonContext)) return node }.converted(in: jsonContext) case .maker: return try subscriptions.converted(in: jsonContext) } }() try orderNode.replace(relation: "customer_address", with: address.makeNode(in: jsonContext)) if type == .maker { let customer = try order.customer().all()[0] try orderNode.replace(relation: "customer", with: customer.makeNode(in: jsonContext)) } let card = try Portal<String>.open { portal in let card = try Stripe.getCard(with: order.card, for: customer.stripeId()) portal.close(with: card.last4) } orderNode["last4"] = .string(card) return try orderNode.makeResponse() } func create(_ request: Request) throws -> ResponseRepresentable { var order = try Order.createOrder(for: request) try Stripe.charge(order: &order) return try order.makeResponse() } func makeResource() -> Resource<Order> { return Resource( index: index, store: create, show: show ) } }
mit
09a45ff9ac5c3f37c901e282e14f9b2d
35.30597
145
0.558376
4.769608
false
false
false
false
motylevm/skstylekit
Sources/UIColorExtensions.swift
1
3993
// // Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev // // 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 extension UIColor { class func sk_Color(from colorString: String) -> UIColor? { return sk_Color(fromDecString: colorString) ?? sk_Color(fromHexString: colorString) } class func sk_Color(fromHexString hexString: String?) -> UIColor? { guard let hexString = hexString else { return nil } var cString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() var cursorIndex = 0 func nextDigit() -> CGFloat? { var result: CUnsignedInt = 0 let range = cString.index(cString.startIndex, offsetBy: cursorIndex) ..< cString.index(cString.startIndex, offsetBy: cursorIndex + 2) let subString = String(cString[range]) let success = Scanner(string: subString).scanHexInt32(&result) cursorIndex += 2 return success ? (CGFloat(result) / 255.0) : nil } if (cString.hasPrefix("#")) { cString = String(cString[cString.index(after: cString.startIndex)...]) } // ARGB if cString.count == 8 { if let a = nextDigit(), let r = nextDigit(), let g = nextDigit(), let b = nextDigit() { return UIColor(red: r, green: g, blue: b, alpha: a) } return nil } // RGB if cString.count == 6 { if let r = nextDigit(), let g = nextDigit(), let b = nextDigit() { return UIColor(red: r, green: g, blue: b, alpha: 1) } return nil } return nil } class func sk_Color(fromDecString decString: String?) -> UIColor? { guard let decString = decString else { return nil } let components = decString.components(separatedBy: CharacterSet(charactersIn: ",;:-")) let numberComponents: [CGFloat] = components.compactMap { if let value = Int($0), value <= 255 && value >= 0 { return CGFloat(value) / 255 } return nil } guard components.count == numberComponents.count else { return nil } switch components.count { case 4: return UIColor(red: numberComponents[1], green: numberComponents[2], blue: numberComponents[3], alpha: numberComponents[0]) case 3: return UIColor(red: numberComponents[0], green: numberComponents[1], blue: numberComponents[2], alpha: 1) default: return nil } } }
mit
372337e2ec9e266353b5e4e6b2850d44
37.394231
145
0.583271
4.869512
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Fitting/Actions/AffectingSkills.swift
2
2930
// // AffectingSkills.swift // Neocom // // Created by Artem Shimanski on 3/18/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp import Expressible import Alamofire import EVEAPI struct AffectingSkills: View { @ObservedObject var ship: DGMShip @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.backgroundManagedObjectContext) private var backgroundManagedObjectContext @EnvironmentObject private var sharedState: SharedState @ObservedObject private var skills = Lazy<FetchedResultsController<SDEInvType>, Never>() @ObservedObject private var pilot = Lazy<DataLoader<Pilot, AFError>, Never>() private func loadPilot(account: Account) -> DataLoader<Pilot, AFError> { DataLoader(Pilot.load(sharedState.esi.characters.characterID(Int(account.characterID)), in: self.backgroundManagedObjectContext).receive(on: RunLoop.main)) } private func getSkills() -> FetchedResultsController<SDEInvType> { let typeIDs = Set([ship.affectors.map{$0.typeID}, ship.modules.flatMap{$0.affectors.map{$0.typeID}}, ship.drones.flatMap{$0.affectors.map{$0.typeID}}].joined()) let controller = managedObjectContext .from(SDEInvType.self) .filter(/\SDEInvType.published == true && /\SDEInvType.group?.category?.categoryID == SDECategoryID.skill.rawValue && (/\SDEInvType.typeID).in(typeIDs)) .sort(by: \SDEInvType.group?.groupName, ascending: true) .sort(by: \SDEInvType.typeName, ascending: true) .fetchedResultsController(sectionName: /\SDEInvType.group?.groupName, cacheName: nil) return FetchedResultsController(controller) } var body: some View { let skills = self.skills.get(initial: self.getSkills()) let pilot = sharedState.account.map{account in self.pilot.get(initial: self.loadPilot(account: account))}?.result?.value return List { ForEach(skills.sections, id: \.name) { section in AffectingSkillsSection(skills: section, pilot: pilot) } }.listStyle(GroupedListStyle()) .navigationBarTitle(Text("Affecting Skills")) } } struct AffectingSkillsSection: View { var skills: FetchedResultsController<SDEInvType>.Section var pilot: Pilot? var body: some View { Section(header: Text(skills.name.uppercased())) { ForEach(skills.objects, id: \.objectID) { type in SkillCell(type: type, pilot: self.pilot) } } } } #if DEBUG struct AffectingSkills_Previews: PreviewProvider { static var previews: some View { let gang = DGMGang.testGang() return NavigationView { AffectingSkills(ship: gang.pilots.first!.ship!) } .environmentObject(gang) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
c742367ccdb8c507dcd5d94e438f9cca
37.539474
168
0.682485
4.458143
false
false
false
false
surik00/RocketWidget
RocketWidget/Model/Structs/Preferences.swift
1
2080
// // Preferences.swift // RocketWidget // // Created by Suren Khorenyan on 08.10.17. // Copyright © 2017 Suren Khorenyan. All rights reserved. // import Foundation struct Preferences { fileprivate let defaults = UserDefaults.standard fileprivate let exitOnCloseKey = "exit_on_close" fileprivate let exitEvenIfStatusBarMenuEnabledKey = "exit_even_if_status_menu_enabled" fileprivate let statusBarMenuEnabledKey = "status_bar_menu_enabled" fileprivate let hideStatusBarMenuKey = "hide_status_bar_menu" fileprivate let startToStatusBarKey = "start_to_status_bar" fileprivate let hideFromDockWhenWindowClosedKey = "hide_from_dock_when_window_closed" var exitOnClose: Bool { get { return defaults.bool(forKey: exitOnCloseKey) } set { defaults.set(newValue, forKey: exitOnCloseKey) } } var exitEvenIfStatusBarMenuEnabled: Bool { get { return defaults.bool(forKey: exitEvenIfStatusBarMenuEnabledKey) } set { defaults.set(newValue, forKey: exitEvenIfStatusBarMenuEnabledKey) } } var statusBarMenuEnabled: Bool { get { return defaults.bool(forKey: statusBarMenuEnabledKey) } set { defaults.set(newValue, forKey: statusBarMenuEnabledKey) } } var hideStatusBarMenu: Bool { get { return defaults.bool(forKey: hideStatusBarMenuKey) } set { defaults.set(newValue, forKey: hideStatusBarMenuKey) } } var startToStatusBar: Bool { get { return defaults.bool(forKey: startToStatusBarKey) } set { defaults.set(newValue, forKey: startToStatusBarKey) } } var hideFromDockWhenWindowClosed: Bool { get { return defaults.bool(forKey: hideFromDockWhenWindowClosedKey) } set { defaults.set(newValue, forKey: hideFromDockWhenWindowClosedKey) } } }
bsd-3-clause
774fa693d7b2fd5f21b4508b3798036b
26.72
90
0.622896
4.349372
false
false
false
false
cuzv/Redes
RedesSample/Helpers.swift
1
10069
// // Helpers.swift // Copyright (c) 2015-2016 Moch Xiao (http://mochxiao.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 Foundation public extension Dictionary { /// URL query string. public var queryString: String { let mappedList = map { return "\($0.0)=\($0.1)" } return mappedList.sorted().joined(separator: "&") } } // MARK: - md5 // https://github.com/onevcat/Kingfisher/blob/master/Sources/String%2BMD5.swift public extension String { var md5: String { if let data = self.data(using: .utf8, allowLossyConversion: true) { let message = data.withUnsafeBytes { bytes -> [UInt8] in return Array(UnsafeBufferPointer(start: bytes, count: data.count)) } let MD5Calculator = MD5(message) let MD5Data = MD5Calculator.calculate() let MD5String = NSMutableString() for c in MD5Data { MD5String.appendFormat("%02x", c) } return MD5String as String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (MemoryLayout<T>.size * 8) let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } return bytes } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(_ arrayOfBytes: [UInt8]) { append(arrayOfBytes, length: arrayOfBytes.count) } } protocol HashProtocol { var message: Array<UInt8> { get } /** Common part for hash calculation. Prepare header data. */ func prepare(_ len: Int) -> Array<UInt8> } extension HashProtocol { func prepare(_ len: Int) -> Array<UInt8> { var tmpMessage = message // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array<UInt8>(repeating: 0, count: counter) return tmpMessage } } func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) { let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 let d3 = UInt32(slice[idx]) let val: UInt32 = d0 | d1 | d2 | d3 result.append(val) } return result } struct BytesIterator: IteratorProtocol { let chunkSize: Int let data: [UInt8] init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } var offset = 0 mutating func next() -> ArraySlice<UInt8>? { let end = min(chunkSize, data.count - offset) let result = data[offset..<offset + end] offset += result.count return result.count > 0 ? result : nil } } struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] func makeIterator() -> BytesIterator { return BytesIterator(chunkSize: chunkSize, data: data) } } func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) } class MD5: HashProtocol { static let size = 16 // 128 / 8 let message: [UInt8] init (_ message: [UInt8]) { self.message = message } /** specifies the per-round shift amounts */ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> [UInt8] { var tmpMessage = prepare(64) tmpMessage.reserveCapacity(tmpMessage.count + 4) // hash values var hh = hashes // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.count * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage += lengthBytes.reversed() // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = toUInt32Array(chunk) assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A: UInt32 = hh[0] var B: UInt32 = hh[1] var C: UInt32 = hh[2] var D: UInt32 = hh[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< sines.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var result = [UInt8]() result.reserveCapacity(hh.count / 4) hh.forEach { let itemLE = $0.littleEndian result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)] } return result } }
mit
bad9671d738164af86b015fa8f0af4ae
33.820069
133
0.530856
3.846713
false
false
false
false
fousa/trackkit
Example/Tests/Tests/GPX/1.1/GPXTrackSpecs.swift
1
12501
// // TrackKit // // Created by Jelle Vandebeeck on 30/12/2016. // import Quick import Nimble import TrackKit class GPXTrackSpec: QuickSpec { override func spec() { describe("tracks") { it("should not have tracks") { let content = "<gpx version='1.1'></gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.tracks).to(beNil()) } it("should not have tracks without a points") { let content = "<gpx version='1.1'>" + "<trk></trk>" + "<trk></trk>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.tracks).to(beNil()) } it("should not have tracks") { let content = "<gpx version='1.1'>" + "<trk>" + "<trkseg>" + "<trkpt></trkpt>" + "<trkpt></trkpt>" + "</trkseg>" + "<trkseg></trkseg>" + "</trk>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.tracks).to(beNil()) } it("should have tracks") { let content = "<gpx version='1.1'>" + "<trk>" + "<trkseg>" + "<trkpt lat='10' lon='10'></trkpt>" + "<trkpt lat='11' lon='11'></trkpt>" + "</trkseg>" + "</trk>" + "<trk>" + "<trkseg>" + "<trkpt lat='10' lon='10'></trkpt>" + "<trkpt lat='11' lon='11'></trkpt>" + "</trkseg>" + "</trk>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() expect(file.tracks?.count) == 2 } } describe("track data") { var track: Track! beforeEach { let content = "<gpx creator='TrackKit' version='1.1'>" + "<trk>" + "<name>A waypoint</name>" + "<cmt>A comment</cmt>" + "<desc>A description</desc>" + "<src>A source</src>" + "<type>A type</type>" + "<number>9</number>" // Link + "<link href='http://fousa.be'>" + "<text>Fousa</text>" + "<type>text/html</type>" + "</link>" // Segments. + "<trkseg>" + "<trkpt lat='41.2' lon='-71.3'></trkpt>" + "</trkseg>" + "</trk>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() track = file.tracks?.first! } it("should have a name") { expect(track.name) == "A waypoint" } it("should have a comment") { expect(track.comment) == "A comment" } it("should have a description") { expect(track.description) == "A description" } it("should have a source") { expect(track.source) == "A source" } it("should have a link") { expect(track.link?.link) == "http://fousa.be" expect(track.link?.text) == "Fousa" expect(track.link?.mimeType) == "text/html" } it("should have a number") { expect(track.number) == 9 } it("should have a type") { expect(track.type) == "A type" } } describe("track point data") { var point: Point! beforeEach { let content = "<gpx creator='TrackKit' version='1.1'>" + "<trk>" + "<trkseg>" + "<trkpt lat='41.2' lon='-71.3'>" + "<ele>1001</ele>" + "<magvar>300</magvar>" + "<name>A waypoint</name>" + "<time>2016-03-10T10:05:12+02:00</time>" + "<geoidheight>56</geoidheight>" + "<cmt>A comment</cmt>" + "<desc>A description</desc>" + "<src>A source</src>" + "<sym>A symbol</sym>" + "<type>A type</type>" + "<fix>dgps</fix>" + "<sat>9</sat>" + "<hdop>1.3</hdop>" + "<vdop>2.2</vdop>" + "<pdop>3.1</pdop>" + "<ageofdgpsdata>0.4</ageofdgpsdata>" + "<dgpsid>400</dgpsid>" // Link + "<link href='http://fousa.be'>" + "<text>Fousa</text>" + "<type>text/html</type>" + "</link>" + "</trkpt>" + "</trkseg>" + "</trk>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() point = file.tracks?.first?.segments?.first?.points?.first! } it("should have a coordinate") { expect(point.coordinate?.latitude) == 41.2 expect(point.coordinate?.longitude) == -71.3 } it("should have an elevation") { expect(point.elevation) == 1001 } it("should have a magnetic variation") { expect(point.magneticVariation) == 300 } it("should have a time") { expect(point.time?.description) == "2016-03-10 08:05:12 +0000" } it("should have a mean sea level height") { expect(point.meanSeaLevelHeight) == 56 } it("should have a name") { expect(point.name) == "A waypoint" } it("should have a comment") { expect(point.comment) == "A comment" } it("should have a description") { expect(point.description) == "A description" } it("should have a source") { expect(point.source) == "A source" } it("should have a link") { expect(point.link?.link) == "http://fousa.be" expect(point.link?.text) == "Fousa" expect(point.link?.mimeType) == "text/html" } it("should have a symbol") { expect(point.source) == "A source" } it("should have satelites") { expect(point.satelites) == 9 } it("should have a horizontal dilution of precision") { expect(point.horizontalDilutionOfPrecision) == 1.3 } it("should have a vertical dilution of precision") { expect(point.verticalDilutionOfPrecision) == 2.2 } it("should have a position dilution of precision") { expect(point.positionDilutionOfPrecision) == 3.1 } it("should have an age of gpx data") { expect(point.ageOfTheGpxData) == 0.4 } it("should have a gps station type") { expect(point.dgpsStationType) == 400 } it("should have a type") { expect(point.type) == "A type" } it("should have a fix") { expect(point.fix) == .dgps } } describe("empty track point") { var point: Point! beforeEach { let content = "<gpx creator='TrackKit' version='1.1'>" + "<trk>" + "<trkseg>" + "<trkpt lat='41.2' lon='-71.3'></trkpt>" + "</trkseg>" + "</trk>" + "</gpx>" let data = content.data(using: .utf8) let file = try! TrackParser(data: data, type: .gpx).parse() point = file.tracks?.first?.segments?.first?.points?.first! } it("should not have an elevation") { expect(point.elevation).to(beNil()) } it("should not have a magnetic variation") { expect(point.magneticVariation).to(beNil()) } it("should not have a time") { expect(point.time?.description).to(beNil()) } it("should not have a mean sea level height") { expect(point.meanSeaLevelHeight).to(beNil()) } it("should not have a name") { expect(point.name).to(beNil()) } it("should not have a comment") { expect(point.comment).to(beNil()) } it("should not have a description") { expect(point.description).to(beNil()) } it("should not have a source") { expect(point.source).to(beNil()) } it("should not have a link") { expect(point.link).to(beNil()) } it("should not have a type") { expect(point.type).to(beNil()) } it("should not have a fix") { expect(point.fix).to(beNil()) } it("should not have a symbol") { expect(point.source).to(beNil()) } it("should not have satelites") { expect(point.satelites).to(beNil()) } it("should not have a horizontal dilution of precision") { expect(point.horizontalDilutionOfPrecision).to(beNil()) } it("should not have a vertical dilution of precision") { expect(point.verticalDilutionOfPrecision).to(beNil()) } it("should not have a position dilution of precision") { expect(point.positionDilutionOfPrecision).to(beNil()) } it("should not have an age of gpx data") { expect(point.ageOfTheGpxData).to(beNil()) } it("should have a gps station type") { expect(point.dgpsStationType).to(beNil()) } } } }
mit
e9c0c964fe6a8b897939d9537e9f8656
35.340116
86
0.363971
5.125461
false
false
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/27013-mapsignaturefunctiontype.swift
1
2157
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } struct S<g e func > " { A {enum S<T : g let { protocol { _} enum S<H : { func f { let i( ) -> " {{ enum S<T> { func c(){ } { let {} } func a{ }protocol a<h{ class < { import a{{ enum S<T where H : a<T{ { } let a {i typealias d extension { class b { func a< {} } class d:b{{ { class A } class a{ struct B:a{enum S<d where H.h =coe func g }}typealias e { { var f:b } class d<T{ } } func f{{ { struct Q<D{ class A } { class B<T{func Boolean var f{ { let i( ) {{ func i( ) -> <T where B<T where T : { func b } func > " " } } } { {i} { } class < { struct B<T : T{ {enum B<h{ { } } let : " { } import a " { { struct c class a<T where f:T{ a } }struct S<T where f{ protocol P { } class { { {} }} enum S<T where T class b{ : { enum S<d where f:A{} } d:a< a } func c<T where H.h =() { extension { protocol a{ let : c(a<T where f{} func c struct S<T where H : where H.E struct A } class < { { func i func i( ) -> " " A {enum S<D{ func a<T where T=coe } } { }struct S{ enum S<D{ {enum B:b : { func b } func c<H : " { { { class a} } }struct A }protocol { class < { class d<H : where B<f { struct A let : a{ func g class d<D{ for b in c<f { } { }struct A class d<T : where H.E var f{ } }protocol { class d<T where H.h== e, A { } {let:a{ enum S<T> } w {i( ) -> " { struct A { extension { func f { } A { } : a struct B<T== " { _}} } enum S<T where H : a func b(){func f:b(a{ func > <T> { func b { struct B:a(a< a { class < { { } class b{ class A{enum S func a(){ { class a{ class d<T let start = " " let i a { extension { { { struct B<T.E } class d } { class d<T.E struct } var f{ extension { struct S d protocol P { w protocol { protocol { " func g.h{ }protocol a { } w for b in c() -> " { { class c class < a {i} } }struct S<f {let:b<g e func a func a{ }struct S extension { _}} } }} { protocol P { A { protocol P { } class b<H : {{ } protocol P { class < a } { }struct B<T : a } } var f{ typealias e { a } " struct Q<T where B:P{ { } struct func g.h =
apache-2.0
e43f15d5ec0083043a9428bb19e154f7
7.9875
87
0.562819
2.114706
false
false
false
false
JohnKim/stalk.messenger
stalk-messenger/ios/RNSwiftSocketIO/SocketIOClient/SocketClientManager.swift
22
2635
// // SocketClientManager.swift // Socket.IO-Client-Swift // // Created by Erik Little on 6/11/16. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Experimental socket manager. API subject to change. Can be used to persist sockets across ViewControllers. Sockets are strongly stored, so be sure to remove them once they are no longer needed. Example usage: ``` let manager = SocketClientManager.sharedManager manager["room1"] = socket1 manager["room2"] = socket2 manager.removeSocket(socket: socket2) manager["room1"]?.emit("hello") ``` */ open class SocketClientManager : NSObject { open static let sharedManager = SocketClientManager() private var sockets = [String: SocketIOClient]() open subscript(string: String) -> SocketIOClient? { get { return sockets[string] } set(socket) { sockets[string] = socket } } open func addSocket(_ socket: SocketIOClient, labeledAs label: String) { sockets[label] = socket } open func removeSocket(withLabel label: String) -> SocketIOClient? { return sockets.removeValue(forKey: label) } open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? { var returnSocket: SocketIOClient? for (label, dictSocket) in sockets where dictSocket === socket { returnSocket = sockets.removeValue(forKey: label) } return returnSocket } open func removeSockets() { sockets.removeAll() } }
mit
12c644310bac77631be5bfaecafb4a8d
31.134146
81
0.687666
4.574653
false
false
false
false
xwu/swift
test/Generics/associated_type_order.swift
1
434
// RUN: %target-swift-emit-silgen %s -requirement-machine=on | %FileCheck %s protocol P1 { associatedtype B } protocol P2 { associatedtype A } // Make sure that T.[P1:A] < T.[P2:B]. struct G<T : P1 & P2> where T.A == T.B { // CHECK-LABEL: sil hidden [ossa] @$s21associated_type_order1GV3fooyy1AAA2P2PQzF : $@convention(method) <T where T : P1, T : P2, T.A == T.B> (@in_guaranteed T.A, G<T>) -> () { func foo(_: T.A) {} }
apache-2.0
7efdee464b41445fc7bc87b08d84cff4
24.529412
177
0.617512
2.508671
false
false
false
false
MetalheadSanya/GtkSwift
src/HeaderBar.swift
1
5103
// // HeaderBar.swift // GTK-swift // // Created by Alexander Zalutskiy on 18.04.16. // // import CGTK /// `HeaderBar` is similar to a horizontal GtkBox. It allows children to be /// placed at the start or the end. In addition, it allows a title and subtitle /// to be displayed. The title will be centered with respect to the width of the /// box, even if the children at either side take up different amounts of space. /// The height of the titlebar will be set to provide sufficient space for the /// subtitle, even if none is currently set. If a subtitle is not needed, the /// space reservation can be turned off with `hasSubtitle` property. /// /// HeaderBar can add typical window frame controls, such as minimize, maximize /// and close buttons, or the window icon. public class HeaderBar: Container { internal var n_HeaderBar: UnsafeMutablePointer<GtkHeaderBar> internal init(n_HeaderBar: UnsafeMutablePointer<GtkHeaderBar>) { self.n_HeaderBar = n_HeaderBar super.init(n_Container: UnsafeMutablePointer<GtkContainer>(n_HeaderBar)) } /// Creates a new `HeaderBar` widget. public convenience init() { self.init(n_HeaderBar: UnsafeMutablePointer<GtkHeaderBar>(gtk_header_bar_new())) } /// The title should help a user identify the current view. A good title /// should not include the application name. public var title: String { set { gtk_header_bar_set_title(n_HeaderBar, newValue) } get { return String(cString: gtk_header_bar_get_title(n_HeaderBar)) } } /// The title should give a user an additional detail to help him identify the /// current view. /// /// - Note: `HeaderBar` by default reserves room for the subtitle, even if /// none is currently set. If this is not desired, set the `hasSubtitle` /// property to `false`. public var subtitle: String { set { gtk_header_bar_set_subtitle(n_HeaderBar, subtitle) } get { return String(cString: gtk_header_bar_get_subtitle(n_HeaderBar)) } } /// Whether the header bar should reserve space for a subtitle, even if none /// is currently set. public var hasSubtitle: Bool { set { gtk_header_bar_set_has_subtitle(n_HeaderBar, newValue ? 1 : 0) } get { return gtk_header_bar_get_has_subtitle(n_HeaderBar) != 0 } } internal weak var _customTitle: Widget? /// Center widget; that is a child widget that will be centered with respect /// to the full width of the box, even if the children at either side take up /// different amounts of space. public var customTitle: Widget? { set { gtk_header_bar_set_custom_title(n_HeaderBar, newValue?.n_Widget) _customTitle = newValue } get { let n_Widget = gtk_header_bar_get_custom_title(n_HeaderBar) if n_Widget == _customTitle?.n_Widget { return _customTitle } if let n_Widget = n_Widget { print("WARNING: [HeaderBar.customTitle] generate widget from pointer") let widget = Container.correctWidgetForWidget(Widget(n_Widget: n_Widget)) _customTitle = widget return widget } return nil } } /// Adds `child` to bar, packed with reference to the start of the bar. /// /// - Parameter child: the `Widget` to be added to bar public func packStart(child: Widget) { guard child.parent == nil else { return } gtk_header_bar_pack_start(n_HeaderBar, child.n_Widget) if !_children.contains(child) { _children.append(child) } } /// Adds `child` to bar, packed with reference to the end of the bar. /// /// Parameter child: the `Widget` to be added to bar public func packEnd(child: Widget) { guard child.parent == nil else { return } gtk_header_bar_pack_end(n_HeaderBar, child.n_Widget) if !_children.contains(child) { _children.append(child) } } /// Whether this header bar shows the standard window decorations, including /// close, maximize, and minimize. public var showCloseButton: Bool { set { gtk_header_bar_set_show_close_button(n_HeaderBar, newValue ? 1 : 0) } get { return gtk_header_bar_get_show_close_button(n_HeaderBar) != 0 } } /// The decoration layout for this header bar, overriding the /// `DecorationLayout` setting. /// /// There can be valid reasons for overriding the setting, such as a header /// bar design that does not allow for buttons to take room on the right, or /// only offers room for a single close button. Split header bars are another /// example for overriding the setting. /// /// The format of the string is button names, separated by commas. A colon /// separates the buttons that should appear on the left from those on the /// right. Recognized button names are minimize, maximize, close, icon (the /// window icon) and menu (a menu button for the fallback app menu). /// /// For example, `“menu:minimize,maximize,close”` specifies a menu on the /// left, and minimize, maximize and close buttons on the right. public var decorationLayout: String { set { gtk_header_bar_set_decoration_layout(n_HeaderBar, newValue) } get { return String(cString: gtk_header_bar_get_decoration_layout(n_HeaderBar)) } } }
bsd-3-clause
90ac68ee946009a5051f5e0ccefe8269
30.475309
80
0.699745
3.490075
false
false
false
false
Finb/V2ex-Swift
Controller/RightViewController.swift
1
6315
// // RightViewController.swift // V2ex-Swift // // Created by huangfeng on 1/14/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import FXBlurView let RightViewControllerRightNodes = [ rightNodeModel(nodeName: NSLocalizedString("tech" ), nodeTab: "tech"), rightNodeModel(nodeName: NSLocalizedString("creative" ), nodeTab: "creative"), rightNodeModel(nodeName: NSLocalizedString("play" ), nodeTab: "play"), rightNodeModel(nodeName: NSLocalizedString("apple" ), nodeTab: "apple"), rightNodeModel(nodeName: NSLocalizedString("jobs" ), nodeTab: "jobs"), rightNodeModel(nodeName: NSLocalizedString("deals" ), nodeTab: "deals"), rightNodeModel(nodeName: NSLocalizedString("city" ), nodeTab: "city"), rightNodeModel(nodeName: NSLocalizedString("qna" ), nodeTab: "qna"), rightNodeModel(nodeName: NSLocalizedString("hot"), nodeTab: "hot"), rightNodeModel(nodeName: NSLocalizedString("all"), nodeTab: "all"), rightNodeModel(nodeName: NSLocalizedString("r2" ), nodeTab: "r2"), rightNodeModel(nodeName: NSLocalizedString("nodes" ), nodeTab: "nodes"), rightNodeModel(nodeName: NSLocalizedString("members" ), nodeTab: "members"), ] class RightViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { let rightNodes = RightViewControllerRightNodes var currentSelectedTabIndex = 0; var backgroundImageView:UIImageView? var frostedView = FXBlurView() fileprivate lazy var tableView: UITableView = { let tableView = UITableView() tableView.backgroundColor = UIColor.clear tableView.estimatedRowHeight=100 tableView.separatorStyle = .none if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = .never } regClass(tableView, cell: RightNodeTableViewCell.self) tableView.delegate = self tableView.dataSource = self return tableView }() override var preferredStatusBarStyle: UIStatusBarStyle{ get { if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault { if #available(iOS 13.0, *) { return .darkContent } else { return .default } } else{ return .lightContent } } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor; var currentTab:String? = V2EXSettings.sharedInstance[kHomeTab] if currentTab == nil { currentTab = "all" } self.currentSelectedTabIndex = rightNodes.firstIndex { $0.nodeTab == currentTab }! self.backgroundImageView = UIImageView() self.backgroundImageView!.frame = self.view.frame self.backgroundImageView!.contentMode = .left view.addSubview(self.backgroundImageView!) frostedView.underlyingView = self.backgroundImageView! frostedView.isDynamic = false frostedView.frame = self.view.frame frostedView.tintColor = UIColor.black self.view.addSubview(frostedView) self.view.addSubview(self.tableView); self.tableView.snp.makeConstraints{ (make) -> Void in make.top.right.bottom.left.equalTo(self.view); } self.themeChangedHandler = {[weak self] (style) -> Void in if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault { self?.backgroundImageView?.image = UIImage(named: "32.jpg") } else{ self?.backgroundImageView?.image = UIImage(named: "12.jpg") } self?.frostedView.updateAsynchronously(true, completion: nil) } let rowHeight = self.tableView(self.tableView, heightForRowAt: IndexPath(row: 0, section: 0)) let rowCount = self.tableView(self.tableView, numberOfRowsInSection: 0) var paddingTop = (SCREEN_HEIGHT - CGFloat(rowCount) * rowHeight) / 2 if paddingTop <= 0 { paddingTop = 20 } self.tableView.contentInset = UIEdgeInsets(top: paddingTop, left: 0, bottom: 0, right: 0) } func maximumRightDrawerWidth() -> CGFloat{ // 调整RightView宽度 let cell = RightNodeTableViewCell() let cellFont = UIFont(name: cell.nodeNameLabel.font.familyName, size: cell.nodeNameLabel.font.pointSize) for node in rightNodes { let size = node.nodeName!.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key(rawValue: "NSFontAttributeName"):cellFont!], context: nil) let width = size.width + 50 if width > 100 { return width } } return 100 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rightNodes.count; } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 48 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = getCell(tableView, cell: RightNodeTableViewCell.self, indexPath: indexPath); cell.nodeNameLabel.text = self.rightNodes[indexPath.row].nodeName if indexPath.row == self.currentSelectedTabIndex && cell.isSelected == false { self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .middle) } return cell ; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let node = self.rightNodes[indexPath.row]; V2Client.sharedInstance.centerViewController?.tab = node.nodeTab V2Client.sharedInstance.centerViewController?.refreshPage() V2Client.sharedInstance.drawerController?.closeDrawer(animated: true, completion: nil) } } struct rightNodeModel { var nodeName:String? var nodeTab:String? }
mit
ea8134b7735eea85a31dff41bc5d96f3
41.608108
131
0.640818
4.981043
false
false
false
false
Sharelink/Bahamut
SRCPlugin/SharelinkLauncher/StartController.swift
1
796
// // ViewController.swift // CSRCPluginTemplate // // Created by AlexChow on 16/1/23. // Copyright © 2016年 Sharelink. All rights reserved. // import UIKit import SharelinkKernel class StartController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() self.initWaitingScreen() SharelinkAppDelegate.startSharelink() } func initWaitingScreen() { let storyBoard = UIStoryboard(name: "LaunchScreen", bundle: NSBundle.mainBundle()) let controller = storyBoard.instantiateViewControllerWithIdentifier("LaunchScreen") let launchScr = controller.view launchScr.frame = self.view.bounds self.view.backgroundColor = UIColor.blackColor() self.view.addSubview(launchScr) } }
mit
a0438d894c0bbddbb210760a25322566
25.433333
91
0.693569
4.720238
false
false
false
false
pinchih/SamsClubChallengeMobile-iOS
Sam'sClubChallengeMobile-iOS/NetworkActivityDisplayable.swift
1
2904
// // NetworkActivityDisplayable.swift // Sam'sClubChallengeMobile-iOS // // Created by Pin-Chih on 8/7/17. // Copyright © 2017 Pin-Chih Lin. All rights reserved. // import Foundation import UIKit /// A generic enum that represents the result of network calls enum NetworkResult<T>{ case uninitialized case loading case success(data:T) case error(message:String) } /// The NetworkActivityDisplayable protocol provides a convenience way of showing network status to users. /// Whenever a UIViewController class conformed to this protocol should declare: /// - A loadingView, which is UIActivityIndicatorView type,and it can be customized in your ViewController /// - A errorView, which is UILable type, and it can be customized in your ViewController /// - A networkState, which is a NetworkResult<T> type protocol NetworkActivityDisplayable { associatedtype returnedData var loadingView : UIActivityIndicatorView { get set } var errorView : UILabel { get } var networkStatus : NetworkResult<returnedData> { get set } func updateNetworkStatus() } /// This extension of NetworkActivityDisplayable makes sure that whenever a UIViewController class conformed to this protocol, /// the implementation of required functions are therefore provided. /// Anyone wishs to implement their custom behavior of the protocol should override these functions. /// These functions are: /// - A update function which updates the corresponding views according to the status of network call /// - A setupNetworkActivityDisplayableView function that setup the loadingView and errorView in the UIViewController /// IMPORTANT: Call this function in the viewDidLoad function, which makes sure the loadingView and errorView are layouted properly. extension NetworkActivityDisplayable where Self : UIViewController { func setupNetworkActivityDisplayableViews(){ view.addSubview(loadingView) loadingView.centerToSuperView() view.addSubview(errorView) errorView.centerToSuperView() errorView.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, multiplier: 0.8).isActive = true } func updateNetworkStatus(){ switch networkStatus{ case .loading: loadingView.isHidden = false loadingView.startAnimating() errorView.isHidden = true case .success: loadingView.isHidden = true loadingView.stopAnimating() errorView.isHidden = true case .error(let message): loadingView.isHidden = true loadingView.stopAnimating() errorView.text = message errorView.isHidden = false case .uninitialized: break } } }
mit
085358a544878b4cdca3bf62e793ec03
32.367816
132
0.686531
5.550669
false
false
false
false
EslamHanafy/ESUtilities
ESUtilities/ESDate.swift
1
8657
// // ESDateUtility.swift // ESUtilities // // Created by Eslam on 8/3/17. // Copyright © 2017 eslam. All rights reserved. // import Foundation public class ESDate:NSObject { //MARK: - Current date methods /// get current string date in format "dd-MM-yyyy-hh:mm:ss" /// /// - Returns: the current date string public class func getCurrentStringDate()->String{ return getDateFormatter().string(from: Date()) } /// get current date as string in format "dd-MM-yyyy" /// /// - Returns: the current date public class func getCurrentDate()->String { return getCurrentStringDate(withFormat: "dd-MM-yyyy") } /// get current time as string in format "hh:mm:ss" /// /// - Returns: the current time public class func getCurrentTime()->String{ return getCurrentStringDate(withFormat: "hh:mm:ss") } /// get current string date with a specific format /// /// - Parameter format: the date format /// - Returns: the string date for the specific format public class func getCurrentStringDate(withFormat format:String)->String{ return getDateFormatter(withFormat: format).string(from: Date()) } //MARK: - Other date methods /// split date and time from a string date /// /// - Parameters: /// - str: the full date string /// - format: the full date string format /// - Returns: the date and the time from the string date , if the full string date refer to today the date value will be "today" public class func getDateAndTimeStrings(fromDateString str:String,withFormat format:String)->(date:String,time:String)? { //check if date string and the format is valid if let date = getDate(fromatString: str, withFormat: format){ let dateFormatter = getDateFormatter(withFormat: "d MMMM YYYY") var output:(date:String,time:String) //get date from the string //check if the is date is today if getCurrentStringDate(withFormat: "d MMMM YYYY") == dateFormatter.string(from: date) { output.date = "Today" }else{ output.date = dateFormatter.string(from: date) } //get the time from the string dateFormatter.dateFormat = "h:mma" dateFormatter.amSymbol = "am" dateFormatter.pmSymbol = "pm" output.time = dateFormatter.string(from: date) return output } //the date string or the format was not valid return nil } /// get Date object from string date /// /// - Parameters: /// - str: the full string date /// - format: the full string date format /// - Returns: the Date object public class func getDate(fromatString str:String,withFormat format:String)->Date? { return getDateFormatter(withFormat: format).date(from: str) } /// get DateFormatter object in english locale /// /// - Parameter format: the formatter you want , the default value is "dd-MM-yyyy-hh:mm:ss" /// - Returns: the DateFormatter object public class func getDateFormatter(withFormat format:String? = nil) -> DateFormatter { let format:String = format == nil ? "dd-MM-yyyy-hh:mm:ss" : format! let dateFormatter = DateFormatter() dateFormatter.dateFormat = format dateFormatter.locale = Locale(identifier: "en") return dateFormatter } //MARK: - Human dates /// get human date for current time /// /// - Parameter localized: if you pass it true you will have the result localized based on ESKeys { ESYear : for years , ESMonth : for months , ESWeek : for weeks , ESDay : for days , ESHour : for hours , ESMinute : for minutes , ESSecond : for seconds } and you must put this keys in your Localizable.strings file for example "ESDay" = " days ago"; , default value localized is false /// - Returns: human date public class func getHumanDate(localized:Bool = false)->String { return getHumanDate(fromDate: Date(),localized: localized) } /// get human date from string date /// /// - Parameters: /// - str: the full string date /// - format: the full string date format /// - localized: if you pass it true you will have the result localized based on ESKeys { ESYear : for years , ESMonth : for months , ESWeek : for weeks , ESDay : for days , ESHour : for hours , ESMinute : for minutes , ESSecond : for seconds } and you must put this keys in your Localizable.strings file for example "ESDay" = " days ago"; , default value localized is false /// - Returns: human date public class func getHumanDate(fromString str:String, withFormat format:String , localized:Bool = false) -> String? { let date = getDate(fromatString: str, withFormat: format) return date == nil ? nil : getHumanDate(fromDate: date!,localized: localized) } /// get human date from Date object /// /// - Parameters: /// - date: the Date object /// - localized: if you pass it true you will have the result localized based on ESKeys { ESYear : for years , ESMonth : for months , ESWeek : for weeks , ESDay : for days , ESHour : for hours , ESMinute : for minutes , ESSecond : for seconds } and you must put this keys in your Localizable.strings file for example "ESDay" = " days ago"; , default value localized is false /// - Returns: human date public class func getHumanDate(fromDate date:Date , localized:Bool = false)->String{ let currentDate = Date() if currentDate.years(from: date) > 0 { return localized ? "\(currentDate.years(from: date))" + ESUtilities.localizedSitringFor(key: "ESYear") : "\(currentDate.years(from: date))y" } if currentDate.months(from: date) > 0 { return localized ? "\(currentDate.months(from: date))" + ESUtilities.localizedSitringFor(key: "ESMonth") : "\(currentDate.months(from: date))M" } if currentDate.weeks(from: date) > 0 { return localized ? "\(currentDate.weeks(from: date))" + ESUtilities.localizedSitringFor(key: "ESWeek") : "\(currentDate.weeks(from: date))w" } if currentDate.days(from: date) > 0 { return localized ? "\(currentDate.days(from: date))" + ESUtilities.localizedSitringFor(key: "ESDay") : "\(currentDate.days(from: date))d" } if currentDate.hours(from: date) > 0 { return localized ? "\(currentDate.hours(from: date))" + ESUtilities.localizedSitringFor(key: "ESHour") : "\(currentDate.hours(from: date))h" } if currentDate.minutes(from: date) > 0 { return localized ? "\(currentDate.minutes(from: date))" + ESUtilities.localizedSitringFor(key: "ESMinute") : "\(currentDate.minutes(from: date))m" } if currentDate.seconds(from: date) > 0 { return localized ? "\(currentDate.seconds(from: date))" + ESUtilities.localizedSitringFor(key: "ESSecond") : "\(currentDate.seconds(from: date))s" } return "" } } //MARK: - Date extension extension Date { /// Returns the amount of years from another date func years(from date: Date) -> Int { return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0 } /// Returns the amount of months from another date func months(from date: Date) -> Int { return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0 } /// Returns the amount of weeks from another date func weeks(from date: Date) -> Int { return Calendar.current.dateComponents([.weekOfYear], from: date, to: self).weekOfYear ?? 0 } /// Returns the amount of days from another date func days(from date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } /// Returns the amount of hours from another date func hours(from date: Date) -> Int { return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0 } /// Returns the amount of minutes from another date func minutes(from date: Date) -> Int { return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0 } /// Returns the amount of seconds from another date func seconds(from date: Date) -> Int { return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 } }
gpl-3.0
d76bb62bb66b1c141008ede5ddf8cc25
43.163265
388
0.629737
4.304326
false
false
false
false
StephenVinouze/ios-charts
ChartsRealm/Classes/Data/RealmBaseDataSet.swift
2
12253
// // RealmBaseDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import Charts import Realm import Realm.Dynamic public class RealmBaseDataSet: ChartBaseDataSet { public func initialize() { fatalError("RealmBaseDataSet is an abstract class, you must inherit from it. Also please do not call super.initialize().") } public required init() { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) initialize() } public override init(label: String?) { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.label = label initialize() } public init(results: RLMResults?, yValueField: String, xIndexField: String?, label: String?) { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.label = label _results = results _yValueField = yValueField _xIndexField = xIndexField _results = _results?.sortedResultsUsingProperty(_xIndexField!, ascending: true) notifyDataSetChanged() initialize() } public convenience init(results: RLMResults?, yValueField: String, label: String?) { self.init(results: results, yValueField: yValueField, xIndexField: nil, label: label) } public convenience init(results: RLMResults?, yValueField: String, xIndexField: String?) { self.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: "DataSet") } public convenience init(results: RLMResults?, yValueField: String) { self.init(results: results, yValueField: yValueField) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, label: String?) { super.init() // default color colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.label = label _yValueField = yValueField _xIndexField = xIndexField if realm != nil { loadResults(realm: realm!, modelName: modelName) } initialize() } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, label: String?) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, label: label) } public func loadResults(realm realm: RLMRealm, modelName: String) { loadResults(realm: realm, modelName: modelName, predicate: nil) } public func loadResults(realm realm: RLMRealm, modelName: String, predicate: NSPredicate?) { if predicate == nil { _results = realm.allObjects(modelName) } else { _results = realm.objects(modelName, withPredicate: predicate) } if _xIndexField != nil { _results = _results?.sortedResultsUsingProperty(_xIndexField!, ascending: true) } notifyDataSetChanged() } // MARK: - Data functions and accessors internal var _results: RLMResults? internal var _yValueField: String? internal var _xIndexField: String? internal var _cache = [ChartDataEntry]() internal var _cacheFirst: Int = -1 internal var _cacheLast: Int = -1 internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// Makes sure that the cache is populated for the specified range internal func ensureCache(start start: Int, end: Int) { if start <= _cacheLast && end >= _cacheFirst { return } guard let results = _results else { return } if _cacheFirst == -1 || _cacheLast == -1 { _cache.removeAll() _cache.reserveCapacity(end - start + 1) for i in UInt(start) ..< UInt(end + 1) { _cache.append(buildEntryFromResultObject(results.objectAtIndex(i), atIndex: i)) } _cacheFirst = start _cacheLast = end } if start < _cacheFirst { var newEntries = [ChartDataEntry]() newEntries.reserveCapacity(start - _cacheFirst) for i in UInt(start) ..< UInt(_cacheFirst) { newEntries.append(buildEntryFromResultObject(results.objectAtIndex(i), atIndex: i)) } _cache.insertContentsOf(newEntries, at: 0) _cacheFirst = start } if end > _cacheLast { for i in UInt(_cacheLast + 1) ..< UInt(end + 1) { _cache.append(buildEntryFromResultObject(results.objectAtIndex(i), atIndex: i)) } _cacheLast = end } } internal func buildEntryFromResultObject(object: RLMObject, atIndex: UInt) -> ChartDataEntry { let entry = ChartDataEntry(value: object[_yValueField!] as! Double, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) return entry } /// Makes sure that the cache is populated for the specified range internal func clearCache() { _cache.removeAll() _cacheFirst = -1 _cacheLast = -1 } /// Use this method to tell the data set that the underlying data has changed public override func notifyDataSetChanged() { calcMinMax(start: _lastStart, end: _lastEnd) } public override func calcMinMax(start start: Int, end: Int) { let yValCount = self.entryCount if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } ensureCache(start: start, end: endValue) if _cache.count == 0 { return } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for i in start ... endValue { let e = _cache[i - _cacheFirst] if (!e.value.isNaN) { if (e.value < _yMin) { _yMin = e.value } if (e.value > _yMax) { _yMax = e.value } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// - returns: the minimum y-value this DataSet holds public override var yMin: Double { return _yMin } /// - returns: the maximum y-value this DataSet holds public override var yMax: Double { return _yMax } /// - returns: the number of y-values this DataSet represents public override var entryCount: Int { return Int(_results?.count ?? 0) } /// - returns: the value of the Entry object at the given xIndex. Returns NaN if no value is at the given x-index. public override func yValForXIndex(x: Int) -> Double { let e = self.entryForXIndex(x) if (e !== nil && e!.xIndex == x) { return e!.value } else { return Double.NaN } } /// - returns: the entry object found at the given index (not x-index!) /// - throws: out of bounds /// if `i` is out of bounds, it may throw an out-of-bounds exception public override func entryForIndex(i: Int) -> ChartDataEntry? { if i < _lastStart || i > _lastEnd { ensureCache(start: i, end: i) } return _cache[i - _lastStart] } /// - returns: the first Entry object found at the given xIndex with binary search. /// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index. /// nil if no Entry object at that index. public override func entryForXIndex(x: Int, rounding: ChartDataSetRounding) -> ChartDataEntry? { let index = self.entryIndex(xIndex: x, rounding: rounding) if (index > -1) { return entryForIndex(index) } return nil } /// - returns: the first Entry object found at the given xIndex with binary search. /// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index. /// nil if no Entry object at that index. public override func entryForXIndex(x: Int) -> ChartDataEntry? { return entryForXIndex(x, rounding: .Closest) } /// - returns: the array-index of the specified entry /// /// - parameter x: x-index of the entry to search for public override func entryIndex(xIndex x: Int, rounding: ChartDataSetRounding) -> Int { guard let results = _results else { return -1 } let foundIndex = results.indexOfObjectWithPredicate( NSPredicate(format: "%K == %d", _xIndexField!, x) ) // TODO: Figure out a way to quickly find the closest index return Int(foundIndex) } /// - returns: the array-index of the specified entry /// /// - parameter e: the entry to search for public override func entryIndex(entry e: ChartDataEntry) -> Int { for i in 0 ..< _cache.count { if (_cache[i] === e || _cache[i].isEqual(e)) { return _cacheFirst + i } } return -1 } /// Not supported on Realm datasets public override func addEntry(e: ChartDataEntry) -> Bool { return false } /// Not supported on Realm datasets public override func addEntryOrdered(e: ChartDataEntry) -> Bool { return false } /// Not supported on Realm datasets public override func removeEntry(entry: ChartDataEntry) -> Bool { return false } /// Checks if this DataSet contains the specified Entry. /// - returns: true if contains the entry, false if not. public override func contains(e: ChartDataEntry) -> Bool { for entry in _cache { if (entry.isEqual(e)) { return true } } return false } /// Returns the fieldname that represents the "y-values" in the realm-data. public var yValueField: String? { get { return _yValueField } } /// Returns the fieldname that represents the "x-index" in the realm-data. public var xIndexField: String? { get { return _xIndexField } } // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmBaseDataSet copy._results = _results copy._yValueField = _yValueField copy._xIndexField = _xIndexField copy._yMax = _yMax copy._yMin = _yMin copy._lastStart = _lastStart copy._lastEnd = _lastEnd return copy } }
apache-2.0
08ae65b1d749779651313918d78c333e
27.429234
151
0.552355
4.650095
false
false
false
false
mlgoogle/viossvc
viossvc/Marco/AppConst.swift
1
4836
// // AppConfig.swift // viossvc // // Created by yaowang on 2016/10/31. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit class AppConst { class Color { static let C0 = UIColor(RGBHex:0x131f32) static let CR = UIColor(RGBHex:0xb82525) static let C1 = UIColor.blackColor() static let C2 = UIColor(RGBHex:0x666666) static let C3 = UIColor(RGBHex:0x999999) static let C4 = UIColor(RGBHex:0xaaaaaa) static let C5 = UIColor(RGBHex:0xe2e2e2) static let C6 = UIColor(RGBHex:0xf2f2f2) }; class SystemFont { static let S1 = UIFont.systemFontOfSize(18) static let S2 = UIFont.systemFontOfSize(15) static let S3 = UIFont.systemFontOfSize(13) static let S4 = UIFont.systemFontOfSize(12) static let S5 = UIFont.systemFontOfSize(10) static let S14 = UIFont.systemFontOfSize(14) }; class Event { static let login = "login" static let sign_btn = "sign_btn" static let sign_confrim = "sign_confrim" static let sign_last = "sign_last" static let sign_next = "sign_next" static let bank_add = "bank_add" static let bank_select = "bank_select" static let drawcash = "drawcash" static let drawcash_pwd = "drawcash_pwd" static let drawcash_total = "drawcash_total" static let message_send = "message_send" static let order_accept = "order_accept" static let order_aply = "order_aply" static let order_unaply = "order_unaply" static let order_chat = "order_chat" static let order_list = "order_list" static let order_refuse = "order_refuse" static let server_add = "server_add" static let server_addPicture = "server_addPicture" static let server_beauty = "server_beauty" static let server_cancelAdd = "server_cancelAdd" static let server_mark = "server_mark" static let server_next = "server_next" static let server_picture = "server_picture" static let server_sure = "server_sure" static let server_delete = "server_delete" static let server_update = "server_update" static let server_start = "server_start" static let server_end = "server_end" static let server_type = "server_type" static let server_price = "server_price" static let share_eat = "share_eat" static let share_fun = "share_fun" static let share_hotel = "share_hotel" static let share_phone = "share_phone" static let share_travel = "share_travel" static let skillshare_comment = "skillshare_comment" static let skillshare_detail = "skillshare_detail" static let user_anthuser = "user_anthuser" static let user_location = "user_location" static let user_logout = "user_logout" static let user_nickname = "user_nickname" static let user_question = "user_question" static let user_resetpwd = "user_resetpwd" static let user_sex = "user_sex" static let user_version = "user_version" static let user_icon = "user_icon" static let user_clearcache = "user_clearcache" } class Network { #if true //是否测试环境 // static let TcpServerIP:String = "192.168.199.131" // static let TcpServerPort:UInt16 = 10001 static let TcpServerIP:String = "139.224.34.22" static let TcpServerPort:UInt16 = 10001 static let TttpHostUrl:String = "http://139.224.34.22"; #else static let TcpServerIP:String = "103.40.192.101"; static let TcpServerPort:UInt16 = 10002 static let HttpHostUrl:String = "http://61.147.114.78"; #endif static let TimeoutSec:UInt16 = 10 static let qiniuHost = "http://ofr5nvpm7.bkt.clouddn.com/" static let qiniuImgStyle = "?imageView2/2/w/160/h/160/interlace/0/q/100" } class Text { static let PhoneFormatErr = "请输入正确的手机号" static let VerifyCodeErr = "请输入正确的验证码" static let CheckInviteCodeErr = "邀请码有误,请重新输入" static let SMSVerifyCodeErr = "获取验证码失败" static let PasswordTwoErr = "两次密码不一致" static let ReSMSVerifyCode = "重新获取" static let ErrorDomain = "com.yundian.viossvc" static let PhoneFormat = "^1[3|4|5|7|8][0-9]\\d{8}$" static let RegisterPhoneError = "输入的手机号已注册" } static let DefaultPageSize = 15 enum Action:UInt { case CallPhone = 10001 case HandleOrder = 11001 case ShowLocation = 11002 } static let UMAppkey = "584a3eb345297d271600127e" }
apache-2.0
a13000dbaf77c4bd0f5893c37035a100
38.241667
80
0.627522
3.678906
false
false
false
false
AlexeyTyurenkov/NBUStats
NBUStatProject/NBUStat/Modules/Hryvnia Today Interbank/HryvniaTodayModuleBuilder.swift
1
2340
// // HryvniaTodayModuleBuilder.swift // FinStat Ukraine // // Created by Aleksey Tyurenkov on 3/2/18. // Copyright © 2018 Oleksii Tiurenkov. All rights reserved. // import Foundation import UIKit import FinstatLib class HryvniaTodayModuleBuilder: ModuleBuilderProtocol { var presenter: TablePresenterProtocol! { return nil } func viewController() -> UIViewController { let storyBoard = UIStoryboard(name: "Currencies", bundle: nil) let initialController = storyBoard.instantiateInitialViewController() if let navigationController = initialController as? UINavigationController { if let controller = navigationController.topViewController as? TableContainerViewController { controller.navigationItem.title = self.moduleName controller.presenter = presenter } } return initialController ?? UIViewController() } var moduleName: String { return NSLocalizedString("", comment: "") } } class InterbankHTModuleBuilder: HryvniaTodayModuleBuilder { override var presenter: TablePresenterProtocol! { let presenter = HryvniaTodayPresenter() presenter.service = InterbankHTService() return presenter } override var moduleName: String{ return NSLocalizedString("Оперативні курси валют на Miжбанку\n(Hryvna.Today)", comment: "") } } class BlackHTModuleBuilder: HryvniaTodayModuleBuilder { override var presenter: TablePresenterProtocol! { let presenter = HryvniaTodayPresenter() presenter.service = BlackHTService() return presenter } override var moduleName: String{ return NSLocalizedString("Очікування готівкого ринку\n(Hryvna.Today)", comment: "") } } class CommercialHTModuleBuilder: HryvniaTodayModuleBuilder { override var presenter: TablePresenterProtocol! { let presenter = HryvniaTodayPresenter() presenter.service = CommercialHTService() return presenter } override var moduleName: String{ return NSLocalizedString("Оперативні середні готівкові курси по банках\n(Hryvna.Today)", comment: "") } }
mit
d369bc24eb201ca5d7f9325dbfa43f3e
28.194805
109
0.683719
4.460317
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/two-sum-ii-input-array-is-sorted.swift
2
1943
/** * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ * * */ /// Two pointers. /// - Complexity: /// - Time: O(n), n is the number of elements in the array. /// - Space: O(1) /// class Solution { func twoSum(_ numbers: [Int], _ target: Int) -> [Int] { var left = 0 var right = numbers.count - 1 while left < right { // print("\(left) - \(right)") if target == numbers[left] + numbers[right] {return [left+1, right+1]} else if target < numbers[left] + numbers[right] {right -= 1} else {left += 1} } return [0, 0] } } /// Binary Search /// - Complexity: /// - Time: O(nlogn), n is the number of elements in the array. /// - Space: O(1) /// class Solution { func twoSum(_ numbers: [Int], _ target: Int) -> [Int] { for index in 0 ..< numbers.count { let tmp = target - numbers[index] var left = index + 1 var right = numbers.count - 1 while left <= right { let mid = left + (right - left) / 2 if numbers[mid] == tmp { return [index + 1, mid + 1] } else if numbers[mid] > tmp { right = mid - 1 } else { left = mid + 1 } } } return [0, 0] } } /// Dictionary: /// - Time: O(n), n is the number of elements in the array. /// - Space: O(n), we have a dictionary to keep the value and its index we have visited. /// class Solution { func twoSum(_ numbers: [Int], _ target: Int) -> [Int] { var dict: [Int : Int] = [:] for index in 0 ..< numbers.count { if let idx1 = dict[target - numbers[index]] { return [idx1 + 1, index + 1] } dict[numbers[index]] = index } return [0, 0] } }
mit
cf9c01d7d202fa0fc021acbf9121c2d5
27.15942
92
0.464231
3.686907
false
false
false
false
milseman/swift
test/SILOptimizer/access_enforcement_noescape.swift
7
26835
// RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s // RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -swift-version 3 -parse-as-library %s | %FileCheck %s // REQUIRES: asserts // This tests SILGen and AccessEnforcementSelection as a single set of tests. // (Some static/dynamic enforcement selection is done in SILGen, and some is // deferred. That may change over time but we want the outcome to be the same). // // These tests attempt to fully cover the possibilities of reads and // modifications to captures along with `inout` arguments on both the caller and // callee side. // Helper func doOne(_ f: () -> ()) { f() } // Helper func doTwo(_: ()->(), _: ()->()) {} // Helper func doOneInout(_: ()->(), _: inout Int) {} // Error: Cannot capture nonescaping closure. // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func reentrantCapturedNoescape(fn: (() -> ()) -> ()) { // let c = { fn {} } // fn(c) // } // Helper struct Frob { mutating func outerMut() { doOne { innerMut() } } mutating func innerMut() {} } // Allow nested mutable access via closures. func nestedNoEscape(f: inout Frob) { doOne { f.outerMut() } } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tF : $@convention(thin) (@inout Frob) -> () { // CHECK-NOT: begin_access // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tF' // closure #1 in nestedNoEscape(f:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tFyycfU_ : $@convention(thin) (@inout_aliasable Frob) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob // CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> () // CHECK: end_access [[ACCESS]] : $*Frob // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tFyycfU_' // Allow aliased noescape reads. func readRead() { var x = 3 // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape8readReadyyF : $@convention(thin) () -> () { // CHECK: [[ALLOC:%.*]] = alloc_stack $Int, var, name "x" // CHECK-NOT: begin_access // CHECK: apply // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape8readReadyyF' // closure #1 in readRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape8readReadyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape8readReadyyFyycfU_' // closure #2 in readRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape8readReadyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape8readReadyyFyycfU0_' // Allow aliased noescape reads of an `inout` arg. func inoutReadRead(x: inout Int) { // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tF' // closure #1 in inoutReadRead(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU_' // closure #2 in inoutReadRead(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU0_' // Allow aliased noescape read + boxed read. func readBoxRead() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo(c, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape11readBoxReadyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape11readBoxReadyyF' // closure #1 in readBoxRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape11readBoxReadyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape11readBoxReadyyFyycfU_' // closure #2 in readBoxRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape11readBoxReadyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape11readBoxReadyyFyycfU0_' // Error: cannout capture inout. // // func inoutReadReadBox(x: inout Int) { // let c = { _ = x } // doTwo({ _ = x }, c) // } // Allow aliased noescape read + write. func readWrite() { var x = 3 // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] doTwo({ _ = x }, { x = 42 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape9readWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape9readWriteyyF' // closure #1 in readWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape9readWriteyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape9readWriteyyFyycfU_' // closure #2 in readWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape9readWriteyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape9readWriteyyFyycfU0_' // Allow aliased noescape read + write of an `inout` arg. func inoutReadWrite(x: inout Int) { // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] doTwo({ _ = x }, { x = 3 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tF' // closure #1 in inoutReadWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU_' // closure #2 in inoutReadWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU0_' func readBoxWrite() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo(c, { x = 42 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape12readBoxWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readBoxWriteyyF' // closure #1 in readBoxWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readBoxWriteyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readBoxWriteyyFyycfU_' // closure #2 in readBoxWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readBoxWriteyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readBoxWriteyyFyycfU0_' // Error: cannout capture inout. // func inoutReadBoxWrite(x: inout Int) { // let c = { _ = x } // doTwo({ x = 42 }, c) // } func readWriteBox() { var x = 3 let c = { x = 42 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo({ _ = x }, c) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape12readWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[PA1]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readWriteBoxyyF' // closure #1 in readWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readWriteBoxyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readWriteBoxyyFyycfU_' // closure #2 in readWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readWriteBoxyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readWriteBoxyyFyycfU0_' // Error: cannout capture inout. // func inoutReadWriteBox(x: inout Int) { // let c = { x = 42 } // doTwo({ _ = x }, c) // } // Error: noescape read + write inout. func readWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14readWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // CHECK: end_access [[ACCESS2]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14readWriteInoutyyF' // closure #1 in readWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape14readWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14readWriteInoutyyFyycfU_' // Error: noescape read + write inout of an inout. func inoutReadWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // CHECK: end_access [[ACCESS2]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tF' // closure #1 in inoutReadWriteInout(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tFyycfU_' // Traps on boxed read + write inout. // Covered by Interpreter/enforce_exclusive_access.swift. func readBoxWriteInout() { var x = 3 let c = { _ = x } // Around the call: [modify] [dynamic] // Inside closure: [read] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape17readBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[ACCESS]]) // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape17readBoxWriteInoutyyF' // closure #1 in readBoxWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape17readBoxWriteInoutyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape17readBoxWriteInoutyyFyycfU_' // Error: inout cannot be captured. // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func inoutReadBoxWriteInout(x: inout Int) { // let c = { _ = x } // doOneInout(c, &x) // } // Allow aliased noescape write + write. func writeWrite() { var x = 3 // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42 }, { x = 87 }) _ = x } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape10writeWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape10writeWriteyyF' // closure #1 in writeWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape10writeWriteyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape10writeWriteyyFyycfU_' // closure #2 in writeWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape10writeWriteyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape10writeWriteyyFyycfU0_' // Allow aliased noescape write + write of an `inout` arg. func inoutWriteWrite(x: inout Int) { // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42}, { x = 87 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tF' // closure #1 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU_' // closure #2 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU0_' // Traps on aliased boxed write + noescape write. // Covered by Interpreter/enforce_exclusive_access.swift. func writeWriteBox() { var x = 3 let c = { x = 87 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo({ x = 42 }, c) _ = x } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape13writeWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[PA1]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13writeWriteBoxyyF' // closure #1 in writeWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape13writeWriteBoxyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13writeWriteBoxyyFyycfU_' // closure #2 in writeWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape13writeWriteBoxyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13writeWriteBoxyyFyycfU0_' // Error: inout cannot be captured. // func inoutWriteWriteBox(x: inout Int) { // let c = { x = 87 } // doTwo({ x = 42 }, c) // } // Error: on noescape write + write inout. func writeWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ x = 42 }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape15writeWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // CHECK: end_access [[ACCESS2]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape15writeWriteInoutyyF' // closure #1 in writeWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape15writeWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape15writeWriteInoutyyFyycfU_' // Error: on noescape write + write inout. func inoutWriteWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ x = 42 }, &x) } // inoutWriteWriteInout(x:) // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // CHECK: end_access [[ACCESS2]] // CHECK-LABEL: // end sil function '_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tF' // closure #1 in inoutWriteWriteInout(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tFyycfU_' // Traps on boxed write + write inout. // Covered by Interpreter/enforce_exclusive_access.swift. func writeBoxWriteInout() { var x = 3 let c = { x = 42 } // Around the call: [modify] [dynamic] // Inside closure: [modify] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape18writeBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[ACCESS]]) // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape18writeBoxWriteInoutyyF' // closure #1 in writeBoxWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_' // Error: Cannot capture inout // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func inoutWriteBoxWriteInout(x: inout Int) { // let c = { x = 42 } // doOneInout(c, &x) // } // Helper func doBlockInout(_: @convention(block) ()->(), _: inout Int) {} // FIXME: This case could be statically enforced, but requires quite a bit of SIL pattern matching. func readBlockWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] doBlockInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape19readBlockWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[F1:%.*]] = function_ref @_T027access_enforcement_noescape19readBlockWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () // CHECK: [[PA:%.*]] = partial_apply [[F1]](%0) : $@convention(thin) (@inout_aliasable Int) -> () // CHECK-NOT: begin_access // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply // CHECK: end_access [[WRITE]] : $*Int // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19readBlockWriteInoutyyF' // CHECK-LABEL: sil private @_T027access_enforcement_noescape19readBlockWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: begin_access [read] [static] %0 : $*Int // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19readBlockWriteInoutyyFyycfU_' // Test AccessSummaryAnalysis. // // The captured @inout_aliasable argument to `doOne` is re-partially applied, // then stored is a box before passing it to doBlockInout. func noEscapeBlock() { var x = 3 doOne { doBlockInout({ _ = x }, &x) } } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape13noEscapeBlockyyF : $@convention(thin) () -> () { // CHECK: partial_apply // CHECK-NOT: begin_access // CHECK: apply // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13noEscapeBlockyyF' // CHECK-LABEL: sil private @_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[F1:%.*]] = function_ref @_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_yycfU_ : $@convention(thin) (@inout_aliasable Int) -> () // CHECK: [[PA:%.*]] = partial_apply [[F1]](%0) : $@convention(thin) (@inout_aliasable Int) -> () // CHECK: [[STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> () // CHECK: [[ADDR:%.*]] = project_block_storage %5 : $*@block_storage @callee_owned () -> () // CHECK: store [[PA]] to [[ADDR]] : $*@callee_owned () -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[STORAGE]] : $*@block_storage @callee_owned () -> (), invoke %8 : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> ()) -> (), type $@convention(block) () -> () // CHECK: [[ARG:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> () // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[ARG]], [[WRITE]]) : $@convention(thin) (@owned @convention(block) () -> (), @inout Int) -> () // CHECK: end_access [[WRITE]] : $*Int // CHECK: destroy_addr [[ADDR]] : $*@callee_owned () -> () // CHECK: dealloc_stack [[STORAGE]] : $*@block_storage @callee_owned () -> () // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_' // CHECK-LABEL: sil private @_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_yycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: begin_access [read] [static] %0 : $*Int // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_yycfU_'
apache-2.0
29ade44b28e8dc1c9129c54067627c1a
46.579787
232
0.664878
3.313781
false
false
false
false
rustedivan/tapmap
geobaketool/Operations/OperationFitLabels.swift
1
1553
// // OperationFitLabels.swift // geobaketool // // Created by Ivan Milles on 2020-03-03. // Copyright © 2020 Wildbrain. All rights reserved. // import Foundation class OperationFitLabels : Operation { let input : ToolGeoFeatureMap var output : ToolGeoFeatureMap let report : ProgressReport init(features: ToolGeoFeatureMap, reporter: @escaping ProgressReport) { input = features report = reporter output = [:] super.init() } override func main() { guard !isCancelled else { print("Cancelled before starting"); return } for (key, feature) in input { let labelCenter = feature.tessellations.first!.visualCenter let rank: Int switch feature.level { case .Continent: rank = 0 case .Country: rank = 1 case .Province: rank = 2 } let regionMarker = GeoPlace(location: labelCenter, name: feature.name, kind: .Region, rank: rank) let editedPlaces = (feature.places ?? Set()).union([regionMarker]) let updatedFeature = ToolGeoFeature(level: feature.level, polygons: feature.polygons, tessellations: feature.tessellations, places: editedPlaces, children: feature.children, stringProperties: feature.stringProperties, valueProperties: feature.valueProperties) output[key] = updatedFeature if (output.count > 0) { let reportLine = "\(feature.name) labelled" report((Double(output.count) / Double(input.count)), reportLine, false) } } } }
mit
6fc3d45dca14c85c022bb1e2d8754928
25.758621
100
0.652062
3.776156
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/Shared/Main View Controllers/MainViewController.swift
1
7934
import UIKit import PopcornKit import PopcornTorrent.PTTorrentDownloadManager import MediaPlayer.MPMediaItem class MainViewController: UIViewController, CollectionViewControllerDelegate { func load(page: Int) {} func collectionView(isEmptyForUnknownReason collectionView: UICollectionView) {} func collectionView(_ collectionView: UICollectionView, titleForHeaderInSection section: Int) -> String? { return nil } func collectionView(nibForHeaderInCollectionView collectionView: UICollectionView) -> UINib? { return nil } func minItemSize(forCellIn collectionView: UICollectionView, at indexPath: IndexPath) -> CGSize? { return nil } func collectionView(_ collectionView: UICollectionView, insetForSectionAt section: Int) -> UIEdgeInsets? { return nil } @IBOutlet weak var sidePanelConstraint: NSLayoutConstraint? var collectionViewController: CollectionViewController! var collectionView: UICollectionView? { get { return collectionViewController?.collectionView } set(newObject) { collectionViewController?.collectionView = newObject } } var environmentsToFocus: [UIFocusEnvironment] = [] override var preferredFocusEnvironments: [UIFocusEnvironment] { return environmentsToFocus.isEmpty ? super.preferredFocusEnvironments : environmentsToFocus } override dynamic func viewWillAppear(_ animated: Bool) { if self.view.bounds != (super.navigationController?.view?.bounds)! { self.view.bounds = (super.navigationController?.view?.bounds)! } super.viewWillAppear(animated) #if os(iOS) navigationController?.navigationBar.isBackgroundHidden = false #else if #available(tvOS 13, *){ if (self.navigationItem.leftBarButtonItems?.count ?? 0 > 0){ (self.navigationItem.leftBarButtonItems?[0].customView?.subviews[0] as? UILabel)?.removeFromSuperview() self.navigationItem.leftBarButtonItems?.removeLast() } if (self.navigationItem.rightBarButtonItems?.count ?? 0 > 0){ for buttonItem in (self.navigationItem.rightBarButtonItems)! { buttonItem.customView?.subviews[0].removeFromSuperview() self.navigationItem.rightBarButtonItems?.removeFirst() } } } #endif navigationController?.navigationBar.tintColor = .app } override dynamic func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsFocusUpdate() updateFocusIfNeeded() environmentsToFocus.removeAll() collectionView?.setNeedsFocusUpdate() collectionView?.updateFocusIfNeeded() collectionView?.reloadData() } override dynamic func viewDidLoad() { super.viewDidLoad() collectionViewController.paginated = true load(page: 1) } func didRefresh(collectionView: UICollectionView) { collectionViewController.dataSources = [[]] collectionView.reloadData() load(page: 1) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "embed", let vc = segue.destination as? CollectionViewController { collectionViewController = vc collectionViewController.delegate = self #if os(iOS) collectionViewController.isRefreshable = true #endif } else if let segue = segue as? AutoPlayStoryboardSegue, segue.identifier == "showMovie" || segue.identifier == "showShow", let media: Media = sender as? Movie ?? sender as? Show, let vc = storyboard?.instantiateViewController(withIdentifier: String(describing: DetailViewController.self)) as? DetailViewController { #if os(tvOS) if let destination = segue.destination as? TVLoadingViewController { destination.loadView() // Initialize the @IBOutlets if let image = media.smallCoverImage, let url = URL(string: image) { destination.backgroundImageView.af_setImage(withURL: url) } destination.titleLabel.text = media.title } #endif // Exact same storyboard UI is being used for both classes. This will enable subclass-specific functions however, stored instance variables have to be set using `object_setIvar` otherwise there will be weird malloc crashes. object_setClass(vc, media is Movie ? MovieDetailViewController.self : ShowDetailViewController.self) #if os(iOS) navigationController?.navigationBar.isBackgroundHidden = true #endif vc.loadMedia(id: media.id) { (media, error) in guard let navigationController = segue.destination.navigationController, navigationController.visibleViewController === segue.destination // Make sure we're still loading and the user hasn't dismissed the view. else { return } let transition = CATransition() transition.duration = 0.5 transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) transition.type = CATransitionType.fade DispatchQueue.main.async() { navigationController.view.layer.add(transition, forKey: nil) } defer { DispatchQueue.main.asyncAfter(deadline: .now() + transition.duration) { var viewControllers = navigationController.viewControllers if let index = viewControllers.firstIndex(where: {$0 === segue.destination}) { viewControllers.remove(at: index) navigationController.setViewControllers(viewControllers, animated: false) } if let media = (media as? Show)?.latestUnwatchedEpisode() ?? media, segue.shouldAutoPlay { AppDelegate.shared.chooseQuality(nil, media: media) { torrent in AppDelegate.shared.play(media, torrent: torrent) } } } } if let error = error { let vc = UIViewController() let view: ErrorBackgroundView? = .fromNib() view?.setUpView(error: error) vc.view = view navigationController.pushViewController(vc, animated: false) } else if let currentItem = media { vc.currentItem = currentItem navigationController.pushViewController(vc, animated: false) } } } else if segue.identifier == "showPerson", let vc = segue.destination as? PersonViewController, let person: Person = sender as? Crew ?? sender as? Actor { vc.currentItem = person } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == "showLeftPane", #available(tvOS 13, *){ return true } if identifier == "showLeftPane"{ return false } return true } }
gpl-3.0
5ef0c7843635b2ddde9b06c220bb3361
42.593407
235
0.586211
6.208138
false
false
false
false
HunterMz/MZLayout
MZLayout/ViewController.swift
1
1376
// // ViewController.swift // MZLayout // // Created by 猎人 on 2016/12/21. // Copyright © 2016年 Hunter. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let aView = UIView() view.addSubview(aView) aView.backgroundColor = UIColor.blue let _ = aView.mz_setSize(width: 100, height: 100).mz_centreToSuperView() let bView = UIView() view.addSubview(bView) bView.backgroundColor = UIColor.red let _ = bView.mz_topToBottom(toView: aView, distance: 30).mz_axisXToSuperView(offsetX: 0).mz_widthToWidth(toView: aView, multiplier: 1).mz_heightToHeight(toView: aView, multiplier: 1); let cView = UIView() bView.addSubview(cView) cView.backgroundColor = UIColor.white let dView = UIView() bView.addSubview(dView) dView.backgroundColor = UIColor.black let _ = cView.mz_topToSuperView(distance: 20).mz_leftToSuperView(distance: 0).mz_bottomToSuperView(distance: 0) let _ = dView.mz_topToSuperView(distance: 20).mz_leftToRight(toView: cView, distance: 10).mz_bottomToSuperView(distance: 0).mz_rightToSuperView(distance: 0).mz_widthToWidth(toView: cView, multiplier: 1) } }
apache-2.0
9e839c74970bd6f4ca3eeaad4e81d2f7
30.837209
210
0.636231
4.098802
false
false
false
false
luongm/fastlane
fastlane/swift/Fastlane.swift
1
353169
import Foundation @discardableResult func adb(serial: String = "", command: String? = nil, adbPath: String = "adb") -> String { let command = RubyCommand(commandID: "", methodName: "adb", className: nil, args: [RubyCommand.Argument(name: "serial", value: serial), RubyCommand.Argument(name: "command", value: command), RubyCommand.Argument(name: "adb_path", value: adbPath)]) return runner.executeCommand(command) } func adbDevices(adbPath: String = "adb") { let command = RubyCommand(commandID: "", methodName: "adb_devices", className: nil, args: [RubyCommand.Argument(name: "adb_path", value: adbPath)]) _ = runner.executeCommand(command) } func addExtraPlatforms(platforms: [String] = []) { let command = RubyCommand(commandID: "", methodName: "add_extra_platforms", className: nil, args: [RubyCommand.Argument(name: "platforms", value: platforms)]) _ = runner.executeCommand(command) } func addGitTag(tag: String? = nil, grouping: String = "builds", `prefix`: String = "", buildNumber: String, message: String? = nil, commit: String? = nil, force: Bool = false, sign: Bool = false) { let command = RubyCommand(commandID: "", methodName: "add_git_tag", className: nil, args: [RubyCommand.Argument(name: "tag", value: tag), RubyCommand.Argument(name: "grouping", value: grouping), RubyCommand.Argument(name: "prefix", value: `prefix`), RubyCommand.Argument(name: "build_number", value: buildNumber), RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "commit", value: commit), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "sign", value: sign)]) _ = runner.executeCommand(command) } func appStoreBuildNumber(initialBuildNumber: String = "1", appIdentifier: String, username: String, teamId: String? = nil, live: Bool = true, version: String? = nil, platform: String = "ios", teamName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "app_store_build_number", className: nil, args: [RubyCommand.Argument(name: "initial_build_number", value: initialBuildNumber), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "live", value: live), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "team_name", value: teamName)]) _ = runner.executeCommand(command) } func appaloosa(binary: String, apiToken: String, storeId: String, groupIds: String = "", screenshots: String, locale: String = "en-US", device: String? = nil, description: String? = nil) { let command = RubyCommand(commandID: "", methodName: "appaloosa", className: nil, args: [RubyCommand.Argument(name: "binary", value: binary), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "store_id", value: storeId), RubyCommand.Argument(name: "group_ids", value: groupIds), RubyCommand.Argument(name: "screenshots", value: screenshots), RubyCommand.Argument(name: "locale", value: locale), RubyCommand.Argument(name: "device", value: device), RubyCommand.Argument(name: "description", value: description)]) _ = runner.executeCommand(command) } func appetize(apiToken: String, url: String? = nil, platform: String = "ios", path: String? = nil, publicKey: String? = nil, note: String? = nil) { let command = RubyCommand(commandID: "", methodName: "appetize", className: nil, args: [RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "url", value: url), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "public_key", value: publicKey), RubyCommand.Argument(name: "note", value: note)]) _ = runner.executeCommand(command) } func appetizeViewingUrlGenerator(publicKey: String, baseUrl: String = "https://appetize.io/embed", device: String = "iphone5s", scale: String? = nil, orientation: String = "portrait", language: String? = nil, color: String = "black", launchUrl: String? = nil, osVersion: String? = nil, params: String? = nil, proxy: String? = nil) { let command = RubyCommand(commandID: "", methodName: "appetize_viewing_url_generator", className: nil, args: [RubyCommand.Argument(name: "public_key", value: publicKey), RubyCommand.Argument(name: "base_url", value: baseUrl), RubyCommand.Argument(name: "device", value: device), RubyCommand.Argument(name: "scale", value: scale), RubyCommand.Argument(name: "orientation", value: orientation), RubyCommand.Argument(name: "language", value: language), RubyCommand.Argument(name: "color", value: color), RubyCommand.Argument(name: "launch_url", value: launchUrl), RubyCommand.Argument(name: "os_version", value: osVersion), RubyCommand.Argument(name: "params", value: params), RubyCommand.Argument(name: "proxy", value: proxy)]) _ = runner.executeCommand(command) } func appium(platform: String, specPath: String, appPath: String, invokeAppiumServer: Bool = true, host: String = "0.0.0.0", port: String = "4723", appiumPath: String? = nil, caps: [String : Any]? = nil, appiumLib: [String : Any]? = nil) { let command = RubyCommand(commandID: "", methodName: "appium", className: nil, args: [RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "spec_path", value: specPath), RubyCommand.Argument(name: "app_path", value: appPath), RubyCommand.Argument(name: "invoke_appium_server", value: invokeAppiumServer), RubyCommand.Argument(name: "host", value: host), RubyCommand.Argument(name: "port", value: port), RubyCommand.Argument(name: "appium_path", value: appiumPath), RubyCommand.Argument(name: "caps", value: caps), RubyCommand.Argument(name: "appium_lib", value: appiumLib)]) _ = runner.executeCommand(command) } func appledoc(input: String, output: String? = nil, templates: String? = nil, docsetInstallPath: String? = nil, include: String? = nil, ignore: String? = nil, excludeOutput: String? = nil, indexDesc: String? = nil, projectName: String, projectVersion: String? = nil, projectCompany: String, companyId: String? = nil, createHtml: Bool = false, createDocset: Bool = false, installDocset: Bool = false, publishDocset: Bool = false, noCreateDocset: Bool = false, htmlAnchors: String? = nil, cleanOutput: Bool = false, docsetBundleId: String? = nil, docsetBundleName: String? = nil, docsetDesc: String? = nil, docsetCopyright: String? = nil, docsetFeedName: String? = nil, docsetFeedUrl: String? = nil, docsetFeedFormats: String? = nil, docsetPackageUrl: String? = nil, docsetFallbackUrl: String? = nil, docsetPublisherId: String? = nil, docsetPublisherName: String? = nil, docsetMinXcodeVersion: String? = nil, docsetPlatformFamily: String? = nil, docsetCertIssuer: String? = nil, docsetCertSigner: String? = nil, docsetBundleFilename: String? = nil, docsetAtomFilename: String? = nil, docsetXmlFilename: String? = nil, docsetPackageFilename: String? = nil, options: String? = nil, crossrefFormat: String? = nil, exitThreshold: String = "2", docsSectionTitle: String? = nil, warnings: String? = nil, logformat: String? = nil, verbose: String? = nil) { let command = RubyCommand(commandID: "", methodName: "appledoc", className: nil, args: [RubyCommand.Argument(name: "input", value: input), RubyCommand.Argument(name: "output", value: output), RubyCommand.Argument(name: "templates", value: templates), RubyCommand.Argument(name: "docset_install_path", value: docsetInstallPath), RubyCommand.Argument(name: "include", value: include), RubyCommand.Argument(name: "ignore", value: ignore), RubyCommand.Argument(name: "exclude_output", value: excludeOutput), RubyCommand.Argument(name: "index_desc", value: indexDesc), RubyCommand.Argument(name: "project_name", value: projectName), RubyCommand.Argument(name: "project_version", value: projectVersion), RubyCommand.Argument(name: "project_company", value: projectCompany), RubyCommand.Argument(name: "company_id", value: companyId), RubyCommand.Argument(name: "create_html", value: createHtml), RubyCommand.Argument(name: "create_docset", value: createDocset), RubyCommand.Argument(name: "install_docset", value: installDocset), RubyCommand.Argument(name: "publish_docset", value: publishDocset), RubyCommand.Argument(name: "no_create_docset", value: noCreateDocset), RubyCommand.Argument(name: "html_anchors", value: htmlAnchors), RubyCommand.Argument(name: "clean_output", value: cleanOutput), RubyCommand.Argument(name: "docset_bundle_id", value: docsetBundleId), RubyCommand.Argument(name: "docset_bundle_name", value: docsetBundleName), RubyCommand.Argument(name: "docset_desc", value: docsetDesc), RubyCommand.Argument(name: "docset_copyright", value: docsetCopyright), RubyCommand.Argument(name: "docset_feed_name", value: docsetFeedName), RubyCommand.Argument(name: "docset_feed_url", value: docsetFeedUrl), RubyCommand.Argument(name: "docset_feed_formats", value: docsetFeedFormats), RubyCommand.Argument(name: "docset_package_url", value: docsetPackageUrl), RubyCommand.Argument(name: "docset_fallback_url", value: docsetFallbackUrl), RubyCommand.Argument(name: "docset_publisher_id", value: docsetPublisherId), RubyCommand.Argument(name: "docset_publisher_name", value: docsetPublisherName), RubyCommand.Argument(name: "docset_min_xcode_version", value: docsetMinXcodeVersion), RubyCommand.Argument(name: "docset_platform_family", value: docsetPlatformFamily), RubyCommand.Argument(name: "docset_cert_issuer", value: docsetCertIssuer), RubyCommand.Argument(name: "docset_cert_signer", value: docsetCertSigner), RubyCommand.Argument(name: "docset_bundle_filename", value: docsetBundleFilename), RubyCommand.Argument(name: "docset_atom_filename", value: docsetAtomFilename), RubyCommand.Argument(name: "docset_xml_filename", value: docsetXmlFilename), RubyCommand.Argument(name: "docset_package_filename", value: docsetPackageFilename), RubyCommand.Argument(name: "options", value: options), RubyCommand.Argument(name: "crossref_format", value: crossrefFormat), RubyCommand.Argument(name: "exit_threshold", value: exitThreshold), RubyCommand.Argument(name: "docs_section_title", value: docsSectionTitle), RubyCommand.Argument(name: "warnings", value: warnings), RubyCommand.Argument(name: "logformat", value: logformat), RubyCommand.Argument(name: "verbose", value: verbose)]) _ = runner.executeCommand(command) } func appstore(username: String, appIdentifier: String? = nil, app: String, editLive: Bool = false, ipa: String? = nil, pkg: String? = nil, platform: String = "ios", metadataPath: String? = nil, screenshotsPath: String? = nil, skipBinaryUpload: Bool = false, useLiveVersion: Bool = false, skipScreenshots: Bool = false, appVersion: String? = nil, skipMetadata: Bool = false, skipAppVersionUpdate: Bool = false, force: Bool = false, submitForReview: Bool = false, automaticRelease: Bool = false, autoReleaseDate: String? = nil, phasedRelease: Bool = false, priceTier: String? = nil, buildNumber: String? = nil, appRatingConfigPath: String? = nil, submissionInformation: String? = nil, teamId: String? = nil, teamName: String? = nil, devPortalTeamId: String? = nil, devPortalTeamName: String? = nil, itcProvider: String? = nil, overwriteScreenshots: Bool = false, runPrecheckBeforeSubmit: Bool = true, precheckDefaultRuleLevel: String = "warn", appIcon: String? = nil, appleWatchAppIcon: String? = nil, copyright: String? = nil, primaryCategory: String? = nil, secondaryCategory: String? = nil, primaryFirstSubCategory: String? = nil, primarySecondSubCategory: String? = nil, secondaryFirstSubCategory: String? = nil, secondarySecondSubCategory: String? = nil, tradeRepresentativeContactInformation: [String : Any]? = nil, appReviewInformation: [String : Any]? = nil, description: String? = nil, name: String? = nil, subtitle: [String : Any]? = nil, keywords: [String : Any]? = nil, promotionalText: [String : Any]? = nil, releaseNotes: String? = nil, privacyUrl: String? = nil, supportUrl: String? = nil, marketingUrl: String? = nil, languages: [String]? = nil, ignoreLanguageDirectoryValidation: Bool = false, precheckIncludeInAppPurchases: Bool = true) { let command = RubyCommand(commandID: "", methodName: "appstore", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "app", value: app), RubyCommand.Argument(name: "edit_live", value: editLive), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "pkg", value: pkg), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "metadata_path", value: metadataPath), RubyCommand.Argument(name: "screenshots_path", value: screenshotsPath), RubyCommand.Argument(name: "skip_binary_upload", value: skipBinaryUpload), RubyCommand.Argument(name: "use_live_version", value: useLiveVersion), RubyCommand.Argument(name: "skip_screenshots", value: skipScreenshots), RubyCommand.Argument(name: "app_version", value: appVersion), RubyCommand.Argument(name: "skip_metadata", value: skipMetadata), RubyCommand.Argument(name: "skip_app_version_update", value: skipAppVersionUpdate), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "submit_for_review", value: submitForReview), RubyCommand.Argument(name: "automatic_release", value: automaticRelease), RubyCommand.Argument(name: "auto_release_date", value: autoReleaseDate), RubyCommand.Argument(name: "phased_release", value: phasedRelease), RubyCommand.Argument(name: "price_tier", value: priceTier), RubyCommand.Argument(name: "build_number", value: buildNumber), RubyCommand.Argument(name: "app_rating_config_path", value: appRatingConfigPath), RubyCommand.Argument(name: "submission_information", value: submissionInformation), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "dev_portal_team_id", value: devPortalTeamId), RubyCommand.Argument(name: "dev_portal_team_name", value: devPortalTeamName), RubyCommand.Argument(name: "itc_provider", value: itcProvider), RubyCommand.Argument(name: "overwrite_screenshots", value: overwriteScreenshots), RubyCommand.Argument(name: "run_precheck_before_submit", value: runPrecheckBeforeSubmit), RubyCommand.Argument(name: "precheck_default_rule_level", value: precheckDefaultRuleLevel), RubyCommand.Argument(name: "app_icon", value: appIcon), RubyCommand.Argument(name: "apple_watch_app_icon", value: appleWatchAppIcon), RubyCommand.Argument(name: "copyright", value: copyright), RubyCommand.Argument(name: "primary_category", value: primaryCategory), RubyCommand.Argument(name: "secondary_category", value: secondaryCategory), RubyCommand.Argument(name: "primary_first_sub_category", value: primaryFirstSubCategory), RubyCommand.Argument(name: "primary_second_sub_category", value: primarySecondSubCategory), RubyCommand.Argument(name: "secondary_first_sub_category", value: secondaryFirstSubCategory), RubyCommand.Argument(name: "secondary_second_sub_category", value: secondarySecondSubCategory), RubyCommand.Argument(name: "trade_representative_contact_information", value: tradeRepresentativeContactInformation), RubyCommand.Argument(name: "app_review_information", value: appReviewInformation), RubyCommand.Argument(name: "description", value: description), RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "subtitle", value: subtitle), RubyCommand.Argument(name: "keywords", value: keywords), RubyCommand.Argument(name: "promotional_text", value: promotionalText), RubyCommand.Argument(name: "release_notes", value: releaseNotes), RubyCommand.Argument(name: "privacy_url", value: privacyUrl), RubyCommand.Argument(name: "support_url", value: supportUrl), RubyCommand.Argument(name: "marketing_url", value: marketingUrl), RubyCommand.Argument(name: "languages", value: languages), RubyCommand.Argument(name: "ignore_language_directory_validation", value: ignoreLanguageDirectoryValidation), RubyCommand.Argument(name: "precheck_include_in_app_purchases", value: precheckIncludeInAppPurchases)]) _ = runner.executeCommand(command) } func apteligent(dsym: String? = nil, appId: String, apiKey: String) { let command = RubyCommand(commandID: "", methodName: "apteligent", className: nil, args: [RubyCommand.Argument(name: "dsym", value: dsym), RubyCommand.Argument(name: "app_id", value: appId), RubyCommand.Argument(name: "api_key", value: apiKey)]) _ = runner.executeCommand(command) } func artifactory(file: String, repo: String, repoPath: String, endpoint: String, username: String, password: String, properties: String = "{}", sslPemFile: String? = nil, sslVerify: Bool = true, proxyUsername: String? = nil, proxyPassword: String? = nil, proxyAddress: String? = nil, proxyPort: String? = nil) { let command = RubyCommand(commandID: "", methodName: "artifactory", className: nil, args: [RubyCommand.Argument(name: "file", value: file), RubyCommand.Argument(name: "repo", value: repo), RubyCommand.Argument(name: "repo_path", value: repoPath), RubyCommand.Argument(name: "endpoint", value: endpoint), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "properties", value: properties), RubyCommand.Argument(name: "ssl_pem_file", value: sslPemFile), RubyCommand.Argument(name: "ssl_verify", value: sslVerify), RubyCommand.Argument(name: "proxy_username", value: proxyUsername), RubyCommand.Argument(name: "proxy_password", value: proxyPassword), RubyCommand.Argument(name: "proxy_address", value: proxyAddress), RubyCommand.Argument(name: "proxy_port", value: proxyPort)]) _ = runner.executeCommand(command) } func automaticCodeSigning(path: String, useAutomaticSigning: Bool = false, teamId: String? = nil, targets: [String]? = nil, codeSignIdentity: String? = nil, profileName: String? = nil, profileUuid: String? = nil, bundleIdentifier: String? = nil) { let command = RubyCommand(commandID: "", methodName: "automatic_code_signing", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "use_automatic_signing", value: useAutomaticSigning), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "targets", value: targets), RubyCommand.Argument(name: "code_sign_identity", value: codeSignIdentity), RubyCommand.Argument(name: "profile_name", value: profileName), RubyCommand.Argument(name: "profile_uuid", value: profileUuid), RubyCommand.Argument(name: "bundle_identifier", value: bundleIdentifier)]) _ = runner.executeCommand(command) } func backupFile(path: String) { let command = RubyCommand(commandID: "", methodName: "backup_file", className: nil, args: [RubyCommand.Argument(name: "path", value: path)]) _ = runner.executeCommand(command) } func backupXcarchive(xcarchive: String, destination: String, zip: Bool = true, zipFilename: String? = nil, versioned: Bool = true) { let command = RubyCommand(commandID: "", methodName: "backup_xcarchive", className: nil, args: [RubyCommand.Argument(name: "xcarchive", value: xcarchive), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "zip", value: zip), RubyCommand.Argument(name: "zip_filename", value: zipFilename), RubyCommand.Argument(name: "versioned", value: versioned)]) _ = runner.executeCommand(command) } func badge(dark: String? = nil, custom: String? = nil, noBadge: String? = nil, shield: String? = nil, alpha: String? = nil, path: String = ".", shieldIoTimeout: String? = nil, glob: String? = nil, alphaChannel: String? = nil, shieldGravity: String? = nil, shieldNoResize: String? = nil) { let command = RubyCommand(commandID: "", methodName: "badge", className: nil, args: [RubyCommand.Argument(name: "dark", value: dark), RubyCommand.Argument(name: "custom", value: custom), RubyCommand.Argument(name: "no_badge", value: noBadge), RubyCommand.Argument(name: "shield", value: shield), RubyCommand.Argument(name: "alpha", value: alpha), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "shield_io_timeout", value: shieldIoTimeout), RubyCommand.Argument(name: "glob", value: glob), RubyCommand.Argument(name: "alpha_channel", value: alphaChannel), RubyCommand.Argument(name: "shield_gravity", value: shieldGravity), RubyCommand.Argument(name: "shield_no_resize", value: shieldNoResize)]) _ = runner.executeCommand(command) } func buildAndUploadToAppetize(xcodebuild: [String : Any] = [:], scheme: String? = nil, apiToken: String) { let command = RubyCommand(commandID: "", methodName: "build_and_upload_to_appetize", className: nil, args: [RubyCommand.Argument(name: "xcodebuild", value: xcodebuild), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "api_token", value: apiToken)]) _ = runner.executeCommand(command) } func buildAndroidApp(task: String, flavor: String? = nil, buildType: String? = nil, flags: String? = nil, projectDir: String = ".", gradlePath: String? = nil, properties: String? = nil, systemProperties: String? = nil, serial: String = "", printCommand: Bool = true, printCommandOutput: Bool = true) { let command = RubyCommand(commandID: "", methodName: "build_android_app", className: nil, args: [RubyCommand.Argument(name: "task", value: task), RubyCommand.Argument(name: "flavor", value: flavor), RubyCommand.Argument(name: "build_type", value: buildType), RubyCommand.Argument(name: "flags", value: flags), RubyCommand.Argument(name: "project_dir", value: projectDir), RubyCommand.Argument(name: "gradle_path", value: gradlePath), RubyCommand.Argument(name: "properties", value: properties), RubyCommand.Argument(name: "system_properties", value: systemProperties), RubyCommand.Argument(name: "serial", value: serial), RubyCommand.Argument(name: "print_command", value: printCommand), RubyCommand.Argument(name: "print_command_output", value: printCommandOutput)]) _ = runner.executeCommand(command) } func buildApp(workspace: String? = nil, project: String? = nil, scheme: String? = nil, clean: Bool = false, outputDirectory: String = ".", outputName: String? = nil, configuration: String? = nil, silent: Bool = false, codesigningIdentity: String? = nil, skipPackageIpa: Bool = false, includeSymbols: Bool? = nil, includeBitcode: Bool? = nil, exportMethod: String? = nil, exportOptions: [String : Any]? = nil, exportXcargs: String? = nil, skipBuildArchive: Bool? = nil, skipArchive: Bool? = nil, buildPath: String? = nil, archivePath: String? = nil, derivedDataPath: String? = nil, resultBundle: String? = nil, buildlogPath: String = "~/Library/Logs/gym", sdk: String? = nil, toolchain: String? = nil, destination: String? = nil, exportTeamId: String? = nil, xcargs: String? = nil, xcconfig: String? = nil, suppressXcodeOutput: String? = nil, disableXcpretty: String? = nil, xcprettyTestFormat: String? = nil, xcprettyFormatter: String? = nil, xcprettyReportJunit: String? = nil, xcprettyReportHtml: String? = nil, xcprettyReportJson: String? = nil, analyzeBuildTime: String? = nil, xcprettyUtf: String? = nil, skipProfileDetection: Bool = false) { let command = RubyCommand(commandID: "", methodName: "build_app", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_name", value: outputName), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "silent", value: silent), RubyCommand.Argument(name: "codesigning_identity", value: codesigningIdentity), RubyCommand.Argument(name: "skip_package_ipa", value: skipPackageIpa), RubyCommand.Argument(name: "include_symbols", value: includeSymbols), RubyCommand.Argument(name: "include_bitcode", value: includeBitcode), RubyCommand.Argument(name: "export_method", value: exportMethod), RubyCommand.Argument(name: "export_options", value: exportOptions), RubyCommand.Argument(name: "export_xcargs", value: exportXcargs), RubyCommand.Argument(name: "skip_build_archive", value: skipBuildArchive), RubyCommand.Argument(name: "skip_archive", value: skipArchive), RubyCommand.Argument(name: "build_path", value: buildPath), RubyCommand.Argument(name: "archive_path", value: archivePath), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "result_bundle", value: resultBundle), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "toolchain", value: toolchain), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "export_team_id", value: exportTeamId), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "xcconfig", value: xcconfig), RubyCommand.Argument(name: "suppress_xcode_output", value: suppressXcodeOutput), RubyCommand.Argument(name: "disable_xcpretty", value: disableXcpretty), RubyCommand.Argument(name: "xcpretty_test_format", value: xcprettyTestFormat), RubyCommand.Argument(name: "xcpretty_formatter", value: xcprettyFormatter), RubyCommand.Argument(name: "xcpretty_report_junit", value: xcprettyReportJunit), RubyCommand.Argument(name: "xcpretty_report_html", value: xcprettyReportHtml), RubyCommand.Argument(name: "xcpretty_report_json", value: xcprettyReportJson), RubyCommand.Argument(name: "analyze_build_time", value: analyzeBuildTime), RubyCommand.Argument(name: "xcpretty_utf", value: xcprettyUtf), RubyCommand.Argument(name: "skip_profile_detection", value: skipProfileDetection)]) _ = runner.executeCommand(command) } func buildIosApp(workspace: String? = nil, project: String? = nil, scheme: String? = nil, clean: Bool = false, outputDirectory: String = ".", outputName: String? = nil, configuration: String? = nil, silent: Bool = false, codesigningIdentity: String? = nil, skipPackageIpa: Bool = false, includeSymbols: Bool? = nil, includeBitcode: Bool? = nil, exportMethod: String? = nil, exportOptions: [String : Any]? = nil, exportXcargs: String? = nil, skipBuildArchive: Bool? = nil, skipArchive: Bool? = nil, buildPath: String? = nil, archivePath: String? = nil, derivedDataPath: String? = nil, resultBundle: String? = nil, buildlogPath: String = "~/Library/Logs/gym", sdk: String? = nil, toolchain: String? = nil, destination: String? = nil, exportTeamId: String? = nil, xcargs: String? = nil, xcconfig: String? = nil, suppressXcodeOutput: String? = nil, disableXcpretty: String? = nil, xcprettyTestFormat: String? = nil, xcprettyFormatter: String? = nil, xcprettyReportJunit: String? = nil, xcprettyReportHtml: String? = nil, xcprettyReportJson: String? = nil, analyzeBuildTime: String? = nil, xcprettyUtf: String? = nil, skipProfileDetection: Bool = false) { let command = RubyCommand(commandID: "", methodName: "build_ios_app", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_name", value: outputName), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "silent", value: silent), RubyCommand.Argument(name: "codesigning_identity", value: codesigningIdentity), RubyCommand.Argument(name: "skip_package_ipa", value: skipPackageIpa), RubyCommand.Argument(name: "include_symbols", value: includeSymbols), RubyCommand.Argument(name: "include_bitcode", value: includeBitcode), RubyCommand.Argument(name: "export_method", value: exportMethod), RubyCommand.Argument(name: "export_options", value: exportOptions), RubyCommand.Argument(name: "export_xcargs", value: exportXcargs), RubyCommand.Argument(name: "skip_build_archive", value: skipBuildArchive), RubyCommand.Argument(name: "skip_archive", value: skipArchive), RubyCommand.Argument(name: "build_path", value: buildPath), RubyCommand.Argument(name: "archive_path", value: archivePath), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "result_bundle", value: resultBundle), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "toolchain", value: toolchain), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "export_team_id", value: exportTeamId), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "xcconfig", value: xcconfig), RubyCommand.Argument(name: "suppress_xcode_output", value: suppressXcodeOutput), RubyCommand.Argument(name: "disable_xcpretty", value: disableXcpretty), RubyCommand.Argument(name: "xcpretty_test_format", value: xcprettyTestFormat), RubyCommand.Argument(name: "xcpretty_formatter", value: xcprettyFormatter), RubyCommand.Argument(name: "xcpretty_report_junit", value: xcprettyReportJunit), RubyCommand.Argument(name: "xcpretty_report_html", value: xcprettyReportHtml), RubyCommand.Argument(name: "xcpretty_report_json", value: xcprettyReportJson), RubyCommand.Argument(name: "analyze_build_time", value: analyzeBuildTime), RubyCommand.Argument(name: "xcpretty_utf", value: xcprettyUtf), RubyCommand.Argument(name: "skip_profile_detection", value: skipProfileDetection)]) _ = runner.executeCommand(command) } func bundleInstall(binstubs: String? = nil, clean: Bool = false, fullIndex: Bool = false, gemfile: String? = nil, jobs: Bool? = nil, local: Bool = false, deployment: Bool = false, noCache: Bool = false, noPrune: Bool = false, path: String? = nil, system: Bool = false, quiet: Bool = false, retry: Bool? = nil, shebang: String? = nil, standalone: String? = nil, trustPolicy: String? = nil, without: String? = nil, with: String? = nil) { let command = RubyCommand(commandID: "", methodName: "bundle_install", className: nil, args: [RubyCommand.Argument(name: "binstubs", value: binstubs), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "full_index", value: fullIndex), RubyCommand.Argument(name: "gemfile", value: gemfile), RubyCommand.Argument(name: "jobs", value: jobs), RubyCommand.Argument(name: "local", value: local), RubyCommand.Argument(name: "deployment", value: deployment), RubyCommand.Argument(name: "no_cache", value: noCache), RubyCommand.Argument(name: "no_prune", value: noPrune), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "system", value: system), RubyCommand.Argument(name: "quiet", value: quiet), RubyCommand.Argument(name: "retry", value: retry), RubyCommand.Argument(name: "shebang", value: shebang), RubyCommand.Argument(name: "standalone", value: standalone), RubyCommand.Argument(name: "trust_policy", value: trustPolicy), RubyCommand.Argument(name: "without", value: without), RubyCommand.Argument(name: "with", value: with)]) _ = runner.executeCommand(command) } func captureAndroidScreenshots(androidHome: String? = nil, buildToolsVersion: String? = nil, locales: [String] = ["en-US"], clearPreviousScreenshots: Bool = false, outputDirectory: String = "fastlane/metadata/android", skipOpenSummary: Bool = false, appPackageName: String, testsPackageName: String? = nil, useTestsInPackages: [String]? = nil, useTestsInClasses: [String]? = nil, launchArguments: [String]? = nil, testInstrumentationRunner: String = "android.support.test.runner.AndroidJUnitRunner", endingLocale: String = "en-US", appApkPath: String? = nil, testsApkPath: String? = nil, specificDevice: String? = nil, deviceType: String = "phone", exitOnTestFailure: Bool = true, reinstallApp: Bool = false) { let command = RubyCommand(commandID: "", methodName: "capture_android_screenshots", className: nil, args: [RubyCommand.Argument(name: "android_home", value: androidHome), RubyCommand.Argument(name: "build_tools_version", value: buildToolsVersion), RubyCommand.Argument(name: "locales", value: locales), RubyCommand.Argument(name: "clear_previous_screenshots", value: clearPreviousScreenshots), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "skip_open_summary", value: skipOpenSummary), RubyCommand.Argument(name: "app_package_name", value: appPackageName), RubyCommand.Argument(name: "tests_package_name", value: testsPackageName), RubyCommand.Argument(name: "use_tests_in_packages", value: useTestsInPackages), RubyCommand.Argument(name: "use_tests_in_classes", value: useTestsInClasses), RubyCommand.Argument(name: "launch_arguments", value: launchArguments), RubyCommand.Argument(name: "test_instrumentation_runner", value: testInstrumentationRunner), RubyCommand.Argument(name: "ending_locale", value: endingLocale), RubyCommand.Argument(name: "app_apk_path", value: appApkPath), RubyCommand.Argument(name: "tests_apk_path", value: testsApkPath), RubyCommand.Argument(name: "specific_device", value: specificDevice), RubyCommand.Argument(name: "device_type", value: deviceType), RubyCommand.Argument(name: "exit_on_test_failure", value: exitOnTestFailure), RubyCommand.Argument(name: "reinstall_app", value: reinstallApp)]) _ = runner.executeCommand(command) } func captureIosScreenshots(workspace: String? = nil, project: String? = nil, xcargs: String? = nil, devices: [String]? = nil, languages: [String] = ["en-US"], launchArguments: [String] = [""], outputDirectory: String = "screenshots", outputSimulatorLogs: Bool = false, iosVersion: String? = nil, skipOpenSummary: Bool = false, skipHelperVersionCheck: Bool = false, clearPreviousScreenshots: Bool = false, reinstallApp: Bool = false, eraseSimulator: Bool = false, localizeSimulator: Bool = false, appIdentifier: String? = nil, addPhotos: [String]? = nil, addVideos: [String]? = nil, buildlogPath: String = "~/Library/Logs/snapshot", clean: Bool = false, testWithoutBuilding: Bool? = nil, configuration: String? = nil, xcprettyArgs: String? = nil, sdk: String? = nil, scheme: String? = nil, numberOfRetries: Int = 1, stopAfterFirstError: Bool = false, derivedDataPath: String? = nil, testTargetName: String? = nil, namespaceLogFiles: String? = nil, concurrentSimulators: Bool = true) { let command = RubyCommand(commandID: "", methodName: "capture_ios_screenshots", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "devices", value: devices), RubyCommand.Argument(name: "languages", value: languages), RubyCommand.Argument(name: "launch_arguments", value: launchArguments), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_simulator_logs", value: outputSimulatorLogs), RubyCommand.Argument(name: "ios_version", value: iosVersion), RubyCommand.Argument(name: "skip_open_summary", value: skipOpenSummary), RubyCommand.Argument(name: "skip_helper_version_check", value: skipHelperVersionCheck), RubyCommand.Argument(name: "clear_previous_screenshots", value: clearPreviousScreenshots), RubyCommand.Argument(name: "reinstall_app", value: reinstallApp), RubyCommand.Argument(name: "erase_simulator", value: eraseSimulator), RubyCommand.Argument(name: "localize_simulator", value: localizeSimulator), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "add_photos", value: addPhotos), RubyCommand.Argument(name: "add_videos", value: addVideos), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "test_without_building", value: testWithoutBuilding), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "xcpretty_args", value: xcprettyArgs), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "number_of_retries", value: numberOfRetries), RubyCommand.Argument(name: "stop_after_first_error", value: stopAfterFirstError), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "test_target_name", value: testTargetName), RubyCommand.Argument(name: "namespace_log_files", value: namespaceLogFiles), RubyCommand.Argument(name: "concurrent_simulators", value: concurrentSimulators)]) _ = runner.executeCommand(command) } func captureScreenshots(workspace: String? = nil, project: String? = nil, xcargs: String? = nil, devices: [String]? = nil, languages: [String] = ["en-US"], launchArguments: [String] = [""], outputDirectory: String = "screenshots", outputSimulatorLogs: Bool = false, iosVersion: String? = nil, skipOpenSummary: Bool = false, skipHelperVersionCheck: Bool = false, clearPreviousScreenshots: Bool = false, reinstallApp: Bool = false, eraseSimulator: Bool = false, localizeSimulator: Bool = false, appIdentifier: String? = nil, addPhotos: [String]? = nil, addVideos: [String]? = nil, buildlogPath: String = "~/Library/Logs/snapshot", clean: Bool = false, testWithoutBuilding: Bool? = nil, configuration: String? = nil, xcprettyArgs: String? = nil, sdk: String? = nil, scheme: String? = nil, numberOfRetries: Int = 1, stopAfterFirstError: Bool = false, derivedDataPath: String? = nil, testTargetName: String? = nil, namespaceLogFiles: String? = nil, concurrentSimulators: Bool = true) { let command = RubyCommand(commandID: "", methodName: "capture_screenshots", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "devices", value: devices), RubyCommand.Argument(name: "languages", value: languages), RubyCommand.Argument(name: "launch_arguments", value: launchArguments), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_simulator_logs", value: outputSimulatorLogs), RubyCommand.Argument(name: "ios_version", value: iosVersion), RubyCommand.Argument(name: "skip_open_summary", value: skipOpenSummary), RubyCommand.Argument(name: "skip_helper_version_check", value: skipHelperVersionCheck), RubyCommand.Argument(name: "clear_previous_screenshots", value: clearPreviousScreenshots), RubyCommand.Argument(name: "reinstall_app", value: reinstallApp), RubyCommand.Argument(name: "erase_simulator", value: eraseSimulator), RubyCommand.Argument(name: "localize_simulator", value: localizeSimulator), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "add_photos", value: addPhotos), RubyCommand.Argument(name: "add_videos", value: addVideos), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "test_without_building", value: testWithoutBuilding), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "xcpretty_args", value: xcprettyArgs), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "number_of_retries", value: numberOfRetries), RubyCommand.Argument(name: "stop_after_first_error", value: stopAfterFirstError), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "test_target_name", value: testTargetName), RubyCommand.Argument(name: "namespace_log_files", value: namespaceLogFiles), RubyCommand.Argument(name: "concurrent_simulators", value: concurrentSimulators)]) _ = runner.executeCommand(command) } func carthage(command: String = "bootstrap", dependencies: [String] = [], useSsh: Bool? = nil, useSubmodules: Bool? = nil, useBinaries: Bool? = nil, noBuild: Bool? = nil, noSkipCurrent: Bool? = nil, derivedData: String? = nil, verbose: Bool? = nil, platform: String? = nil, cacheBuilds: Bool = false, frameworks: [String] = [], output: String? = nil, configuration: String? = nil, toolchain: String? = nil, projectDirectory: String? = nil, newResolver: Bool? = nil) { let command = RubyCommand(commandID: "", methodName: "carthage", className: nil, args: [RubyCommand.Argument(name: "command", value: command), RubyCommand.Argument(name: "dependencies", value: dependencies), RubyCommand.Argument(name: "use_ssh", value: useSsh), RubyCommand.Argument(name: "use_submodules", value: useSubmodules), RubyCommand.Argument(name: "use_binaries", value: useBinaries), RubyCommand.Argument(name: "no_build", value: noBuild), RubyCommand.Argument(name: "no_skip_current", value: noSkipCurrent), RubyCommand.Argument(name: "derived_data", value: derivedData), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "cache_builds", value: cacheBuilds), RubyCommand.Argument(name: "frameworks", value: frameworks), RubyCommand.Argument(name: "output", value: output), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "toolchain", value: toolchain), RubyCommand.Argument(name: "project_directory", value: projectDirectory), RubyCommand.Argument(name: "new_resolver", value: newResolver)]) _ = runner.executeCommand(command) } func cert(development: Bool = false, force: Bool = false, username: String, teamId: String? = nil, teamName: String? = nil, outputPath: String = ".", keychainPath: String, keychainPassword: String? = nil, platform: String = "ios") { let command = RubyCommand(commandID: "", methodName: "cert", className: nil, args: [RubyCommand.Argument(name: "development", value: development), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "keychain_path", value: keychainPath), RubyCommand.Argument(name: "keychain_password", value: keychainPassword), RubyCommand.Argument(name: "platform", value: platform)]) _ = runner.executeCommand(command) } @discardableResult func changelogFromGitCommits(between: String? = nil, commitsCount: Int? = nil, pretty: String = "%B", dateFormat: String? = nil, ancestryPath: Bool = false, tagMatchPattern: String? = nil, matchLightweightTag: Bool = true, includeMerges: Bool? = nil, mergeCommitFiltering: String = "include_merges") -> String { let command = RubyCommand(commandID: "", methodName: "changelog_from_git_commits", className: nil, args: [RubyCommand.Argument(name: "between", value: between), RubyCommand.Argument(name: "commits_count", value: commitsCount), RubyCommand.Argument(name: "pretty", value: pretty), RubyCommand.Argument(name: "date_format", value: dateFormat), RubyCommand.Argument(name: "ancestry_path", value: ancestryPath), RubyCommand.Argument(name: "tag_match_pattern", value: tagMatchPattern), RubyCommand.Argument(name: "match_lightweight_tag", value: matchLightweightTag), RubyCommand.Argument(name: "include_merges", value: includeMerges), RubyCommand.Argument(name: "merge_commit_filtering", value: mergeCommitFiltering)]) return runner.executeCommand(command) } func chatwork(apiToken: String, message: String, roomid: String, success: Bool = true) { let command = RubyCommand(commandID: "", methodName: "chatwork", className: nil, args: [RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "roomid", value: roomid), RubyCommand.Argument(name: "success", value: success)]) _ = runner.executeCommand(command) } func checkAppStoreMetadata(appIdentifier: String, username: String, teamId: String? = nil, teamName: String? = nil, defaultRuleLevel: String = "error", includeInAppPurchases: Bool = true, negativeAppleSentiment: String? = nil, placeholderText: String? = nil, otherPlatforms: String? = nil, futureFunctionality: String? = nil, testWords: String? = nil, curseWords: String? = nil, freeStuffInIap: String? = nil, customText: String? = nil, copyrightDate: String? = nil, unreachableUrls: String? = nil) { let command = RubyCommand(commandID: "", methodName: "check_app_store_metadata", className: nil, args: [RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "default_rule_level", value: defaultRuleLevel), RubyCommand.Argument(name: "include_in_app_purchases", value: includeInAppPurchases), RubyCommand.Argument(name: "negative_apple_sentiment", value: negativeAppleSentiment), RubyCommand.Argument(name: "placeholder_text", value: placeholderText), RubyCommand.Argument(name: "other_platforms", value: otherPlatforms), RubyCommand.Argument(name: "future_functionality", value: futureFunctionality), RubyCommand.Argument(name: "test_words", value: testWords), RubyCommand.Argument(name: "curse_words", value: curseWords), RubyCommand.Argument(name: "free_stuff_in_iap", value: freeStuffInIap), RubyCommand.Argument(name: "custom_text", value: customText), RubyCommand.Argument(name: "copyright_date", value: copyrightDate), RubyCommand.Argument(name: "unreachable_urls", value: unreachableUrls)]) _ = runner.executeCommand(command) } func cleanBuildArtifacts(excludePattern: String? = nil) { let command = RubyCommand(commandID: "", methodName: "clean_build_artifacts", className: nil, args: [RubyCommand.Argument(name: "exclude_pattern", value: excludePattern)]) _ = runner.executeCommand(command) } func cleanCocoapodsCache(name: String? = nil) { let command = RubyCommand(commandID: "", methodName: "clean_cocoapods_cache", className: nil, args: [RubyCommand.Argument(name: "name", value: name)]) _ = runner.executeCommand(command) } func clearDerivedData(derivedDataPath: String = "~/Library/Developer/Xcode/DerivedData") { let command = RubyCommand(commandID: "", methodName: "clear_derived_data", className: nil, args: [RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath)]) _ = runner.executeCommand(command) } func clipboard(value: String) { let command = RubyCommand(commandID: "", methodName: "clipboard", className: nil, args: [RubyCommand.Argument(name: "value", value: value)]) _ = runner.executeCommand(command) } func cloc(binaryPath: String = "/usr/local/bin/cloc", excludeDir: String? = nil, outputDirectory: String = "build", sourceDirectory: String = "", xml: Bool = true) { let command = RubyCommand(commandID: "", methodName: "cloc", className: nil, args: [RubyCommand.Argument(name: "binary_path", value: binaryPath), RubyCommand.Argument(name: "exclude_dir", value: excludeDir), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "source_directory", value: sourceDirectory), RubyCommand.Argument(name: "xml", value: xml)]) _ = runner.executeCommand(command) } func clubmate() { let command = RubyCommand(commandID: "", methodName: "clubmate", className: nil, args: []) _ = runner.executeCommand(command) } func cocoapods(clean: Bool = true, integrate: Bool = true, repoUpdate: Bool = false, silent: Bool = false, verbose: Bool = false, ansi: Bool = true, useBundleExec: Bool = true, podfile: String? = nil, errorCallback: String? = nil, tryRepoUpdateOnError: Bool? = nil) { let command = RubyCommand(commandID: "", methodName: "cocoapods", className: nil, args: [RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "integrate", value: integrate), RubyCommand.Argument(name: "repo_update", value: repoUpdate), RubyCommand.Argument(name: "silent", value: silent), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "ansi", value: ansi), RubyCommand.Argument(name: "use_bundle_exec", value: useBundleExec), RubyCommand.Argument(name: "podfile", value: podfile), RubyCommand.Argument(name: "error_callback", value: errorCallback), RubyCommand.Argument(name: "try_repo_update_on_error", value: tryRepoUpdateOnError)]) _ = runner.executeCommand(command) } @discardableResult func commitGithubFile(repositoryName: String, serverUrl: String = "https://api.github.com", apiToken: String, branch: String = "master", path: String, message: String? = nil, secure: Bool = true) -> [String : String] { let command = RubyCommand(commandID: "", methodName: "commit_github_file", className: nil, args: [RubyCommand.Argument(name: "repository_name", value: repositoryName), RubyCommand.Argument(name: "server_url", value: serverUrl), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "branch", value: branch), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "secure", value: secure)]) return parseDictionary(fromString: runner.executeCommand(command)) } func commitVersionBump(message: String? = nil, xcodeproj: String? = nil, force: Bool = false, settings: Bool = false, ignore: String? = nil, include: [String] = []) { let command = RubyCommand(commandID: "", methodName: "commit_version_bump", className: nil, args: [RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "settings", value: settings), RubyCommand.Argument(name: "ignore", value: ignore), RubyCommand.Argument(name: "include", value: include)]) _ = runner.executeCommand(command) } func copyArtifacts(keepOriginal: Bool = true, targetPath: String = "artifacts", artifacts: [String] = [], failOnMissing: Bool = false) { let command = RubyCommand(commandID: "", methodName: "copy_artifacts", className: nil, args: [RubyCommand.Argument(name: "keep_original", value: keepOriginal), RubyCommand.Argument(name: "target_path", value: targetPath), RubyCommand.Argument(name: "artifacts", value: artifacts), RubyCommand.Argument(name: "fail_on_missing", value: failOnMissing)]) _ = runner.executeCommand(command) } func crashlytics(ipaPath: String? = nil, apkPath: String? = nil, crashlyticsPath: String? = nil, apiToken: String, buildSecret: String, notesPath: String? = nil, notes: String? = nil, groups: String? = nil, emails: String? = nil, notifications: Bool = true, debug: Bool = false) { let command = RubyCommand(commandID: "", methodName: "crashlytics", className: nil, args: [RubyCommand.Argument(name: "ipa_path", value: ipaPath), RubyCommand.Argument(name: "apk_path", value: apkPath), RubyCommand.Argument(name: "crashlytics_path", value: crashlyticsPath), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "build_secret", value: buildSecret), RubyCommand.Argument(name: "notes_path", value: notesPath), RubyCommand.Argument(name: "notes", value: notes), RubyCommand.Argument(name: "groups", value: groups), RubyCommand.Argument(name: "emails", value: emails), RubyCommand.Argument(name: "notifications", value: notifications), RubyCommand.Argument(name: "debug", value: debug)]) _ = runner.executeCommand(command) } func createAppOnline(username: String, appIdentifier: String, bundleIdentifierSuffix: String? = nil, appName: String, appVersion: String? = nil, sku: String, platform: String = "ios", language: String = "English", companyName: String? = nil, skipItc: Bool = false, itcUsers: [String]? = nil, enabledFeatures: String = "{}", enableServices: String = "{}", skipDevcenter: Bool = false, teamId: String? = nil, teamName: String? = nil, itcTeamId: String? = nil, itcTeamName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "create_app_online", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "bundle_identifier_suffix", value: bundleIdentifierSuffix), RubyCommand.Argument(name: "app_name", value: appName), RubyCommand.Argument(name: "app_version", value: appVersion), RubyCommand.Argument(name: "sku", value: sku), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "language", value: language), RubyCommand.Argument(name: "company_name", value: companyName), RubyCommand.Argument(name: "skip_itc", value: skipItc), RubyCommand.Argument(name: "itc_users", value: itcUsers), RubyCommand.Argument(name: "enabled_features", value: enabledFeatures), RubyCommand.Argument(name: "enable_services", value: enableServices), RubyCommand.Argument(name: "skip_devcenter", value: skipDevcenter), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "itc_team_id", value: itcTeamId), RubyCommand.Argument(name: "itc_team_name", value: itcTeamName)]) _ = runner.executeCommand(command) } func createKeychain(name: String? = nil, path: String? = nil, password: String, defaultKeychain: Bool = false, unlock: Bool = false, timeout: String = "300", lockWhenSleeps: Bool = false, lockAfterTimeout: Bool = false, addToSearchList: Bool = true) { let command = RubyCommand(commandID: "", methodName: "create_keychain", className: nil, args: [RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "default_keychain", value: defaultKeychain), RubyCommand.Argument(name: "unlock", value: unlock), RubyCommand.Argument(name: "timeout", value: timeout), RubyCommand.Argument(name: "lock_when_sleeps", value: lockWhenSleeps), RubyCommand.Argument(name: "lock_after_timeout", value: lockAfterTimeout), RubyCommand.Argument(name: "add_to_search_list", value: addToSearchList)]) _ = runner.executeCommand(command) } func createPullRequest(apiToken: String, repo: String, title: String, body: String? = nil, head: String? = nil, base: String = "master", apiUrl: String = "https://api.github.com") { let command = RubyCommand(commandID: "", methodName: "create_pull_request", className: nil, args: [RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "repo", value: repo), RubyCommand.Argument(name: "title", value: title), RubyCommand.Argument(name: "body", value: body), RubyCommand.Argument(name: "head", value: head), RubyCommand.Argument(name: "base", value: base), RubyCommand.Argument(name: "api_url", value: apiUrl)]) _ = runner.executeCommand(command) } func danger(useBundleExec: Bool = true, verbose: Bool = false, dangerId: String? = nil, dangerfile: String? = nil, githubApiToken: String? = nil, failOnErrors: Bool = false, newComment: Bool = false, base: String? = nil, head: String? = nil, pr: String? = nil) { let command = RubyCommand(commandID: "", methodName: "danger", className: nil, args: [RubyCommand.Argument(name: "use_bundle_exec", value: useBundleExec), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "danger_id", value: dangerId), RubyCommand.Argument(name: "dangerfile", value: dangerfile), RubyCommand.Argument(name: "github_api_token", value: githubApiToken), RubyCommand.Argument(name: "fail_on_errors", value: failOnErrors), RubyCommand.Argument(name: "new_comment", value: newComment), RubyCommand.Argument(name: "base", value: base), RubyCommand.Argument(name: "head", value: head), RubyCommand.Argument(name: "pr", value: pr)]) _ = runner.executeCommand(command) } func deleteKeychain(name: String? = nil, keychainPath: String? = nil) { let command = RubyCommand(commandID: "", methodName: "delete_keychain", className: nil, args: [RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "keychain_path", value: keychainPath)]) _ = runner.executeCommand(command) } func deliver(username: String = deliverfile.username, appIdentifier: String? = deliverfile.appIdentifier, app: String = deliverfile.app, editLive: Bool = deliverfile.editLive, ipa: String? = deliverfile.ipa, pkg: String? = deliverfile.pkg, platform: String = deliverfile.platform, metadataPath: String? = deliverfile.metadataPath, screenshotsPath: String? = deliverfile.screenshotsPath, skipBinaryUpload: Bool = deliverfile.skipBinaryUpload, useLiveVersion: Bool = deliverfile.useLiveVersion, skipScreenshots: Bool = deliverfile.skipScreenshots, appVersion: String? = deliverfile.appVersion, skipMetadata: Bool = deliverfile.skipMetadata, skipAppVersionUpdate: Bool = deliverfile.skipAppVersionUpdate, force: Bool = deliverfile.force, submitForReview: Bool = deliverfile.submitForReview, automaticRelease: Bool = deliverfile.automaticRelease, autoReleaseDate: String? = deliverfile.autoReleaseDate, phasedRelease: Bool = deliverfile.phasedRelease, priceTier: String? = deliverfile.priceTier, buildNumber: String? = deliverfile.buildNumber, appRatingConfigPath: String? = deliverfile.appRatingConfigPath, submissionInformation: String? = deliverfile.submissionInformation, teamId: String? = deliverfile.teamId, teamName: String? = deliverfile.teamName, devPortalTeamId: String? = deliverfile.devPortalTeamId, devPortalTeamName: String? = deliverfile.devPortalTeamName, itcProvider: String? = deliverfile.itcProvider, overwriteScreenshots: Bool = deliverfile.overwriteScreenshots, runPrecheckBeforeSubmit: Bool = deliverfile.runPrecheckBeforeSubmit, precheckDefaultRuleLevel: String = deliverfile.precheckDefaultRuleLevel, appIcon: String? = deliverfile.appIcon, appleWatchAppIcon: String? = deliverfile.appleWatchAppIcon, copyright: String? = deliverfile.copyright, primaryCategory: String? = deliverfile.primaryCategory, secondaryCategory: String? = deliverfile.secondaryCategory, primaryFirstSubCategory: String? = deliverfile.primaryFirstSubCategory, primarySecondSubCategory: String? = deliverfile.primarySecondSubCategory, secondaryFirstSubCategory: String? = deliverfile.secondaryFirstSubCategory, secondarySecondSubCategory: String? = deliverfile.secondarySecondSubCategory, tradeRepresentativeContactInformation: [String : Any]? = deliverfile.tradeRepresentativeContactInformation, appReviewInformation: [String : Any]? = deliverfile.appReviewInformation, description: String? = deliverfile.description, name: String? = deliverfile.name, subtitle: [String : Any]? = deliverfile.subtitle, keywords: [String : Any]? = deliverfile.keywords, promotionalText: [String : Any]? = deliverfile.promotionalText, releaseNotes: String? = deliverfile.releaseNotes, privacyUrl: String? = deliverfile.privacyUrl, supportUrl: String? = deliverfile.supportUrl, marketingUrl: String? = deliverfile.marketingUrl, languages: [String]? = deliverfile.languages, ignoreLanguageDirectoryValidation: Bool = deliverfile.ignoreLanguageDirectoryValidation, precheckIncludeInAppPurchases: Bool = deliverfile.precheckIncludeInAppPurchases) { let command = RubyCommand(commandID: "", methodName: "deliver", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "app", value: app), RubyCommand.Argument(name: "edit_live", value: editLive), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "pkg", value: pkg), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "metadata_path", value: metadataPath), RubyCommand.Argument(name: "screenshots_path", value: screenshotsPath), RubyCommand.Argument(name: "skip_binary_upload", value: skipBinaryUpload), RubyCommand.Argument(name: "use_live_version", value: useLiveVersion), RubyCommand.Argument(name: "skip_screenshots", value: skipScreenshots), RubyCommand.Argument(name: "app_version", value: appVersion), RubyCommand.Argument(name: "skip_metadata", value: skipMetadata), RubyCommand.Argument(name: "skip_app_version_update", value: skipAppVersionUpdate), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "submit_for_review", value: submitForReview), RubyCommand.Argument(name: "automatic_release", value: automaticRelease), RubyCommand.Argument(name: "auto_release_date", value: autoReleaseDate), RubyCommand.Argument(name: "phased_release", value: phasedRelease), RubyCommand.Argument(name: "price_tier", value: priceTier), RubyCommand.Argument(name: "build_number", value: buildNumber), RubyCommand.Argument(name: "app_rating_config_path", value: appRatingConfigPath), RubyCommand.Argument(name: "submission_information", value: submissionInformation), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "dev_portal_team_id", value: devPortalTeamId), RubyCommand.Argument(name: "dev_portal_team_name", value: devPortalTeamName), RubyCommand.Argument(name: "itc_provider", value: itcProvider), RubyCommand.Argument(name: "overwrite_screenshots", value: overwriteScreenshots), RubyCommand.Argument(name: "run_precheck_before_submit", value: runPrecheckBeforeSubmit), RubyCommand.Argument(name: "precheck_default_rule_level", value: precheckDefaultRuleLevel), RubyCommand.Argument(name: "app_icon", value: appIcon), RubyCommand.Argument(name: "apple_watch_app_icon", value: appleWatchAppIcon), RubyCommand.Argument(name: "copyright", value: copyright), RubyCommand.Argument(name: "primary_category", value: primaryCategory), RubyCommand.Argument(name: "secondary_category", value: secondaryCategory), RubyCommand.Argument(name: "primary_first_sub_category", value: primaryFirstSubCategory), RubyCommand.Argument(name: "primary_second_sub_category", value: primarySecondSubCategory), RubyCommand.Argument(name: "secondary_first_sub_category", value: secondaryFirstSubCategory), RubyCommand.Argument(name: "secondary_second_sub_category", value: secondarySecondSubCategory), RubyCommand.Argument(name: "trade_representative_contact_information", value: tradeRepresentativeContactInformation), RubyCommand.Argument(name: "app_review_information", value: appReviewInformation), RubyCommand.Argument(name: "description", value: description), RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "subtitle", value: subtitle), RubyCommand.Argument(name: "keywords", value: keywords), RubyCommand.Argument(name: "promotional_text", value: promotionalText), RubyCommand.Argument(name: "release_notes", value: releaseNotes), RubyCommand.Argument(name: "privacy_url", value: privacyUrl), RubyCommand.Argument(name: "support_url", value: supportUrl), RubyCommand.Argument(name: "marketing_url", value: marketingUrl), RubyCommand.Argument(name: "languages", value: languages), RubyCommand.Argument(name: "ignore_language_directory_validation", value: ignoreLanguageDirectoryValidation), RubyCommand.Argument(name: "precheck_include_in_app_purchases", value: precheckIncludeInAppPurchases)]) _ = runner.executeCommand(command) } func deploygate(apiToken: String, user: String, ipa: String? = nil, apk: String? = nil, message: String = "No changelog provided", distributionKey: String? = nil, releaseNote: String? = nil, disableNotify: Bool = false) { let command = RubyCommand(commandID: "", methodName: "deploygate", className: nil, args: [RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "user", value: user), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "apk", value: apk), RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "distribution_key", value: distributionKey), RubyCommand.Argument(name: "release_note", value: releaseNote), RubyCommand.Argument(name: "disable_notify", value: disableNotify)]) _ = runner.executeCommand(command) } func dotgpgEnvironment(dotgpgFile: String) { let command = RubyCommand(commandID: "", methodName: "dotgpg_environment", className: nil, args: [RubyCommand.Argument(name: "dotgpg_file", value: dotgpgFile)]) _ = runner.executeCommand(command) } func download(url: String) { let command = RubyCommand(commandID: "", methodName: "download", className: nil, args: [RubyCommand.Argument(name: "url", value: url)]) _ = runner.executeCommand(command) } func downloadDsyms(username: String, appIdentifier: String, teamId: String? = nil, teamName: String? = nil, platform: String = "ios", version: String? = nil, buildNumber: String? = nil, outputDirectory: String? = nil) { let command = RubyCommand(commandID: "", methodName: "download_dsyms", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "build_number", value: buildNumber), RubyCommand.Argument(name: "output_directory", value: outputDirectory)]) _ = runner.executeCommand(command) } func dsymZip(archivePath: String? = nil, dsymPath: String? = nil, all: Bool = false) { let command = RubyCommand(commandID: "", methodName: "dsym_zip", className: nil, args: [RubyCommand.Argument(name: "archive_path", value: archivePath), RubyCommand.Argument(name: "dsym_path", value: dsymPath), RubyCommand.Argument(name: "all", value: all)]) _ = runner.executeCommand(command) } func ensureGitBranch(branch: String = "master") { let command = RubyCommand(commandID: "", methodName: "ensure_git_branch", className: nil, args: [RubyCommand.Argument(name: "branch", value: branch)]) _ = runner.executeCommand(command) } func ensureGitStatusClean(showUncommittedChanges: Bool = false) { let command = RubyCommand(commandID: "", methodName: "ensure_git_status_clean", className: nil, args: [RubyCommand.Argument(name: "show_uncommitted_changes", value: showUncommittedChanges)]) _ = runner.executeCommand(command) } func ensureNoDebugCode(text: String, path: String = ".", `extension`: String? = nil, extensions: String? = nil, exclude: String? = nil, excludeDirs: [String]? = nil) { let command = RubyCommand(commandID: "", methodName: "ensure_no_debug_code", className: nil, args: [RubyCommand.Argument(name: "text", value: text), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "extension", value: `extension`), RubyCommand.Argument(name: "extensions", value: extensions), RubyCommand.Argument(name: "exclude", value: exclude), RubyCommand.Argument(name: "exclude_dirs", value: excludeDirs)]) _ = runner.executeCommand(command) } func ensureXcodeVersion(version: String) { let command = RubyCommand(commandID: "", methodName: "ensure_xcode_version", className: nil, args: [RubyCommand.Argument(name: "version", value: version)]) _ = runner.executeCommand(command) } @discardableResult func environmentVariable(`set`: [String : Any]? = nil, `get`: String? = nil, remove: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "environment_variable", className: nil, args: [RubyCommand.Argument(name: "set", value: `set`), RubyCommand.Argument(name: "get", value: `get`), RubyCommand.Argument(name: "remove", value: remove)]) return runner.executeCommand(command) } func erb(template: String, destination: String? = nil, placeholders: [String : Any] = [:]) { let command = RubyCommand(commandID: "", methodName: "erb", className: nil, args: [RubyCommand.Argument(name: "template", value: template), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "placeholders", value: placeholders)]) _ = runner.executeCommand(command) } func flock(message: String, token: String, baseUrl: String = "https://api.flock.co/hooks/sendMessage") { let command = RubyCommand(commandID: "", methodName: "flock", className: nil, args: [RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "token", value: token), RubyCommand.Argument(name: "base_url", value: baseUrl)]) _ = runner.executeCommand(command) } func frameScreenshots(white: String? = nil, silver: String? = nil, roseGold: String? = nil, gold: String? = nil, forceDeviceType: String? = nil, useLegacyIphone5s: Bool = false, useLegacyIphone6s: Bool = false, forceOrientationBlock: String? = nil, path: String = "./") { let command = RubyCommand(commandID: "", methodName: "frame_screenshots", className: nil, args: [RubyCommand.Argument(name: "white", value: white), RubyCommand.Argument(name: "silver", value: silver), RubyCommand.Argument(name: "rose_gold", value: roseGold), RubyCommand.Argument(name: "gold", value: gold), RubyCommand.Argument(name: "force_device_type", value: forceDeviceType), RubyCommand.Argument(name: "use_legacy_iphone5s", value: useLegacyIphone5s), RubyCommand.Argument(name: "use_legacy_iphone6s", value: useLegacyIphone6s), RubyCommand.Argument(name: "force_orientation_block", value: forceOrientationBlock), RubyCommand.Argument(name: "path", value: path)]) _ = runner.executeCommand(command) } func frameit(white: String? = nil, silver: String? = nil, roseGold: String? = nil, gold: String? = nil, forceDeviceType: String? = nil, useLegacyIphone5s: Bool = false, useLegacyIphone6s: Bool = false, forceOrientationBlock: String? = nil, path: String = "./") { let command = RubyCommand(commandID: "", methodName: "frameit", className: nil, args: [RubyCommand.Argument(name: "white", value: white), RubyCommand.Argument(name: "silver", value: silver), RubyCommand.Argument(name: "rose_gold", value: roseGold), RubyCommand.Argument(name: "gold", value: gold), RubyCommand.Argument(name: "force_device_type", value: forceDeviceType), RubyCommand.Argument(name: "use_legacy_iphone5s", value: useLegacyIphone5s), RubyCommand.Argument(name: "use_legacy_iphone6s", value: useLegacyIphone6s), RubyCommand.Argument(name: "force_orientation_block", value: forceOrientationBlock), RubyCommand.Argument(name: "path", value: path)]) _ = runner.executeCommand(command) } func gcovr() { let command = RubyCommand(commandID: "", methodName: "gcovr", className: nil, args: []) _ = runner.executeCommand(command) } @discardableResult func getBuildNumber(xcodeproj: String? = nil, hideErrorWhenVersioningDisabled: Bool = false) -> String { let command = RubyCommand(commandID: "", methodName: "get_build_number", className: nil, args: [RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "hide_error_when_versioning_disabled", value: hideErrorWhenVersioningDisabled)]) return runner.executeCommand(command) } func getBuildNumberRepository(useHgRevisionNumber: Bool = false) { let command = RubyCommand(commandID: "", methodName: "get_build_number_repository", className: nil, args: [RubyCommand.Argument(name: "use_hg_revision_number", value: useHgRevisionNumber)]) _ = runner.executeCommand(command) } func getCertificates(development: Bool = false, force: Bool = false, username: String, teamId: String? = nil, teamName: String? = nil, outputPath: String = ".", keychainPath: String, keychainPassword: String? = nil, platform: String = "ios") { let command = RubyCommand(commandID: "", methodName: "get_certificates", className: nil, args: [RubyCommand.Argument(name: "development", value: development), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "keychain_path", value: keychainPath), RubyCommand.Argument(name: "keychain_password", value: keychainPassword), RubyCommand.Argument(name: "platform", value: platform)]) _ = runner.executeCommand(command) } func getGithubRelease(url: String, serverUrl: String = "https://api.github.com", version: String, apiToken: String? = nil) { let command = RubyCommand(commandID: "", methodName: "get_github_release", className: nil, args: [RubyCommand.Argument(name: "url", value: url), RubyCommand.Argument(name: "server_url", value: serverUrl), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "api_token", value: apiToken)]) _ = runner.executeCommand(command) } @discardableResult func getInfoPlistValue(key: String, path: String) -> String { let command = RubyCommand(commandID: "", methodName: "get_info_plist_value", className: nil, args: [RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "path", value: path)]) return runner.executeCommand(command) } @discardableResult func getIpaInfoPlistValue(key: String, ipa: String) -> String { let command = RubyCommand(commandID: "", methodName: "get_ipa_info_plist_value", className: nil, args: [RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "ipa", value: ipa)]) return runner.executeCommand(command) } func getProvisioningProfile(adhoc: Bool = false, development: Bool = false, skipInstall: Bool = false, force: Bool = false, appIdentifier: String, username: String, teamId: String? = nil, teamName: String? = nil, provisioningName: String? = nil, ignoreProfilesWithDifferentName: Bool = false, outputPath: String = ".", certId: String? = nil, certOwnerName: String? = nil, filename: String? = nil, skipFetchProfiles: Bool = false, skipCertificateVerification: Bool = false, platform: String = "ios", readonly: Bool = false, templateName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "get_provisioning_profile", className: nil, args: [RubyCommand.Argument(name: "adhoc", value: adhoc), RubyCommand.Argument(name: "development", value: development), RubyCommand.Argument(name: "skip_install", value: skipInstall), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "provisioning_name", value: provisioningName), RubyCommand.Argument(name: "ignore_profiles_with_different_name", value: ignoreProfilesWithDifferentName), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "cert_id", value: certId), RubyCommand.Argument(name: "cert_owner_name", value: certOwnerName), RubyCommand.Argument(name: "filename", value: filename), RubyCommand.Argument(name: "skip_fetch_profiles", value: skipFetchProfiles), RubyCommand.Argument(name: "skip_certificate_verification", value: skipCertificateVerification), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "readonly", value: readonly), RubyCommand.Argument(name: "template_name", value: templateName)]) _ = runner.executeCommand(command) } func getPushCertificate(development: Bool = false, generateP12: Bool = true, activeDaysLimit: String = "30", force: Bool = false, savePrivateKey: Bool = true, appIdentifier: String, username: String, teamId: String? = nil, teamName: String? = nil, p12Password: String, pemName: String? = nil, outputPath: String = ".", newProfile: String? = nil) { let command = RubyCommand(commandID: "", methodName: "get_push_certificate", className: nil, args: [RubyCommand.Argument(name: "development", value: development), RubyCommand.Argument(name: "generate_p12", value: generateP12), RubyCommand.Argument(name: "active_days_limit", value: activeDaysLimit), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "save_private_key", value: savePrivateKey), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "p12_password", value: p12Password), RubyCommand.Argument(name: "pem_name", value: pemName), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "new_profile", value: newProfile)]) _ = runner.executeCommand(command) } @discardableResult func getVersionNumber(xcodeproj: String? = nil, scheme: String? = nil, target: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "get_version_number", className: nil, args: [RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "target", value: target)]) return runner.executeCommand(command) } func gitAdd(path: String? = nil, pathspec: String? = nil) { let command = RubyCommand(commandID: "", methodName: "git_add", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "pathspec", value: pathspec)]) _ = runner.executeCommand(command) } @discardableResult func gitBranch() -> String { let command = RubyCommand(commandID: "", methodName: "git_branch", className: nil, args: []) return runner.executeCommand(command) } func gitCommit(path: String, message: String) { let command = RubyCommand(commandID: "", methodName: "git_commit", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "message", value: message)]) _ = runner.executeCommand(command) } func gitPull(onlyTags: Bool = false) { let command = RubyCommand(commandID: "", methodName: "git_pull", className: nil, args: [RubyCommand.Argument(name: "only_tags", value: onlyTags)]) _ = runner.executeCommand(command) } func gitTagExists(tag: String) { let command = RubyCommand(commandID: "", methodName: "git_tag_exists", className: nil, args: [RubyCommand.Argument(name: "tag", value: tag)]) _ = runner.executeCommand(command) } func githubApi(serverUrl: String = "https://api.github.com", apiToken: String, httpMethod: String = "GET", body: String = "{}", rawBody: String? = nil, path: String? = nil, url: String? = nil, errorHandlers: String = "{}", headers: String = "{}", secure: Bool = true) { let command = RubyCommand(commandID: "", methodName: "github_api", className: nil, args: [RubyCommand.Argument(name: "server_url", value: serverUrl), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "http_method", value: httpMethod), RubyCommand.Argument(name: "body", value: body), RubyCommand.Argument(name: "raw_body", value: rawBody), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "url", value: url), RubyCommand.Argument(name: "error_handlers", value: errorHandlers), RubyCommand.Argument(name: "headers", value: headers), RubyCommand.Argument(name: "secure", value: secure)]) _ = runner.executeCommand(command) } func googlePlayTrackVersionCodes(packageName: String, track: String = "production", key: String? = nil, issuer: String? = nil, jsonKey: String? = nil, jsonKeyData: String? = nil, rootUrl: String? = nil) { let command = RubyCommand(commandID: "", methodName: "google_play_track_version_codes", className: nil, args: [RubyCommand.Argument(name: "package_name", value: packageName), RubyCommand.Argument(name: "track", value: track), RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "issuer", value: issuer), RubyCommand.Argument(name: "json_key", value: jsonKey), RubyCommand.Argument(name: "json_key_data", value: jsonKeyData), RubyCommand.Argument(name: "root_url", value: rootUrl)]) _ = runner.executeCommand(command) } func gradle(task: String, flavor: String? = nil, buildType: String? = nil, flags: String? = nil, projectDir: String = ".", gradlePath: String? = nil, properties: String? = nil, systemProperties: String? = nil, serial: String = "", printCommand: Bool = true, printCommandOutput: Bool = true) { let command = RubyCommand(commandID: "", methodName: "gradle", className: nil, args: [RubyCommand.Argument(name: "task", value: task), RubyCommand.Argument(name: "flavor", value: flavor), RubyCommand.Argument(name: "build_type", value: buildType), RubyCommand.Argument(name: "flags", value: flags), RubyCommand.Argument(name: "project_dir", value: projectDir), RubyCommand.Argument(name: "gradle_path", value: gradlePath), RubyCommand.Argument(name: "properties", value: properties), RubyCommand.Argument(name: "system_properties", value: systemProperties), RubyCommand.Argument(name: "serial", value: serial), RubyCommand.Argument(name: "print_command", value: printCommand), RubyCommand.Argument(name: "print_command_output", value: printCommandOutput)]) _ = runner.executeCommand(command) } func gym(workspace: String? = gymfile.workspace, project: String? = gymfile.project, scheme: String? = gymfile.scheme, clean: Bool = gymfile.clean, outputDirectory: String = gymfile.outputDirectory, outputName: String? = gymfile.outputName, configuration: String? = gymfile.configuration, silent: Bool = gymfile.silent, codesigningIdentity: String? = gymfile.codesigningIdentity, skipPackageIpa: Bool = gymfile.skipPackageIpa, includeSymbols: Bool? = gymfile.includeSymbols, includeBitcode: Bool? = gymfile.includeBitcode, exportMethod: String? = gymfile.exportMethod, exportOptions: [String : Any]? = gymfile.exportOptions, exportXcargs: String? = gymfile.exportXcargs, skipBuildArchive: Bool? = gymfile.skipBuildArchive, skipArchive: Bool? = gymfile.skipArchive, buildPath: String? = gymfile.buildPath, archivePath: String? = gymfile.archivePath, derivedDataPath: String? = gymfile.derivedDataPath, resultBundle: String? = gymfile.resultBundle, buildlogPath: String = gymfile.buildlogPath, sdk: String? = gymfile.sdk, toolchain: String? = gymfile.toolchain, destination: String? = gymfile.destination, exportTeamId: String? = gymfile.exportTeamId, xcargs: String? = gymfile.xcargs, xcconfig: String? = gymfile.xcconfig, suppressXcodeOutput: String? = gymfile.suppressXcodeOutput, disableXcpretty: String? = gymfile.disableXcpretty, xcprettyTestFormat: String? = gymfile.xcprettyTestFormat, xcprettyFormatter: String? = gymfile.xcprettyFormatter, xcprettyReportJunit: String? = gymfile.xcprettyReportJunit, xcprettyReportHtml: String? = gymfile.xcprettyReportHtml, xcprettyReportJson: String? = gymfile.xcprettyReportJson, analyzeBuildTime: String? = gymfile.analyzeBuildTime, xcprettyUtf: String? = gymfile.xcprettyUtf, skipProfileDetection: Bool = gymfile.skipProfileDetection) { let command = RubyCommand(commandID: "", methodName: "gym", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_name", value: outputName), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "silent", value: silent), RubyCommand.Argument(name: "codesigning_identity", value: codesigningIdentity), RubyCommand.Argument(name: "skip_package_ipa", value: skipPackageIpa), RubyCommand.Argument(name: "include_symbols", value: includeSymbols), RubyCommand.Argument(name: "include_bitcode", value: includeBitcode), RubyCommand.Argument(name: "export_method", value: exportMethod), RubyCommand.Argument(name: "export_options", value: exportOptions), RubyCommand.Argument(name: "export_xcargs", value: exportXcargs), RubyCommand.Argument(name: "skip_build_archive", value: skipBuildArchive), RubyCommand.Argument(name: "skip_archive", value: skipArchive), RubyCommand.Argument(name: "build_path", value: buildPath), RubyCommand.Argument(name: "archive_path", value: archivePath), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "result_bundle", value: resultBundle), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "toolchain", value: toolchain), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "export_team_id", value: exportTeamId), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "xcconfig", value: xcconfig), RubyCommand.Argument(name: "suppress_xcode_output", value: suppressXcodeOutput), RubyCommand.Argument(name: "disable_xcpretty", value: disableXcpretty), RubyCommand.Argument(name: "xcpretty_test_format", value: xcprettyTestFormat), RubyCommand.Argument(name: "xcpretty_formatter", value: xcprettyFormatter), RubyCommand.Argument(name: "xcpretty_report_junit", value: xcprettyReportJunit), RubyCommand.Argument(name: "xcpretty_report_html", value: xcprettyReportHtml), RubyCommand.Argument(name: "xcpretty_report_json", value: xcprettyReportJson), RubyCommand.Argument(name: "analyze_build_time", value: analyzeBuildTime), RubyCommand.Argument(name: "xcpretty_utf", value: xcprettyUtf), RubyCommand.Argument(name: "skip_profile_detection", value: skipProfileDetection)]) _ = runner.executeCommand(command) } func hgAddTag(tag: String) { let command = RubyCommand(commandID: "", methodName: "hg_add_tag", className: nil, args: [RubyCommand.Argument(name: "tag", value: tag)]) _ = runner.executeCommand(command) } func hgCommitVersionBump(message: String = "Version Bump", xcodeproj: String? = nil, force: Bool = false, testDirtyFiles: String = "file1, file2", testExpectedFiles: String = "file1, file2") { let command = RubyCommand(commandID: "", methodName: "hg_commit_version_bump", className: nil, args: [RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "test_dirty_files", value: testDirtyFiles), RubyCommand.Argument(name: "test_expected_files", value: testExpectedFiles)]) _ = runner.executeCommand(command) } func hgPush(force: Bool = false, destination: String = "") { let command = RubyCommand(commandID: "", methodName: "hg_push", className: nil, args: [RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "destination", value: destination)]) _ = runner.executeCommand(command) } func hipchat(message: String = "", channel: String, apiToken: String, customColor: String? = nil, success: Bool = true, version: String, notifyRoom: Bool = false, apiHost: String = "api.hipchat.com", messageFormat: String = "html", includeHtmlHeader: Bool = true, from: String = "fastlane") { let command = RubyCommand(commandID: "", methodName: "hipchat", className: nil, args: [RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "channel", value: channel), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "custom_color", value: customColor), RubyCommand.Argument(name: "success", value: success), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "notify_room", value: notifyRoom), RubyCommand.Argument(name: "api_host", value: apiHost), RubyCommand.Argument(name: "message_format", value: messageFormat), RubyCommand.Argument(name: "include_html_header", value: includeHtmlHeader), RubyCommand.Argument(name: "from", value: from)]) _ = runner.executeCommand(command) } func hockey(apk: String? = nil, apiToken: String, ipa: String? = nil, dsym: String? = nil, createUpdate: Bool = false, notes: String = "No changelog given", notify: String = "1", status: String = "2", createStatus: String = "2", notesType: String = "1", releaseType: String = "0", mandatory: String = "0", teams: String? = nil, users: String? = nil, tags: String? = nil, bundleShortVersion: String? = nil, bundleVersion: String? = nil, publicIdentifier: String? = nil, commitSha: String? = nil, repositoryUrl: String? = nil, buildServerUrl: String? = nil, uploadDsymOnly: Bool = false, ownerId: String? = nil, strategy: String = "add", timeout: String? = nil, bypassCdn: Bool = false, dsaSignature: String = "") { let command = RubyCommand(commandID: "", methodName: "hockey", className: nil, args: [RubyCommand.Argument(name: "apk", value: apk), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "dsym", value: dsym), RubyCommand.Argument(name: "create_update", value: createUpdate), RubyCommand.Argument(name: "notes", value: notes), RubyCommand.Argument(name: "notify", value: notify), RubyCommand.Argument(name: "status", value: status), RubyCommand.Argument(name: "create_status", value: createStatus), RubyCommand.Argument(name: "notes_type", value: notesType), RubyCommand.Argument(name: "release_type", value: releaseType), RubyCommand.Argument(name: "mandatory", value: mandatory), RubyCommand.Argument(name: "teams", value: teams), RubyCommand.Argument(name: "users", value: users), RubyCommand.Argument(name: "tags", value: tags), RubyCommand.Argument(name: "bundle_short_version", value: bundleShortVersion), RubyCommand.Argument(name: "bundle_version", value: bundleVersion), RubyCommand.Argument(name: "public_identifier", value: publicIdentifier), RubyCommand.Argument(name: "commit_sha", value: commitSha), RubyCommand.Argument(name: "repository_url", value: repositoryUrl), RubyCommand.Argument(name: "build_server_url", value: buildServerUrl), RubyCommand.Argument(name: "upload_dsym_only", value: uploadDsymOnly), RubyCommand.Argument(name: "owner_id", value: ownerId), RubyCommand.Argument(name: "strategy", value: strategy), RubyCommand.Argument(name: "timeout", value: timeout), RubyCommand.Argument(name: "bypass_cdn", value: bypassCdn), RubyCommand.Argument(name: "dsa_signature", value: dsaSignature)]) _ = runner.executeCommand(command) } func ifttt(apiKey: String, eventName: String, value1: String? = nil, value2: String? = nil, value3: String? = nil) { let command = RubyCommand(commandID: "", methodName: "ifttt", className: nil, args: [RubyCommand.Argument(name: "api_key", value: apiKey), RubyCommand.Argument(name: "event_name", value: eventName), RubyCommand.Argument(name: "value1", value: value1), RubyCommand.Argument(name: "value2", value: value2), RubyCommand.Argument(name: "value3", value: value3)]) _ = runner.executeCommand(command) } func importCertificate(keychainName: String, keychainPath: String? = nil, keychainPassword: String? = nil, certificatePath: String, certificatePassword: String? = nil, logOutput: Bool = false) { let command = RubyCommand(commandID: "", methodName: "import_certificate", className: nil, args: [RubyCommand.Argument(name: "keychain_name", value: keychainName), RubyCommand.Argument(name: "keychain_path", value: keychainPath), RubyCommand.Argument(name: "keychain_password", value: keychainPassword), RubyCommand.Argument(name: "certificate_path", value: certificatePath), RubyCommand.Argument(name: "certificate_password", value: certificatePassword), RubyCommand.Argument(name: "log_output", value: logOutput)]) _ = runner.executeCommand(command) } @discardableResult func incrementBuildNumber(buildNumber: String? = nil, xcodeproj: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "increment_build_number", className: nil, args: [RubyCommand.Argument(name: "build_number", value: buildNumber), RubyCommand.Argument(name: "xcodeproj", value: xcodeproj)]) return runner.executeCommand(command) } @discardableResult func incrementVersionNumber(bumpType: String = "patch", versionNumber: String? = nil, xcodeproj: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "increment_version_number", className: nil, args: [RubyCommand.Argument(name: "bump_type", value: bumpType), RubyCommand.Argument(name: "version_number", value: versionNumber), RubyCommand.Argument(name: "xcodeproj", value: xcodeproj)]) return runner.executeCommand(command) } func installOnDevice(extra: String? = nil, deviceId: String? = nil, skipWifi: String? = nil, ipa: String? = nil) { let command = RubyCommand(commandID: "", methodName: "install_on_device", className: nil, args: [RubyCommand.Argument(name: "extra", value: extra), RubyCommand.Argument(name: "device_id", value: deviceId), RubyCommand.Argument(name: "skip_wifi", value: skipWifi), RubyCommand.Argument(name: "ipa", value: ipa)]) _ = runner.executeCommand(command) } func installXcodePlugin(url: String, github: String? = nil) { let command = RubyCommand(commandID: "", methodName: "install_xcode_plugin", className: nil, args: [RubyCommand.Argument(name: "url", value: url), RubyCommand.Argument(name: "github", value: github)]) _ = runner.executeCommand(command) } func installr(apiToken: String, ipa: String, notes: String? = nil, notify: String? = nil, add: String? = nil) { let command = RubyCommand(commandID: "", methodName: "installr", className: nil, args: [RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "notes", value: notes), RubyCommand.Argument(name: "notify", value: notify), RubyCommand.Argument(name: "add", value: add)]) _ = runner.executeCommand(command) } func ipa(workspace: String? = nil, project: String? = nil, configuration: String? = nil, scheme: String? = nil, clean: String? = nil, archive: String? = nil, destination: String? = nil, embed: String? = nil, identity: String? = nil, sdk: String? = nil, ipa: String? = nil, xcconfig: String? = nil, xcargs: String? = nil) { let command = RubyCommand(commandID: "", methodName: "ipa", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "archive", value: archive), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "embed", value: embed), RubyCommand.Argument(name: "identity", value: identity), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "xcconfig", value: xcconfig), RubyCommand.Argument(name: "xcargs", value: xcargs)]) _ = runner.executeCommand(command) } @discardableResult func isCi() -> Bool { let command = RubyCommand(commandID: "", methodName: "is_ci", className: nil, args: []) return parseBool(fromString: runner.executeCommand(command)) } func jazzy(config: String? = nil) { let command = RubyCommand(commandID: "", methodName: "jazzy", className: nil, args: [RubyCommand.Argument(name: "config", value: config)]) _ = runner.executeCommand(command) } func jira(url: String, username: String, password: String, ticketId: String, commentText: String) { let command = RubyCommand(commandID: "", methodName: "jira", className: nil, args: [RubyCommand.Argument(name: "url", value: url), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "ticket_id", value: ticketId), RubyCommand.Argument(name: "comment_text", value: commentText)]) _ = runner.executeCommand(command) } func laneContext() { let command = RubyCommand(commandID: "", methodName: "lane_context", className: nil, args: []) _ = runner.executeCommand(command) } @discardableResult func lastGitTag() -> String { let command = RubyCommand(commandID: "", methodName: "last_git_tag", className: nil, args: []) return runner.executeCommand(command) } @discardableResult func latestTestflightBuildNumber(live: Bool = false, appIdentifier: String, username: String, version: String? = nil, platform: String = "ios", initialBuildNumber: String = "1", teamId: String? = nil, teamName: String? = nil) -> Int { let command = RubyCommand(commandID: "", methodName: "latest_testflight_build_number", className: nil, args: [RubyCommand.Argument(name: "live", value: live), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "initial_build_number", value: initialBuildNumber), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName)]) return parseInt(fromString: runner.executeCommand(command)) } func lcov(projectName: String, scheme: String, arch: String = "i386", outputDir: String = "coverage_reports") { let command = RubyCommand(commandID: "", methodName: "lcov", className: nil, args: [RubyCommand.Argument(name: "project_name", value: projectName), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "arch", value: arch), RubyCommand.Argument(name: "output_dir", value: outputDir)]) _ = runner.executeCommand(command) } func mailgun(mailgunSandboxDomain: String? = nil, mailgunSandboxPostmaster: String? = nil, mailgunApikey: String? = nil, postmaster: String, apikey: String, to: String, from: String = "Mailgun Sandbox", message: String, subject: String = "fastlane build", success: Bool = true, appLink: String, ciBuildLink: String? = nil, templatePath: String? = nil, replyTo: String? = nil, attachment: String? = nil) { let command = RubyCommand(commandID: "", methodName: "mailgun", className: nil, args: [RubyCommand.Argument(name: "mailgun_sandbox_domain", value: mailgunSandboxDomain), RubyCommand.Argument(name: "mailgun_sandbox_postmaster", value: mailgunSandboxPostmaster), RubyCommand.Argument(name: "mailgun_apikey", value: mailgunApikey), RubyCommand.Argument(name: "postmaster", value: postmaster), RubyCommand.Argument(name: "apikey", value: apikey), RubyCommand.Argument(name: "to", value: to), RubyCommand.Argument(name: "from", value: from), RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "subject", value: subject), RubyCommand.Argument(name: "success", value: success), RubyCommand.Argument(name: "app_link", value: appLink), RubyCommand.Argument(name: "ci_build_link", value: ciBuildLink), RubyCommand.Argument(name: "template_path", value: templatePath), RubyCommand.Argument(name: "reply_to", value: replyTo), RubyCommand.Argument(name: "attachment", value: attachment)]) _ = runner.executeCommand(command) } func makeChangelogFromJenkins(fallbackChangelog: String = "", includeCommitBody: Bool = true) { let command = RubyCommand(commandID: "", methodName: "make_changelog_from_jenkins", className: nil, args: [RubyCommand.Argument(name: "fallback_changelog", value: fallbackChangelog), RubyCommand.Argument(name: "include_commit_body", value: includeCommitBody)]) _ = runner.executeCommand(command) } func match(gitUrl: String = matchfile.gitUrl, gitBranch: String = matchfile.gitBranch, type: String = matchfile.type, appIdentifier: [String] = matchfile.appIdentifier, username: String = matchfile.username, keychainName: String = matchfile.keychainName, keychainPassword: String? = matchfile.keychainPassword, readonly: Bool = matchfile.readonly, teamId: String? = matchfile.teamId, gitFullName: String? = matchfile.gitFullName, gitUserEmail: String? = matchfile.gitUserEmail, teamName: String? = matchfile.teamName, verbose: Bool = matchfile.verbose, force: Bool = matchfile.force, skipConfirmation: Bool = matchfile.skipConfirmation, shallowClone: Bool = matchfile.shallowClone, cloneBranchDirectly: Bool = matchfile.cloneBranchDirectly, workspace: String? = matchfile.workspace, forceForNewDevices: Bool = matchfile.forceForNewDevices, skipDocs: Bool = matchfile.skipDocs, platform: String = matchfile.platform, templateName: String? = matchfile.templateName) { let command = RubyCommand(commandID: "", methodName: "match", className: nil, args: [RubyCommand.Argument(name: "git_url", value: gitUrl), RubyCommand.Argument(name: "git_branch", value: gitBranch), RubyCommand.Argument(name: "type", value: type), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "keychain_name", value: keychainName), RubyCommand.Argument(name: "keychain_password", value: keychainPassword), RubyCommand.Argument(name: "readonly", value: readonly), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "git_full_name", value: gitFullName), RubyCommand.Argument(name: "git_user_email", value: gitUserEmail), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "skip_confirmation", value: skipConfirmation), RubyCommand.Argument(name: "shallow_clone", value: shallowClone), RubyCommand.Argument(name: "clone_branch_directly", value: cloneBranchDirectly), RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "force_for_new_devices", value: forceForNewDevices), RubyCommand.Argument(name: "skip_docs", value: skipDocs), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "template_name", value: templateName)]) _ = runner.executeCommand(command) } func modifyServices(username: String, appIdentifier: String, services: [String : Any] = [:], teamId: String? = nil, teamName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "modify_services", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "services", value: services), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName)]) _ = runner.executeCommand(command) } func nexusUpload(file: String, repoId: String, repoGroupId: String, repoProjectName: String, repoProjectVersion: String, repoClassifier: String? = nil, endpoint: String, mountPath: String = "/nexus", username: String, password: String, sslVerify: Bool = true, verbose: Bool = false, proxyUsername: String? = nil, proxyPassword: String? = nil, proxyAddress: String? = nil, proxyPort: String? = nil) { let command = RubyCommand(commandID: "", methodName: "nexus_upload", className: nil, args: [RubyCommand.Argument(name: "file", value: file), RubyCommand.Argument(name: "repo_id", value: repoId), RubyCommand.Argument(name: "repo_group_id", value: repoGroupId), RubyCommand.Argument(name: "repo_project_name", value: repoProjectName), RubyCommand.Argument(name: "repo_project_version", value: repoProjectVersion), RubyCommand.Argument(name: "repo_classifier", value: repoClassifier), RubyCommand.Argument(name: "endpoint", value: endpoint), RubyCommand.Argument(name: "mount_path", value: mountPath), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "ssl_verify", value: sslVerify), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "proxy_username", value: proxyUsername), RubyCommand.Argument(name: "proxy_password", value: proxyPassword), RubyCommand.Argument(name: "proxy_address", value: proxyAddress), RubyCommand.Argument(name: "proxy_port", value: proxyPort)]) _ = runner.executeCommand(command) } func notification(title: String = "fastlane", subtitle: String? = nil, message: String, sound: String? = nil, activate: String? = nil, appIcon: String? = nil, contentImage: String? = nil, open: String? = nil, execute: String? = nil) { let command = RubyCommand(commandID: "", methodName: "notification", className: nil, args: [RubyCommand.Argument(name: "title", value: title), RubyCommand.Argument(name: "subtitle", value: subtitle), RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "sound", value: sound), RubyCommand.Argument(name: "activate", value: activate), RubyCommand.Argument(name: "app_icon", value: appIcon), RubyCommand.Argument(name: "content_image", value: contentImage), RubyCommand.Argument(name: "open", value: open), RubyCommand.Argument(name: "execute", value: execute)]) _ = runner.executeCommand(command) } @discardableResult func numberOfCommits(all: String? = nil) -> Int { let command = RubyCommand(commandID: "", methodName: "number_of_commits", className: nil, args: [RubyCommand.Argument(name: "all", value: all)]) return parseInt(fromString: runner.executeCommand(command)) } func oclint(oclintPath: String = "oclint", compileCommands: String = "compile_commands.json", selectReqex: String? = nil, selectRegex: String? = nil, excludeRegex: String? = nil, reportType: String = "html", reportPath: String? = nil, listEnabledRules: Bool = false, rc: String? = nil, thresholds: String? = nil, enableRules: String? = nil, disableRules: String? = nil, maxPriority1: String? = nil, maxPriority2: String? = nil, maxPriority3: String? = nil, enableClangStaticAnalyzer: Bool = false, enableGlobalAnalysis: Bool = false, allowDuplicatedViolations: Bool = false) { let command = RubyCommand(commandID: "", methodName: "oclint", className: nil, args: [RubyCommand.Argument(name: "oclint_path", value: oclintPath), RubyCommand.Argument(name: "compile_commands", value: compileCommands), RubyCommand.Argument(name: "select_reqex", value: selectReqex), RubyCommand.Argument(name: "select_regex", value: selectRegex), RubyCommand.Argument(name: "exclude_regex", value: excludeRegex), RubyCommand.Argument(name: "report_type", value: reportType), RubyCommand.Argument(name: "report_path", value: reportPath), RubyCommand.Argument(name: "list_enabled_rules", value: listEnabledRules), RubyCommand.Argument(name: "rc", value: rc), RubyCommand.Argument(name: "thresholds", value: thresholds), RubyCommand.Argument(name: "enable_rules", value: enableRules), RubyCommand.Argument(name: "disable_rules", value: disableRules), RubyCommand.Argument(name: "max_priority_1", value: maxPriority1), RubyCommand.Argument(name: "max_priority_2", value: maxPriority2), RubyCommand.Argument(name: "max_priority_3", value: maxPriority3), RubyCommand.Argument(name: "enable_clang_static_analyzer", value: enableClangStaticAnalyzer), RubyCommand.Argument(name: "enable_global_analysis", value: enableGlobalAnalysis), RubyCommand.Argument(name: "allow_duplicated_violations", value: allowDuplicatedViolations)]) _ = runner.executeCommand(command) } func onesignal(authToken: String, appName: String, androidToken: String? = nil, apnsP12: String? = nil, apnsP12Password: String? = nil, apnsEnv: String = "production") { let command = RubyCommand(commandID: "", methodName: "onesignal", className: nil, args: [RubyCommand.Argument(name: "auth_token", value: authToken), RubyCommand.Argument(name: "app_name", value: appName), RubyCommand.Argument(name: "android_token", value: androidToken), RubyCommand.Argument(name: "apns_p12", value: apnsP12), RubyCommand.Argument(name: "apns_p12_password", value: apnsP12Password), RubyCommand.Argument(name: "apns_env", value: apnsEnv)]) _ = runner.executeCommand(command) } func pem(development: Bool = false, generateP12: Bool = true, activeDaysLimit: String = "30", force: Bool = false, savePrivateKey: Bool = true, appIdentifier: String, username: String, teamId: String? = nil, teamName: String? = nil, p12Password: String, pemName: String? = nil, outputPath: String = ".", newProfile: String? = nil) { let command = RubyCommand(commandID: "", methodName: "pem", className: nil, args: [RubyCommand.Argument(name: "development", value: development), RubyCommand.Argument(name: "generate_p12", value: generateP12), RubyCommand.Argument(name: "active_days_limit", value: activeDaysLimit), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "save_private_key", value: savePrivateKey), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "p12_password", value: p12Password), RubyCommand.Argument(name: "pem_name", value: pemName), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "new_profile", value: newProfile)]) _ = runner.executeCommand(command) } func pilot(username: String, appIdentifier: String? = nil, appPlatform: String = "ios", ipa: String? = nil, changelog: String? = nil, betaAppDescription: String? = nil, betaAppFeedbackEmail: String? = nil, skipSubmission: Bool = false, skipWaitingForBuildProcessing: Bool = false, updateBuildInfoOnUpload: Bool = false, appleId: String? = nil, distributeExternal: Bool = false, firstName: String? = nil, lastName: String? = nil, email: String? = nil, testersFilePath: String = "./testers.csv", waitProcessingInterval: Int = 30, teamId: String? = nil, teamName: String? = nil, devPortalTeamId: String? = nil, itcProvider: String? = nil, groups: [String]? = nil, waitForUploadedBuild: Bool = false) { let command = RubyCommand(commandID: "", methodName: "pilot", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "app_platform", value: appPlatform), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "changelog", value: changelog), RubyCommand.Argument(name: "beta_app_description", value: betaAppDescription), RubyCommand.Argument(name: "beta_app_feedback_email", value: betaAppFeedbackEmail), RubyCommand.Argument(name: "skip_submission", value: skipSubmission), RubyCommand.Argument(name: "skip_waiting_for_build_processing", value: skipWaitingForBuildProcessing), RubyCommand.Argument(name: "update_build_info_on_upload", value: updateBuildInfoOnUpload), RubyCommand.Argument(name: "apple_id", value: appleId), RubyCommand.Argument(name: "distribute_external", value: distributeExternal), RubyCommand.Argument(name: "first_name", value: firstName), RubyCommand.Argument(name: "last_name", value: lastName), RubyCommand.Argument(name: "email", value: email), RubyCommand.Argument(name: "testers_file_path", value: testersFilePath), RubyCommand.Argument(name: "wait_processing_interval", value: waitProcessingInterval), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "dev_portal_team_id", value: devPortalTeamId), RubyCommand.Argument(name: "itc_provider", value: itcProvider), RubyCommand.Argument(name: "groups", value: groups), RubyCommand.Argument(name: "wait_for_uploaded_build", value: waitForUploadedBuild)]) _ = runner.executeCommand(command) } func pluginScores(outputPath: String, templatePath: String) { let command = RubyCommand(commandID: "", methodName: "plugin_scores", className: nil, args: [RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "template_path", value: templatePath)]) _ = runner.executeCommand(command) } func podLibLint(useBundleExec: Bool = true, verbose: String? = nil, allowWarnings: String? = nil, sources: String? = nil, useLibraries: Bool = false, failFast: Bool = false, `private`: Bool = false, quick: Bool = false) { let command = RubyCommand(commandID: "", methodName: "pod_lib_lint", className: nil, args: [RubyCommand.Argument(name: "use_bundle_exec", value: useBundleExec), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "allow_warnings", value: allowWarnings), RubyCommand.Argument(name: "sources", value: sources), RubyCommand.Argument(name: "use_libraries", value: useLibraries), RubyCommand.Argument(name: "fail_fast", value: failFast), RubyCommand.Argument(name: "private", value: `private`), RubyCommand.Argument(name: "quick", value: quick)]) _ = runner.executeCommand(command) } func podPush(path: String? = nil, repo: String? = nil, allowWarnings: String? = nil, useLibraries: String? = nil, sources: String? = nil, swiftVersion: String? = nil, verbose: Bool = false) { let command = RubyCommand(commandID: "", methodName: "pod_push", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "repo", value: repo), RubyCommand.Argument(name: "allow_warnings", value: allowWarnings), RubyCommand.Argument(name: "use_libraries", value: useLibraries), RubyCommand.Argument(name: "sources", value: sources), RubyCommand.Argument(name: "swift_version", value: swiftVersion), RubyCommand.Argument(name: "verbose", value: verbose)]) _ = runner.executeCommand(command) } func podioItem(clientId: String, clientSecret: String, appId: String, appToken: String, identifyingField: String, identifyingValue: String, otherFields: [String : Any]? = nil) { let command = RubyCommand(commandID: "", methodName: "podio_item", className: nil, args: [RubyCommand.Argument(name: "client_id", value: clientId), RubyCommand.Argument(name: "client_secret", value: clientSecret), RubyCommand.Argument(name: "app_id", value: appId), RubyCommand.Argument(name: "app_token", value: appToken), RubyCommand.Argument(name: "identifying_field", value: identifyingField), RubyCommand.Argument(name: "identifying_value", value: identifyingValue), RubyCommand.Argument(name: "other_fields", value: otherFields)]) _ = runner.executeCommand(command) } func precheck(appIdentifier: String = precheckfile.appIdentifier, username: String = precheckfile.username, teamId: String? = precheckfile.teamId, teamName: String? = precheckfile.teamName, defaultRuleLevel: String = precheckfile.defaultRuleLevel, includeInAppPurchases: Bool = precheckfile.includeInAppPurchases, freeStuffInIap: String? = precheckfile.freeStuffInIap) { let command = RubyCommand(commandID: "", methodName: "precheck", className: nil, args: [RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "default_rule_level", value: defaultRuleLevel), RubyCommand.Argument(name: "include_in_app_purchases", value: includeInAppPurchases), RubyCommand.Argument(name: "free_stuff_in_iap", value: freeStuffInIap)]) _ = runner.executeCommand(command) } func produce(username: String, appIdentifier: String, bundleIdentifierSuffix: String? = nil, appName: String, appVersion: String? = nil, sku: String, platform: String = "ios", language: String = "English", companyName: String? = nil, skipItc: Bool = false, itcUsers: [String]? = nil, enabledFeatures: String = "{}", enableServices: String = "{}", skipDevcenter: Bool = false, teamId: String? = nil, teamName: String? = nil, itcTeamId: String? = nil, itcTeamName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "produce", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "bundle_identifier_suffix", value: bundleIdentifierSuffix), RubyCommand.Argument(name: "app_name", value: appName), RubyCommand.Argument(name: "app_version", value: appVersion), RubyCommand.Argument(name: "sku", value: sku), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "language", value: language), RubyCommand.Argument(name: "company_name", value: companyName), RubyCommand.Argument(name: "skip_itc", value: skipItc), RubyCommand.Argument(name: "itc_users", value: itcUsers), RubyCommand.Argument(name: "enabled_features", value: enabledFeatures), RubyCommand.Argument(name: "enable_services", value: enableServices), RubyCommand.Argument(name: "skip_devcenter", value: skipDevcenter), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "itc_team_id", value: itcTeamId), RubyCommand.Argument(name: "itc_team_name", value: itcTeamName)]) _ = runner.executeCommand(command) } @discardableResult func prompt(text: String = "Please enter some text: ", ciInput: String = "", boolean: Bool = false, multiLineEndKeyword: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "prompt", className: nil, args: [RubyCommand.Argument(name: "text", value: text), RubyCommand.Argument(name: "ci_input", value: ciInput), RubyCommand.Argument(name: "boolean", value: boolean), RubyCommand.Argument(name: "multi_line_end_keyword", value: multiLineEndKeyword)]) return runner.executeCommand(command) } func pushGitTags(force: Bool = false, remote: String = "origin", tag: String? = nil) { let command = RubyCommand(commandID: "", methodName: "push_git_tags", className: nil, args: [RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "remote", value: remote), RubyCommand.Argument(name: "tag", value: tag)]) _ = runner.executeCommand(command) } func pushToGitRemote(localBranch: String? = nil, remoteBranch: String? = nil, force: Bool = false, tags: Bool = true, remote: String = "origin") { let command = RubyCommand(commandID: "", methodName: "push_to_git_remote", className: nil, args: [RubyCommand.Argument(name: "local_branch", value: localBranch), RubyCommand.Argument(name: "remote_branch", value: remoteBranch), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "tags", value: tags), RubyCommand.Argument(name: "remote", value: remote)]) _ = runner.executeCommand(command) } @discardableResult func readPodspec(path: String) -> [String : String] { let command = RubyCommand(commandID: "", methodName: "read_podspec", className: nil, args: [RubyCommand.Argument(name: "path", value: path)]) return parseDictionary(fromString: runner.executeCommand(command)) } func recreateSchemes(project: String) { let command = RubyCommand(commandID: "", methodName: "recreate_schemes", className: nil, args: [RubyCommand.Argument(name: "project", value: project)]) _ = runner.executeCommand(command) } @discardableResult func registerDevice(name: String, udid: String, teamId: String? = nil, teamName: String? = nil, username: String) -> String { let command = RubyCommand(commandID: "", methodName: "register_device", className: nil, args: [RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "udid", value: udid), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "username", value: username)]) return runner.executeCommand(command) } func registerDevices(devices: [String : Any]? = nil, devicesFile: String? = nil, teamId: String? = nil, teamName: String? = nil, username: String) { let command = RubyCommand(commandID: "", methodName: "register_devices", className: nil, args: [RubyCommand.Argument(name: "devices", value: devices), RubyCommand.Argument(name: "devices_file", value: devicesFile), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "username", value: username)]) _ = runner.executeCommand(command) } func resetGitRepo(files: String? = nil, force: Bool = false, skipClean: Bool = false, disregardGitignore: Bool = true, exclude: String? = nil) { let command = RubyCommand(commandID: "", methodName: "reset_git_repo", className: nil, args: [RubyCommand.Argument(name: "files", value: files), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "skip_clean", value: skipClean), RubyCommand.Argument(name: "disregard_gitignore", value: disregardGitignore), RubyCommand.Argument(name: "exclude", value: exclude)]) _ = runner.executeCommand(command) } func resetSimulatorContents(ios: [String]? = nil) { let command = RubyCommand(commandID: "", methodName: "reset_simulator_contents", className: nil, args: [RubyCommand.Argument(name: "ios", value: ios)]) _ = runner.executeCommand(command) } func resign(ipa: String, signingIdentity: String, entitlements: String? = nil, provisioningProfile: String, version: String? = nil, displayName: String? = nil, shortVersion: String? = nil, bundleVersion: String? = nil, bundleId: String? = nil, useAppEntitlements: String? = nil, keychainPath: String? = nil) { let command = RubyCommand(commandID: "", methodName: "resign", className: nil, args: [RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "signing_identity", value: signingIdentity), RubyCommand.Argument(name: "entitlements", value: entitlements), RubyCommand.Argument(name: "provisioning_profile", value: provisioningProfile), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "display_name", value: displayName), RubyCommand.Argument(name: "short_version", value: shortVersion), RubyCommand.Argument(name: "bundle_version", value: bundleVersion), RubyCommand.Argument(name: "bundle_id", value: bundleId), RubyCommand.Argument(name: "use_app_entitlements", value: useAppEntitlements), RubyCommand.Argument(name: "keychain_path", value: keychainPath)]) _ = runner.executeCommand(command) } func restoreFile(path: String) { let command = RubyCommand(commandID: "", methodName: "restore_file", className: nil, args: [RubyCommand.Argument(name: "path", value: path)]) _ = runner.executeCommand(command) } @discardableResult func rocket() -> String { let command = RubyCommand(commandID: "", methodName: "rocket", className: nil, args: []) return runner.executeCommand(command) } func rspec() { let command = RubyCommand(commandID: "", methodName: "rspec", className: nil, args: []) _ = runner.executeCommand(command) } func rsync(extra: String = "-av", source: String, destination: String) { let command = RubyCommand(commandID: "", methodName: "rsync", className: nil, args: [RubyCommand.Argument(name: "extra", value: extra), RubyCommand.Argument(name: "source", value: source), RubyCommand.Argument(name: "destination", value: destination)]) _ = runner.executeCommand(command) } func rubocop() { let command = RubyCommand(commandID: "", methodName: "rubocop", className: nil, args: []) _ = runner.executeCommand(command) } func runTests(workspace: String? = nil, project: String? = nil, device: String? = nil, toolchain: String? = nil, devices: [String]? = nil, scheme: String? = nil, clean: Bool = false, codeCoverage: Bool? = nil, addressSanitizer: Bool? = nil, threadSanitizer: Bool? = nil, skipBuild: Bool = false, outputDirectory: String = "./test_output", outputStyle: String? = nil, outputTypes: String = "html,junit", outputFiles: String? = nil, buildlogPath: String = "~/Library/Logs/scan", includeSimulatorLogs: Bool = false, formatter: String? = nil, testWithoutBuilding: Bool? = nil, buildForTesting: Bool? = nil, xctestrun: String? = nil, derivedDataPath: String? = nil, resultBundle: String? = nil, sdk: String? = nil, openReport: Bool = false, configuration: String? = nil, destination: String? = nil, xcargs: String? = nil, xcconfig: String? = nil, onlyTesting: String? = nil, skipTesting: String? = nil, slackUrl: String? = nil, slackChannel: String? = nil, slackMessage: String? = nil, skipSlack: Bool = false, slackOnlyOnFailure: Bool = false, useClangReportName: Bool = false, customReportFileName: String? = nil, failBuild: Bool = true) { let command = RubyCommand(commandID: "", methodName: "run_tests", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "device", value: device), RubyCommand.Argument(name: "toolchain", value: toolchain), RubyCommand.Argument(name: "devices", value: devices), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "code_coverage", value: codeCoverage), RubyCommand.Argument(name: "address_sanitizer", value: addressSanitizer), RubyCommand.Argument(name: "thread_sanitizer", value: threadSanitizer), RubyCommand.Argument(name: "skip_build", value: skipBuild), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_style", value: outputStyle), RubyCommand.Argument(name: "output_types", value: outputTypes), RubyCommand.Argument(name: "output_files", value: outputFiles), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "include_simulator_logs", value: includeSimulatorLogs), RubyCommand.Argument(name: "formatter", value: formatter), RubyCommand.Argument(name: "test_without_building", value: testWithoutBuilding), RubyCommand.Argument(name: "build_for_testing", value: buildForTesting), RubyCommand.Argument(name: "xctestrun", value: xctestrun), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "result_bundle", value: resultBundle), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "open_report", value: openReport), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "xcconfig", value: xcconfig), RubyCommand.Argument(name: "only_testing", value: onlyTesting), RubyCommand.Argument(name: "skip_testing", value: skipTesting), RubyCommand.Argument(name: "slack_url", value: slackUrl), RubyCommand.Argument(name: "slack_channel", value: slackChannel), RubyCommand.Argument(name: "slack_message", value: slackMessage), RubyCommand.Argument(name: "skip_slack", value: skipSlack), RubyCommand.Argument(name: "slack_only_on_failure", value: slackOnlyOnFailure), RubyCommand.Argument(name: "use_clang_report_name", value: useClangReportName), RubyCommand.Argument(name: "custom_report_file_name", value: customReportFileName), RubyCommand.Argument(name: "fail_build", value: failBuild)]) _ = runner.executeCommand(command) } func s3(ipa: String? = nil, dsym: String? = nil, uploadMetadata: Bool = true, plistTemplatePath: String? = nil, plistFileName: String? = nil, htmlTemplatePath: String? = nil, htmlFileName: String? = nil, versionTemplatePath: String? = nil, versionFileName: String? = nil, accessKey: String? = nil, secretAccessKey: String? = nil, bucket: String? = nil, region: String? = nil, path: String = "v{CFBundleShortVersionString}_b{CFBundleVersion}/", source: String? = nil, acl: String = "public_read") { let command = RubyCommand(commandID: "", methodName: "s3", className: nil, args: [RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "dsym", value: dsym), RubyCommand.Argument(name: "upload_metadata", value: uploadMetadata), RubyCommand.Argument(name: "plist_template_path", value: plistTemplatePath), RubyCommand.Argument(name: "plist_file_name", value: plistFileName), RubyCommand.Argument(name: "html_template_path", value: htmlTemplatePath), RubyCommand.Argument(name: "html_file_name", value: htmlFileName), RubyCommand.Argument(name: "version_template_path", value: versionTemplatePath), RubyCommand.Argument(name: "version_file_name", value: versionFileName), RubyCommand.Argument(name: "access_key", value: accessKey), RubyCommand.Argument(name: "secret_access_key", value: secretAccessKey), RubyCommand.Argument(name: "bucket", value: bucket), RubyCommand.Argument(name: "region", value: region), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "source", value: source), RubyCommand.Argument(name: "acl", value: acl)]) _ = runner.executeCommand(command) } func scan(workspace: String? = scanfile.workspace, project: String? = scanfile.project, device: String? = scanfile.device, toolchain: String? = scanfile.toolchain, devices: [String]? = scanfile.devices, scheme: String? = scanfile.scheme, clean: Bool = scanfile.clean, codeCoverage: Bool? = scanfile.codeCoverage, addressSanitizer: Bool? = scanfile.addressSanitizer, threadSanitizer: Bool? = scanfile.threadSanitizer, skipBuild: Bool = scanfile.skipBuild, outputDirectory: String = scanfile.outputDirectory, outputStyle: String? = scanfile.outputStyle, outputTypes: String = scanfile.outputTypes, outputFiles: String? = scanfile.outputFiles, buildlogPath: String = scanfile.buildlogPath, includeSimulatorLogs: Bool = scanfile.includeSimulatorLogs, formatter: String? = scanfile.formatter, testWithoutBuilding: Bool? = scanfile.testWithoutBuilding, buildForTesting: Bool? = scanfile.buildForTesting, xctestrun: String? = scanfile.xctestrun, derivedDataPath: String? = scanfile.derivedDataPath, resultBundle: String? = scanfile.resultBundle, sdk: String? = scanfile.sdk, openReport: Bool = scanfile.openReport, configuration: String? = scanfile.configuration, destination: String? = scanfile.destination, xcargs: String? = scanfile.xcargs, xcconfig: String? = scanfile.xcconfig, onlyTesting: String? = scanfile.onlyTesting, skipTesting: String? = scanfile.skipTesting, slackUrl: String? = scanfile.slackUrl, slackChannel: String? = scanfile.slackChannel, slackMessage: String? = scanfile.slackMessage, skipSlack: Bool = scanfile.skipSlack, slackOnlyOnFailure: Bool = scanfile.slackOnlyOnFailure, useClangReportName: Bool = scanfile.useClangReportName, customReportFileName: String? = scanfile.customReportFileName, failBuild: Bool = scanfile.failBuild) { let command = RubyCommand(commandID: "", methodName: "scan", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "device", value: device), RubyCommand.Argument(name: "toolchain", value: toolchain), RubyCommand.Argument(name: "devices", value: devices), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "code_coverage", value: codeCoverage), RubyCommand.Argument(name: "address_sanitizer", value: addressSanitizer), RubyCommand.Argument(name: "thread_sanitizer", value: threadSanitizer), RubyCommand.Argument(name: "skip_build", value: skipBuild), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_style", value: outputStyle), RubyCommand.Argument(name: "output_types", value: outputTypes), RubyCommand.Argument(name: "output_files", value: outputFiles), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "include_simulator_logs", value: includeSimulatorLogs), RubyCommand.Argument(name: "formatter", value: formatter), RubyCommand.Argument(name: "test_without_building", value: testWithoutBuilding), RubyCommand.Argument(name: "build_for_testing", value: buildForTesting), RubyCommand.Argument(name: "xctestrun", value: xctestrun), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "result_bundle", value: resultBundle), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "open_report", value: openReport), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "destination", value: destination), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "xcconfig", value: xcconfig), RubyCommand.Argument(name: "only_testing", value: onlyTesting), RubyCommand.Argument(name: "skip_testing", value: skipTesting), RubyCommand.Argument(name: "slack_url", value: slackUrl), RubyCommand.Argument(name: "slack_channel", value: slackChannel), RubyCommand.Argument(name: "slack_message", value: slackMessage), RubyCommand.Argument(name: "skip_slack", value: skipSlack), RubyCommand.Argument(name: "slack_only_on_failure", value: slackOnlyOnFailure), RubyCommand.Argument(name: "use_clang_report_name", value: useClangReportName), RubyCommand.Argument(name: "custom_report_file_name", value: customReportFileName), RubyCommand.Argument(name: "fail_build", value: failBuild)]) _ = runner.executeCommand(command) } func scp(username: String, password: String? = nil, host: String, port: String = "22", upload: [String : Any]? = nil, download: [String : Any]? = nil) { let command = RubyCommand(commandID: "", methodName: "scp", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "host", value: host), RubyCommand.Argument(name: "port", value: port), RubyCommand.Argument(name: "upload", value: upload), RubyCommand.Argument(name: "download", value: download)]) _ = runner.executeCommand(command) } func screengrab(androidHome: String? = screengrabfile.androidHome, buildToolsVersion: String? = screengrabfile.buildToolsVersion, locales: [String] = screengrabfile.locales, clearPreviousScreenshots: Bool = screengrabfile.clearPreviousScreenshots, outputDirectory: String = screengrabfile.outputDirectory, skipOpenSummary: Bool = screengrabfile.skipOpenSummary, appPackageName: String = screengrabfile.appPackageName, testsPackageName: String? = screengrabfile.testsPackageName, useTestsInPackages: [String]? = screengrabfile.useTestsInPackages, useTestsInClasses: [String]? = screengrabfile.useTestsInClasses, launchArguments: [String]? = screengrabfile.launchArguments, testInstrumentationRunner: String = screengrabfile.testInstrumentationRunner, endingLocale: String = screengrabfile.endingLocale, appApkPath: String? = screengrabfile.appApkPath, testsApkPath: String? = screengrabfile.testsApkPath, specificDevice: String? = screengrabfile.specificDevice, deviceType: String = screengrabfile.deviceType, exitOnTestFailure: Bool = screengrabfile.exitOnTestFailure, reinstallApp: Bool = screengrabfile.reinstallApp) { let command = RubyCommand(commandID: "", methodName: "screengrab", className: nil, args: [RubyCommand.Argument(name: "android_home", value: androidHome), RubyCommand.Argument(name: "build_tools_version", value: buildToolsVersion), RubyCommand.Argument(name: "locales", value: locales), RubyCommand.Argument(name: "clear_previous_screenshots", value: clearPreviousScreenshots), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "skip_open_summary", value: skipOpenSummary), RubyCommand.Argument(name: "app_package_name", value: appPackageName), RubyCommand.Argument(name: "tests_package_name", value: testsPackageName), RubyCommand.Argument(name: "use_tests_in_packages", value: useTestsInPackages), RubyCommand.Argument(name: "use_tests_in_classes", value: useTestsInClasses), RubyCommand.Argument(name: "launch_arguments", value: launchArguments), RubyCommand.Argument(name: "test_instrumentation_runner", value: testInstrumentationRunner), RubyCommand.Argument(name: "ending_locale", value: endingLocale), RubyCommand.Argument(name: "app_apk_path", value: appApkPath), RubyCommand.Argument(name: "tests_apk_path", value: testsApkPath), RubyCommand.Argument(name: "specific_device", value: specificDevice), RubyCommand.Argument(name: "device_type", value: deviceType), RubyCommand.Argument(name: "exit_on_test_failure", value: exitOnTestFailure), RubyCommand.Argument(name: "reinstall_app", value: reinstallApp)]) _ = runner.executeCommand(command) } func setBuildNumberRepository(useHgRevisionNumber: Bool = false, xcodeproj: String? = nil) { let command = RubyCommand(commandID: "", methodName: "set_build_number_repository", className: nil, args: [RubyCommand.Argument(name: "use_hg_revision_number", value: useHgRevisionNumber), RubyCommand.Argument(name: "xcodeproj", value: xcodeproj)]) _ = runner.executeCommand(command) } func setChangelog(appIdentifier: String, username: String, version: String? = nil, changelog: String? = nil, teamId: String? = nil, teamName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "set_changelog", className: nil, args: [RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "changelog", value: changelog), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName)]) _ = runner.executeCommand(command) } @discardableResult func setGithubRelease(repositoryName: String, serverUrl: String = "https://api.github.com", apiToken: String, tagName: String, name: String? = nil, commitish: String? = nil, description: String? = nil, isDraft: Bool = false, isPrerelease: Bool = false, uploadAssets: String? = nil) -> [String : String] { let command = RubyCommand(commandID: "", methodName: "set_github_release", className: nil, args: [RubyCommand.Argument(name: "repository_name", value: repositoryName), RubyCommand.Argument(name: "server_url", value: serverUrl), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "tag_name", value: tagName), RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "commitish", value: commitish), RubyCommand.Argument(name: "description", value: description), RubyCommand.Argument(name: "is_draft", value: isDraft), RubyCommand.Argument(name: "is_prerelease", value: isPrerelease), RubyCommand.Argument(name: "upload_assets", value: uploadAssets)]) return parseDictionary(fromString: runner.executeCommand(command)) } func setInfoPlistValue(key: String, subkey: String? = nil, value: String, path: String, outputFileName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "set_info_plist_value", className: nil, args: [RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "subkey", value: subkey), RubyCommand.Argument(name: "value", value: value), RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "output_file_name", value: outputFileName)]) _ = runner.executeCommand(command) } func setPodKey(useBundleExec: Bool = true, key: String, value: String, project: String? = nil) { let command = RubyCommand(commandID: "", methodName: "set_pod_key", className: nil, args: [RubyCommand.Argument(name: "use_bundle_exec", value: useBundleExec), RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "value", value: value), RubyCommand.Argument(name: "project", value: project)]) _ = runner.executeCommand(command) } func setupCircleCi(force: Bool = false) { let command = RubyCommand(commandID: "", methodName: "setup_circle_ci", className: nil, args: [RubyCommand.Argument(name: "force", value: force)]) _ = runner.executeCommand(command) } func setupJenkins(force: Bool = false, unlockKeychain: Bool = true, addKeychainToSearchList: String = "replace", setDefaultKeychain: Bool = true, keychainPath: String? = nil, keychainPassword: String, setCodeSigningIdentity: Bool = true, codeSigningIdentity: String? = nil, outputDirectory: String = "./output", derivedDataPath: String = "./derivedData", resultBundle: Bool = true) { let command = RubyCommand(commandID: "", methodName: "setup_jenkins", className: nil, args: [RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "unlock_keychain", value: unlockKeychain), RubyCommand.Argument(name: "add_keychain_to_search_list", value: addKeychainToSearchList), RubyCommand.Argument(name: "set_default_keychain", value: setDefaultKeychain), RubyCommand.Argument(name: "keychain_path", value: keychainPath), RubyCommand.Argument(name: "keychain_password", value: keychainPassword), RubyCommand.Argument(name: "set_code_signing_identity", value: setCodeSigningIdentity), RubyCommand.Argument(name: "code_signing_identity", value: codeSigningIdentity), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "result_bundle", value: resultBundle)]) _ = runner.executeCommand(command) } func setupTravis(force: Bool = false) { let command = RubyCommand(commandID: "", methodName: "setup_travis", className: nil, args: [RubyCommand.Argument(name: "force", value: force)]) _ = runner.executeCommand(command) } @discardableResult func sh(command: String, log: Bool = true, errorCallback: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "sh", className: nil, args: [RubyCommand.Argument(name: "command", value: command), RubyCommand.Argument(name: "log", value: log), RubyCommand.Argument(name: "error_callback", value: errorCallback)]) return runner.executeCommand(command) } func sigh(adhoc: Bool = false, development: Bool = false, skipInstall: Bool = false, force: Bool = false, appIdentifier: String, username: String, teamId: String? = nil, teamName: String? = nil, provisioningName: String? = nil, ignoreProfilesWithDifferentName: Bool = false, outputPath: String = ".", certId: String? = nil, certOwnerName: String? = nil, filename: String? = nil, skipFetchProfiles: Bool = false, skipCertificateVerification: Bool = false, platform: String = "ios", readonly: Bool = false, templateName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "sigh", className: nil, args: [RubyCommand.Argument(name: "adhoc", value: adhoc), RubyCommand.Argument(name: "development", value: development), RubyCommand.Argument(name: "skip_install", value: skipInstall), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "provisioning_name", value: provisioningName), RubyCommand.Argument(name: "ignore_profiles_with_different_name", value: ignoreProfilesWithDifferentName), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "cert_id", value: certId), RubyCommand.Argument(name: "cert_owner_name", value: certOwnerName), RubyCommand.Argument(name: "filename", value: filename), RubyCommand.Argument(name: "skip_fetch_profiles", value: skipFetchProfiles), RubyCommand.Argument(name: "skip_certificate_verification", value: skipCertificateVerification), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "readonly", value: readonly), RubyCommand.Argument(name: "template_name", value: templateName)]) _ = runner.executeCommand(command) } func slack(message: String? = nil, channel: String? = nil, useWebhookConfiguredUsernameAndIcon: Bool = false, slackUrl: String, username: String = "fastlane", iconUrl: String = "https://s3-eu-west-1.amazonaws.com/fastlane.tools/fastlane.png", payload: String = "{}", defaultPayloads: [String]? = nil, attachmentProperties: String = "{}", success: Bool = true, failOnError: Bool = true) { let command = RubyCommand(commandID: "", methodName: "slack", className: nil, args: [RubyCommand.Argument(name: "message", value: message), RubyCommand.Argument(name: "channel", value: channel), RubyCommand.Argument(name: "use_webhook_configured_username_and_icon", value: useWebhookConfiguredUsernameAndIcon), RubyCommand.Argument(name: "slack_url", value: slackUrl), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "icon_url", value: iconUrl), RubyCommand.Argument(name: "payload", value: payload), RubyCommand.Argument(name: "default_payloads", value: defaultPayloads), RubyCommand.Argument(name: "attachment_properties", value: attachmentProperties), RubyCommand.Argument(name: "success", value: success), RubyCommand.Argument(name: "fail_on_error", value: failOnError)]) _ = runner.executeCommand(command) } func slackTrain() { let command = RubyCommand(commandID: "", methodName: "slack_train", className: nil, args: []) _ = runner.executeCommand(command) } func slackTrainStart(distance: Int = 5, train: String = "🚝", rail: String = "=", reverseDirection: Bool = false) { let command = RubyCommand(commandID: "", methodName: "slack_train_start", className: nil, args: [RubyCommand.Argument(name: "distance", value: distance), RubyCommand.Argument(name: "train", value: train), RubyCommand.Argument(name: "rail", value: rail), RubyCommand.Argument(name: "reverse_direction", value: reverseDirection)]) _ = runner.executeCommand(command) } func slather(buildDirectory: String? = nil, proj: String? = nil, workspace: String? = nil, scheme: String? = nil, configuration: String? = nil, inputFormat: String? = nil, buildkite: Bool? = nil, teamcity: Bool? = nil, jenkins: Bool? = nil, travis: Bool? = nil, travisPro: Bool? = nil, circleci: Bool? = nil, coveralls: Bool? = nil, simpleOutput: Bool? = nil, gutterJson: Bool? = nil, coberturaXml: Bool? = nil, llvmCov: String? = nil, html: Bool? = nil, show: Bool = false, sourceDirectory: String? = nil, outputDirectory: String? = nil, ignore: String? = nil, verbose: Bool? = nil, useBundleExec: Bool = false, binaryBasename: Bool = false, binaryFile: Bool = false, sourceFiles: Bool = false, decimals: Bool = false) { let command = RubyCommand(commandID: "", methodName: "slather", className: nil, args: [RubyCommand.Argument(name: "build_directory", value: buildDirectory), RubyCommand.Argument(name: "proj", value: proj), RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "input_format", value: inputFormat), RubyCommand.Argument(name: "buildkite", value: buildkite), RubyCommand.Argument(name: "teamcity", value: teamcity), RubyCommand.Argument(name: "jenkins", value: jenkins), RubyCommand.Argument(name: "travis", value: travis), RubyCommand.Argument(name: "travis_pro", value: travisPro), RubyCommand.Argument(name: "circleci", value: circleci), RubyCommand.Argument(name: "coveralls", value: coveralls), RubyCommand.Argument(name: "simple_output", value: simpleOutput), RubyCommand.Argument(name: "gutter_json", value: gutterJson), RubyCommand.Argument(name: "cobertura_xml", value: coberturaXml), RubyCommand.Argument(name: "llvm_cov", value: llvmCov), RubyCommand.Argument(name: "html", value: html), RubyCommand.Argument(name: "show", value: show), RubyCommand.Argument(name: "source_directory", value: sourceDirectory), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "ignore", value: ignore), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "use_bundle_exec", value: useBundleExec), RubyCommand.Argument(name: "binary_basename", value: binaryBasename), RubyCommand.Argument(name: "binary_file", value: binaryFile), RubyCommand.Argument(name: "source_files", value: sourceFiles), RubyCommand.Argument(name: "decimals", value: decimals)]) _ = runner.executeCommand(command) } func snapshot(workspace: String? = snapshotfile.workspace, project: String? = snapshotfile.project, xcargs: String? = snapshotfile.xcargs, devices: [String]? = snapshotfile.devices, languages: [String] = snapshotfile.languages, launchArguments: [String] = snapshotfile.launchArguments, outputDirectory: String = snapshotfile.outputDirectory, outputSimulatorLogs: Bool = snapshotfile.outputSimulatorLogs, iosVersion: String? = snapshotfile.iosVersion, skipOpenSummary: Bool = snapshotfile.skipOpenSummary, skipHelperVersionCheck: Bool = snapshotfile.skipHelperVersionCheck, clearPreviousScreenshots: Bool = snapshotfile.clearPreviousScreenshots, reinstallApp: Bool = snapshotfile.reinstallApp, eraseSimulator: Bool = snapshotfile.eraseSimulator, localizeSimulator: Bool = snapshotfile.localizeSimulator, appIdentifier: String? = snapshotfile.appIdentifier, addPhotos: [String]? = snapshotfile.addPhotos, addVideos: [String]? = snapshotfile.addVideos, buildlogPath: String = snapshotfile.buildlogPath, clean: Bool = snapshotfile.clean, testWithoutBuilding: Bool? = snapshotfile.testWithoutBuilding, configuration: String? = snapshotfile.configuration, xcprettyArgs: String? = snapshotfile.xcprettyArgs, sdk: String? = snapshotfile.sdk, scheme: String? = snapshotfile.scheme, numberOfRetries: Int = snapshotfile.numberOfRetries, stopAfterFirstError: Bool = snapshotfile.stopAfterFirstError, derivedDataPath: String? = snapshotfile.derivedDataPath, testTargetName: String? = snapshotfile.testTargetName, namespaceLogFiles: String? = snapshotfile.namespaceLogFiles, concurrentSimulators: Bool = snapshotfile.concurrentSimulators) { let command = RubyCommand(commandID: "", methodName: "snapshot", className: nil, args: [RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "project", value: project), RubyCommand.Argument(name: "xcargs", value: xcargs), RubyCommand.Argument(name: "devices", value: devices), RubyCommand.Argument(name: "languages", value: languages), RubyCommand.Argument(name: "launch_arguments", value: launchArguments), RubyCommand.Argument(name: "output_directory", value: outputDirectory), RubyCommand.Argument(name: "output_simulator_logs", value: outputSimulatorLogs), RubyCommand.Argument(name: "ios_version", value: iosVersion), RubyCommand.Argument(name: "skip_open_summary", value: skipOpenSummary), RubyCommand.Argument(name: "skip_helper_version_check", value: skipHelperVersionCheck), RubyCommand.Argument(name: "clear_previous_screenshots", value: clearPreviousScreenshots), RubyCommand.Argument(name: "reinstall_app", value: reinstallApp), RubyCommand.Argument(name: "erase_simulator", value: eraseSimulator), RubyCommand.Argument(name: "localize_simulator", value: localizeSimulator), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "add_photos", value: addPhotos), RubyCommand.Argument(name: "add_videos", value: addVideos), RubyCommand.Argument(name: "buildlog_path", value: buildlogPath), RubyCommand.Argument(name: "clean", value: clean), RubyCommand.Argument(name: "test_without_building", value: testWithoutBuilding), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "xcpretty_args", value: xcprettyArgs), RubyCommand.Argument(name: "sdk", value: sdk), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "number_of_retries", value: numberOfRetries), RubyCommand.Argument(name: "stop_after_first_error", value: stopAfterFirstError), RubyCommand.Argument(name: "derived_data_path", value: derivedDataPath), RubyCommand.Argument(name: "test_target_name", value: testTargetName), RubyCommand.Argument(name: "namespace_log_files", value: namespaceLogFiles), RubyCommand.Argument(name: "concurrent_simulators", value: concurrentSimulators)]) _ = runner.executeCommand(command) } func sonar(projectConfigurationPath: String? = nil, projectKey: String? = nil, projectName: String? = nil, projectVersion: String? = nil, sourcesPath: String? = nil, projectLanguage: String? = nil, sourceEncoding: String? = nil, sonarRunnerArgs: String? = nil, sonarLogin: String? = nil) { let command = RubyCommand(commandID: "", methodName: "sonar", className: nil, args: [RubyCommand.Argument(name: "project_configuration_path", value: projectConfigurationPath), RubyCommand.Argument(name: "project_key", value: projectKey), RubyCommand.Argument(name: "project_name", value: projectName), RubyCommand.Argument(name: "project_version", value: projectVersion), RubyCommand.Argument(name: "sources_path", value: sourcesPath), RubyCommand.Argument(name: "project_language", value: projectLanguage), RubyCommand.Argument(name: "source_encoding", value: sourceEncoding), RubyCommand.Argument(name: "sonar_runner_args", value: sonarRunnerArgs), RubyCommand.Argument(name: "sonar_login", value: sonarLogin)]) _ = runner.executeCommand(command) } func splunkmint(dsym: String? = nil, apiKey: String, apiToken: String, verbose: Bool = false, uploadProgress: Bool = false, proxyUsername: String? = nil, proxyPassword: String? = nil, proxyAddress: String? = nil, proxyPort: String? = nil) { let command = RubyCommand(commandID: "", methodName: "splunkmint", className: nil, args: [RubyCommand.Argument(name: "dsym", value: dsym), RubyCommand.Argument(name: "api_key", value: apiKey), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "upload_progress", value: uploadProgress), RubyCommand.Argument(name: "proxy_username", value: proxyUsername), RubyCommand.Argument(name: "proxy_password", value: proxyPassword), RubyCommand.Argument(name: "proxy_address", value: proxyAddress), RubyCommand.Argument(name: "proxy_port", value: proxyPort)]) _ = runner.executeCommand(command) } func spm(command: String = "build", buildPath: String? = nil, packagePath: String? = nil, configuration: String? = nil, verbose: Bool = false) { let command = RubyCommand(commandID: "", methodName: "spm", className: nil, args: [RubyCommand.Argument(name: "command", value: command), RubyCommand.Argument(name: "build_path", value: buildPath), RubyCommand.Argument(name: "package_path", value: packagePath), RubyCommand.Argument(name: "configuration", value: configuration), RubyCommand.Argument(name: "verbose", value: verbose)]) _ = runner.executeCommand(command) } func ssh(username: String, password: String? = nil, host: String, port: String = "22", commands: [String]? = nil, log: Bool = true) { let command = RubyCommand(commandID: "", methodName: "ssh", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "host", value: host), RubyCommand.Argument(name: "port", value: port), RubyCommand.Argument(name: "commands", value: commands), RubyCommand.Argument(name: "log", value: log)]) _ = runner.executeCommand(command) } func supply(packageName: String, track: String = "production", rollout: String? = nil, metadataPath: String? = nil, key: String? = nil, issuer: String? = nil, jsonKey: String? = nil, jsonKeyData: String? = nil, apk: String? = nil, apkPaths: [String]? = nil, skipUploadApk: Bool = false, skipUploadMetadata: Bool = false, skipUploadImages: Bool = false, skipUploadScreenshots: Bool = false, trackPromoteTo: String? = nil, validateOnly: Bool = false, mapping: String? = nil, mappingPaths: [String]? = nil, rootUrl: String? = nil, checkSupersededTracks: Bool = false) { let command = RubyCommand(commandID: "", methodName: "supply", className: nil, args: [RubyCommand.Argument(name: "package_name", value: packageName), RubyCommand.Argument(name: "track", value: track), RubyCommand.Argument(name: "rollout", value: rollout), RubyCommand.Argument(name: "metadata_path", value: metadataPath), RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "issuer", value: issuer), RubyCommand.Argument(name: "json_key", value: jsonKey), RubyCommand.Argument(name: "json_key_data", value: jsonKeyData), RubyCommand.Argument(name: "apk", value: apk), RubyCommand.Argument(name: "apk_paths", value: apkPaths), RubyCommand.Argument(name: "skip_upload_apk", value: skipUploadApk), RubyCommand.Argument(name: "skip_upload_metadata", value: skipUploadMetadata), RubyCommand.Argument(name: "skip_upload_images", value: skipUploadImages), RubyCommand.Argument(name: "skip_upload_screenshots", value: skipUploadScreenshots), RubyCommand.Argument(name: "track_promote_to", value: trackPromoteTo), RubyCommand.Argument(name: "validate_only", value: validateOnly), RubyCommand.Argument(name: "mapping", value: mapping), RubyCommand.Argument(name: "mapping_paths", value: mappingPaths), RubyCommand.Argument(name: "root_url", value: rootUrl), RubyCommand.Argument(name: "check_superseded_tracks", value: checkSupersededTracks)]) _ = runner.executeCommand(command) } func swiftlint(mode: String = "lint", outputFile: String? = nil, configFile: String? = nil, strict: Bool = false, files: String? = nil, ignoreExitStatus: Bool = false, reporter: String? = nil, quiet: Bool = false, executable: String? = nil) { let command = RubyCommand(commandID: "", methodName: "swiftlint", className: nil, args: [RubyCommand.Argument(name: "mode", value: mode), RubyCommand.Argument(name: "output_file", value: outputFile), RubyCommand.Argument(name: "config_file", value: configFile), RubyCommand.Argument(name: "strict", value: strict), RubyCommand.Argument(name: "files", value: files), RubyCommand.Argument(name: "ignore_exit_status", value: ignoreExitStatus), RubyCommand.Argument(name: "reporter", value: reporter), RubyCommand.Argument(name: "quiet", value: quiet), RubyCommand.Argument(name: "executable", value: executable)]) _ = runner.executeCommand(command) } func syncCodeSigning(gitUrl: String, gitBranch: String = "master", type: String = "development", appIdentifier: [String], username: String, keychainName: String = "login.keychain", keychainPassword: String? = nil, readonly: Bool = false, teamId: String? = nil, gitFullName: String? = nil, gitUserEmail: String? = nil, teamName: String? = nil, verbose: Bool = false, force: Bool = false, skipConfirmation: Bool = false, shallowClone: Bool = false, cloneBranchDirectly: Bool = false, workspace: String? = nil, forceForNewDevices: Bool = false, skipDocs: Bool = false, platform: String = "ios", templateName: String? = nil) { let command = RubyCommand(commandID: "", methodName: "sync_code_signing", className: nil, args: [RubyCommand.Argument(name: "git_url", value: gitUrl), RubyCommand.Argument(name: "git_branch", value: gitBranch), RubyCommand.Argument(name: "type", value: type), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "keychain_name", value: keychainName), RubyCommand.Argument(name: "keychain_password", value: keychainPassword), RubyCommand.Argument(name: "readonly", value: readonly), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "git_full_name", value: gitFullName), RubyCommand.Argument(name: "git_user_email", value: gitUserEmail), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "verbose", value: verbose), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "skip_confirmation", value: skipConfirmation), RubyCommand.Argument(name: "shallow_clone", value: shallowClone), RubyCommand.Argument(name: "clone_branch_directly", value: cloneBranchDirectly), RubyCommand.Argument(name: "workspace", value: workspace), RubyCommand.Argument(name: "force_for_new_devices", value: forceForNewDevices), RubyCommand.Argument(name: "skip_docs", value: skipDocs), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "template_name", value: templateName)]) _ = runner.executeCommand(command) } func testfairy(apiKey: String, ipa: String, symbolsFile: String? = nil, testersGroups: [String] = [], metrics: [String] = [], iconWatermark: String = "off", comment: String = "No comment provided", autoUpdate: String = "off", notify: String = "off", options: [String] = []) { let command = RubyCommand(commandID: "", methodName: "testfairy", className: nil, args: [RubyCommand.Argument(name: "api_key", value: apiKey), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "symbols_file", value: symbolsFile), RubyCommand.Argument(name: "testers_groups", value: testersGroups), RubyCommand.Argument(name: "metrics", value: metrics), RubyCommand.Argument(name: "icon_watermark", value: iconWatermark), RubyCommand.Argument(name: "comment", value: comment), RubyCommand.Argument(name: "auto_update", value: autoUpdate), RubyCommand.Argument(name: "notify", value: notify), RubyCommand.Argument(name: "options", value: options)]) _ = runner.executeCommand(command) } func testflight(username: String, appIdentifier: String? = nil, appPlatform: String = "ios", ipa: String? = nil, changelog: String? = nil, betaAppDescription: String? = nil, betaAppFeedbackEmail: String? = nil, skipSubmission: Bool = false, skipWaitingForBuildProcessing: Bool = false, updateBuildInfoOnUpload: Bool = false, appleId: String? = nil, distributeExternal: Bool = false, firstName: String? = nil, lastName: String? = nil, email: String? = nil, testersFilePath: String = "./testers.csv", waitProcessingInterval: Int = 30, teamId: String? = nil, teamName: String? = nil, devPortalTeamId: String? = nil, itcProvider: String? = nil, groups: [String]? = nil, waitForUploadedBuild: Bool = false) { let command = RubyCommand(commandID: "", methodName: "testflight", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "app_platform", value: appPlatform), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "changelog", value: changelog), RubyCommand.Argument(name: "beta_app_description", value: betaAppDescription), RubyCommand.Argument(name: "beta_app_feedback_email", value: betaAppFeedbackEmail), RubyCommand.Argument(name: "skip_submission", value: skipSubmission), RubyCommand.Argument(name: "skip_waiting_for_build_processing", value: skipWaitingForBuildProcessing), RubyCommand.Argument(name: "update_build_info_on_upload", value: updateBuildInfoOnUpload), RubyCommand.Argument(name: "apple_id", value: appleId), RubyCommand.Argument(name: "distribute_external", value: distributeExternal), RubyCommand.Argument(name: "first_name", value: firstName), RubyCommand.Argument(name: "last_name", value: lastName), RubyCommand.Argument(name: "email", value: email), RubyCommand.Argument(name: "testers_file_path", value: testersFilePath), RubyCommand.Argument(name: "wait_processing_interval", value: waitProcessingInterval), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "dev_portal_team_id", value: devPortalTeamId), RubyCommand.Argument(name: "itc_provider", value: itcProvider), RubyCommand.Argument(name: "groups", value: groups), RubyCommand.Argument(name: "wait_for_uploaded_build", value: waitForUploadedBuild)]) _ = runner.executeCommand(command) } func tryouts(appId: String, apiToken: String, buildFile: String, notes: String? = nil, notesPath: String? = nil, notify: String = "1", status: String = "2") { let command = RubyCommand(commandID: "", methodName: "tryouts", className: nil, args: [RubyCommand.Argument(name: "app_id", value: appId), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "build_file", value: buildFile), RubyCommand.Argument(name: "notes", value: notes), RubyCommand.Argument(name: "notes_path", value: notesPath), RubyCommand.Argument(name: "notify", value: notify), RubyCommand.Argument(name: "status", value: status)]) _ = runner.executeCommand(command) } func twitter(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String, message: String) { let command = RubyCommand(commandID: "", methodName: "twitter", className: nil, args: [RubyCommand.Argument(name: "consumer_key", value: consumerKey), RubyCommand.Argument(name: "consumer_secret", value: consumerSecret), RubyCommand.Argument(name: "access_token", value: accessToken), RubyCommand.Argument(name: "access_token_secret", value: accessTokenSecret), RubyCommand.Argument(name: "message", value: message)]) _ = runner.executeCommand(command) } func typetalk() { let command = RubyCommand(commandID: "", methodName: "typetalk", className: nil, args: []) _ = runner.executeCommand(command) } func unlockKeychain(path: String, password: String, addToSearchList: Bool = true, setDefault: Bool = false) { let command = RubyCommand(commandID: "", methodName: "unlock_keychain", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "add_to_search_list", value: addToSearchList), RubyCommand.Argument(name: "set_default", value: setDefault)]) _ = runner.executeCommand(command) } func updateAppGroupIdentifiers(entitlementsFile: String, appGroupIdentifiers: String) { let command = RubyCommand(commandID: "", methodName: "update_app_group_identifiers", className: nil, args: [RubyCommand.Argument(name: "entitlements_file", value: entitlementsFile), RubyCommand.Argument(name: "app_group_identifiers", value: appGroupIdentifiers)]) _ = runner.executeCommand(command) } func updateAppIdentifier(xcodeproj: String, plistPath: String, appIdentifier: String) { let command = RubyCommand(commandID: "", methodName: "update_app_identifier", className: nil, args: [RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "plist_path", value: plistPath), RubyCommand.Argument(name: "app_identifier", value: appIdentifier)]) _ = runner.executeCommand(command) } func updateFastlane(nightly: Bool = false, noUpdate: Bool = false, tools: String? = nil) { let command = RubyCommand(commandID: "", methodName: "update_fastlane", className: nil, args: [RubyCommand.Argument(name: "nightly", value: nightly), RubyCommand.Argument(name: "no_update", value: noUpdate), RubyCommand.Argument(name: "tools", value: tools)]) _ = runner.executeCommand(command) } func updateIcloudContainerIdentifiers(entitlementsFile: String, icloudContainerIdentifiers: String) { let command = RubyCommand(commandID: "", methodName: "update_icloud_container_identifiers", className: nil, args: [RubyCommand.Argument(name: "entitlements_file", value: entitlementsFile), RubyCommand.Argument(name: "icloud_container_identifiers", value: icloudContainerIdentifiers)]) _ = runner.executeCommand(command) } func updateInfoPlist(xcodeproj: String? = nil, plistPath: String? = nil, scheme: String? = nil, appIdentifier: String? = nil, displayName: String? = nil, block: String? = nil) { let command = RubyCommand(commandID: "", methodName: "update_info_plist", className: nil, args: [RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "plist_path", value: plistPath), RubyCommand.Argument(name: "scheme", value: scheme), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "display_name", value: displayName), RubyCommand.Argument(name: "block", value: block)]) _ = runner.executeCommand(command) } func updateProjectCodeSigning(path: String, udid: String, uuid: String) { let command = RubyCommand(commandID: "", methodName: "update_project_code_signing", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "udid", value: udid), RubyCommand.Argument(name: "uuid", value: uuid)]) _ = runner.executeCommand(command) } func updateProjectProvisioning(xcodeproj: String? = nil, profile: String, targetFilter: String? = nil, buildConfigurationFilter: String? = nil, buildConfiguration: String? = nil, certificate: String = "/tmp/AppleIncRootCertificate.cer") { let command = RubyCommand(commandID: "", methodName: "update_project_provisioning", className: nil, args: [RubyCommand.Argument(name: "xcodeproj", value: xcodeproj), RubyCommand.Argument(name: "profile", value: profile), RubyCommand.Argument(name: "target_filter", value: targetFilter), RubyCommand.Argument(name: "build_configuration_filter", value: buildConfigurationFilter), RubyCommand.Argument(name: "build_configuration", value: buildConfiguration), RubyCommand.Argument(name: "certificate", value: certificate)]) _ = runner.executeCommand(command) } func updateProjectTeam(path: String, teamid: String) { let command = RubyCommand(commandID: "", methodName: "update_project_team", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "teamid", value: teamid)]) _ = runner.executeCommand(command) } func updateUrbanAirshipConfiguration(plistPath: String, developmentAppKey: String? = nil, developmentAppSecret: String? = nil, productionAppKey: String? = nil, productionAppSecret: String? = nil, detectProvisioningMode: Bool? = nil) { let command = RubyCommand(commandID: "", methodName: "update_urban_airship_configuration", className: nil, args: [RubyCommand.Argument(name: "plist_path", value: plistPath), RubyCommand.Argument(name: "development_app_key", value: developmentAppKey), RubyCommand.Argument(name: "development_app_secret", value: developmentAppSecret), RubyCommand.Argument(name: "production_app_key", value: productionAppKey), RubyCommand.Argument(name: "production_app_secret", value: productionAppSecret), RubyCommand.Argument(name: "detect_provisioning_mode", value: detectProvisioningMode)]) _ = runner.executeCommand(command) } func updateUrlSchemes(path: String, urlSchemes: String) { let command = RubyCommand(commandID: "", methodName: "update_url_schemes", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "url_schemes", value: urlSchemes)]) _ = runner.executeCommand(command) } func uploadSymbolsToCrashlytics(dsymPath: String = "./spec/fixtures/dSYM/Themoji.dSYM.zip", apiToken: String? = nil, binaryPath: String? = nil, platform: String = "ios", dsymWorkerThreads: Int = 1) { let command = RubyCommand(commandID: "", methodName: "upload_symbols_to_crashlytics", className: nil, args: [RubyCommand.Argument(name: "dsym_path", value: dsymPath), RubyCommand.Argument(name: "api_token", value: apiToken), RubyCommand.Argument(name: "binary_path", value: binaryPath), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "dsym_worker_threads", value: dsymWorkerThreads)]) _ = runner.executeCommand(command) } func uploadSymbolsToSentry(apiHost: String = "https://app.getsentry.com/api/0", apiKey: String? = nil, authToken: String? = nil, orgSlug: String, projectSlug: String, dsymPath: String? = nil, dsymPaths: String? = nil) { let command = RubyCommand(commandID: "", methodName: "upload_symbols_to_sentry", className: nil, args: [RubyCommand.Argument(name: "api_host", value: apiHost), RubyCommand.Argument(name: "api_key", value: apiKey), RubyCommand.Argument(name: "auth_token", value: authToken), RubyCommand.Argument(name: "org_slug", value: orgSlug), RubyCommand.Argument(name: "project_slug", value: projectSlug), RubyCommand.Argument(name: "dsym_path", value: dsymPath), RubyCommand.Argument(name: "dsym_paths", value: dsymPaths)]) _ = runner.executeCommand(command) } func uploadToAppStore(username: String, appIdentifier: String? = nil, app: String, editLive: Bool = false, ipa: String? = nil, pkg: String? = nil, platform: String = "ios", metadataPath: String? = nil, screenshotsPath: String? = nil, skipBinaryUpload: Bool = false, useLiveVersion: Bool = false, skipScreenshots: Bool = false, appVersion: String? = nil, skipMetadata: Bool = false, skipAppVersionUpdate: Bool = false, force: Bool = false, submitForReview: Bool = false, automaticRelease: Bool = false, autoReleaseDate: String? = nil, phasedRelease: Bool = false, priceTier: String? = nil, buildNumber: String? = nil, appRatingConfigPath: String? = nil, submissionInformation: String? = nil, teamId: String? = nil, teamName: String? = nil, devPortalTeamId: String? = nil, devPortalTeamName: String? = nil, itcProvider: String? = nil, overwriteScreenshots: Bool = false, runPrecheckBeforeSubmit: Bool = true, precheckDefaultRuleLevel: String = "warn", appIcon: String? = nil, appleWatchAppIcon: String? = nil, copyright: String? = nil, primaryCategory: String? = nil, secondaryCategory: String? = nil, primaryFirstSubCategory: String? = nil, primarySecondSubCategory: String? = nil, secondaryFirstSubCategory: String? = nil, secondarySecondSubCategory: String? = nil, tradeRepresentativeContactInformation: [String : Any]? = nil, appReviewInformation: [String : Any]? = nil, description: String? = nil, name: String? = nil, subtitle: [String : Any]? = nil, keywords: [String : Any]? = nil, promotionalText: [String : Any]? = nil, releaseNotes: String? = nil, privacyUrl: String? = nil, supportUrl: String? = nil, marketingUrl: String? = nil, languages: [String]? = nil, ignoreLanguageDirectoryValidation: Bool = false, precheckIncludeInAppPurchases: Bool = true) { let command = RubyCommand(commandID: "", methodName: "upload_to_app_store", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "app", value: app), RubyCommand.Argument(name: "edit_live", value: editLive), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "pkg", value: pkg), RubyCommand.Argument(name: "platform", value: platform), RubyCommand.Argument(name: "metadata_path", value: metadataPath), RubyCommand.Argument(name: "screenshots_path", value: screenshotsPath), RubyCommand.Argument(name: "skip_binary_upload", value: skipBinaryUpload), RubyCommand.Argument(name: "use_live_version", value: useLiveVersion), RubyCommand.Argument(name: "skip_screenshots", value: skipScreenshots), RubyCommand.Argument(name: "app_version", value: appVersion), RubyCommand.Argument(name: "skip_metadata", value: skipMetadata), RubyCommand.Argument(name: "skip_app_version_update", value: skipAppVersionUpdate), RubyCommand.Argument(name: "force", value: force), RubyCommand.Argument(name: "submit_for_review", value: submitForReview), RubyCommand.Argument(name: "automatic_release", value: automaticRelease), RubyCommand.Argument(name: "auto_release_date", value: autoReleaseDate), RubyCommand.Argument(name: "phased_release", value: phasedRelease), RubyCommand.Argument(name: "price_tier", value: priceTier), RubyCommand.Argument(name: "build_number", value: buildNumber), RubyCommand.Argument(name: "app_rating_config_path", value: appRatingConfigPath), RubyCommand.Argument(name: "submission_information", value: submissionInformation), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "dev_portal_team_id", value: devPortalTeamId), RubyCommand.Argument(name: "dev_portal_team_name", value: devPortalTeamName), RubyCommand.Argument(name: "itc_provider", value: itcProvider), RubyCommand.Argument(name: "overwrite_screenshots", value: overwriteScreenshots), RubyCommand.Argument(name: "run_precheck_before_submit", value: runPrecheckBeforeSubmit), RubyCommand.Argument(name: "precheck_default_rule_level", value: precheckDefaultRuleLevel), RubyCommand.Argument(name: "app_icon", value: appIcon), RubyCommand.Argument(name: "apple_watch_app_icon", value: appleWatchAppIcon), RubyCommand.Argument(name: "copyright", value: copyright), RubyCommand.Argument(name: "primary_category", value: primaryCategory), RubyCommand.Argument(name: "secondary_category", value: secondaryCategory), RubyCommand.Argument(name: "primary_first_sub_category", value: primaryFirstSubCategory), RubyCommand.Argument(name: "primary_second_sub_category", value: primarySecondSubCategory), RubyCommand.Argument(name: "secondary_first_sub_category", value: secondaryFirstSubCategory), RubyCommand.Argument(name: "secondary_second_sub_category", value: secondarySecondSubCategory), RubyCommand.Argument(name: "trade_representative_contact_information", value: tradeRepresentativeContactInformation), RubyCommand.Argument(name: "app_review_information", value: appReviewInformation), RubyCommand.Argument(name: "description", value: description), RubyCommand.Argument(name: "name", value: name), RubyCommand.Argument(name: "subtitle", value: subtitle), RubyCommand.Argument(name: "keywords", value: keywords), RubyCommand.Argument(name: "promotional_text", value: promotionalText), RubyCommand.Argument(name: "release_notes", value: releaseNotes), RubyCommand.Argument(name: "privacy_url", value: privacyUrl), RubyCommand.Argument(name: "support_url", value: supportUrl), RubyCommand.Argument(name: "marketing_url", value: marketingUrl), RubyCommand.Argument(name: "languages", value: languages), RubyCommand.Argument(name: "ignore_language_directory_validation", value: ignoreLanguageDirectoryValidation), RubyCommand.Argument(name: "precheck_include_in_app_purchases", value: precheckIncludeInAppPurchases)]) _ = runner.executeCommand(command) } func uploadToPlayStore(packageName: String, track: String = "production", rollout: String? = nil, metadataPath: String? = nil, key: String? = nil, issuer: String? = nil, jsonKey: String? = nil, jsonKeyData: String? = nil, apk: String? = nil, apkPaths: [String]? = nil, skipUploadApk: Bool = false, skipUploadMetadata: Bool = false, skipUploadImages: Bool = false, skipUploadScreenshots: Bool = false, trackPromoteTo: String? = nil, validateOnly: Bool = false, mapping: String? = nil, mappingPaths: [String]? = nil, rootUrl: String? = nil, checkSupersededTracks: Bool = false) { let command = RubyCommand(commandID: "", methodName: "upload_to_play_store", className: nil, args: [RubyCommand.Argument(name: "package_name", value: packageName), RubyCommand.Argument(name: "track", value: track), RubyCommand.Argument(name: "rollout", value: rollout), RubyCommand.Argument(name: "metadata_path", value: metadataPath), RubyCommand.Argument(name: "key", value: key), RubyCommand.Argument(name: "issuer", value: issuer), RubyCommand.Argument(name: "json_key", value: jsonKey), RubyCommand.Argument(name: "json_key_data", value: jsonKeyData), RubyCommand.Argument(name: "apk", value: apk), RubyCommand.Argument(name: "apk_paths", value: apkPaths), RubyCommand.Argument(name: "skip_upload_apk", value: skipUploadApk), RubyCommand.Argument(name: "skip_upload_metadata", value: skipUploadMetadata), RubyCommand.Argument(name: "skip_upload_images", value: skipUploadImages), RubyCommand.Argument(name: "skip_upload_screenshots", value: skipUploadScreenshots), RubyCommand.Argument(name: "track_promote_to", value: trackPromoteTo), RubyCommand.Argument(name: "validate_only", value: validateOnly), RubyCommand.Argument(name: "mapping", value: mapping), RubyCommand.Argument(name: "mapping_paths", value: mappingPaths), RubyCommand.Argument(name: "root_url", value: rootUrl), RubyCommand.Argument(name: "check_superseded_tracks", value: checkSupersededTracks)]) _ = runner.executeCommand(command) } func uploadToTestflight(username: String, appIdentifier: String? = nil, appPlatform: String = "ios", ipa: String? = nil, changelog: String? = nil, betaAppDescription: String? = nil, betaAppFeedbackEmail: String? = nil, skipSubmission: Bool = false, skipWaitingForBuildProcessing: Bool = false, updateBuildInfoOnUpload: Bool = false, appleId: String? = nil, distributeExternal: Bool = false, firstName: String? = nil, lastName: String? = nil, email: String? = nil, testersFilePath: String = "./testers.csv", waitProcessingInterval: Int = 30, teamId: String? = nil, teamName: String? = nil, devPortalTeamId: String? = nil, itcProvider: String? = nil, groups: [String]? = nil, waitForUploadedBuild: Bool = false) { let command = RubyCommand(commandID: "", methodName: "upload_to_testflight", className: nil, args: [RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "app_identifier", value: appIdentifier), RubyCommand.Argument(name: "app_platform", value: appPlatform), RubyCommand.Argument(name: "ipa", value: ipa), RubyCommand.Argument(name: "changelog", value: changelog), RubyCommand.Argument(name: "beta_app_description", value: betaAppDescription), RubyCommand.Argument(name: "beta_app_feedback_email", value: betaAppFeedbackEmail), RubyCommand.Argument(name: "skip_submission", value: skipSubmission), RubyCommand.Argument(name: "skip_waiting_for_build_processing", value: skipWaitingForBuildProcessing), RubyCommand.Argument(name: "update_build_info_on_upload", value: updateBuildInfoOnUpload), RubyCommand.Argument(name: "apple_id", value: appleId), RubyCommand.Argument(name: "distribute_external", value: distributeExternal), RubyCommand.Argument(name: "first_name", value: firstName), RubyCommand.Argument(name: "last_name", value: lastName), RubyCommand.Argument(name: "email", value: email), RubyCommand.Argument(name: "testers_file_path", value: testersFilePath), RubyCommand.Argument(name: "wait_processing_interval", value: waitProcessingInterval), RubyCommand.Argument(name: "team_id", value: teamId), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "dev_portal_team_id", value: devPortalTeamId), RubyCommand.Argument(name: "itc_provider", value: itcProvider), RubyCommand.Argument(name: "groups", value: groups), RubyCommand.Argument(name: "wait_for_uploaded_build", value: waitForUploadedBuild)]) _ = runner.executeCommand(command) } func verifyBuild(provisioningType: String? = nil, provisioningUuid: String? = nil, teamIdentifier: String? = nil, teamName: String? = nil, appName: String? = nil, bundleIdentifier: String? = nil, ipaPath: String? = nil) { let command = RubyCommand(commandID: "", methodName: "verify_build", className: nil, args: [RubyCommand.Argument(name: "provisioning_type", value: provisioningType), RubyCommand.Argument(name: "provisioning_uuid", value: provisioningUuid), RubyCommand.Argument(name: "team_identifier", value: teamIdentifier), RubyCommand.Argument(name: "team_name", value: teamName), RubyCommand.Argument(name: "app_name", value: appName), RubyCommand.Argument(name: "bundle_identifier", value: bundleIdentifier), RubyCommand.Argument(name: "ipa_path", value: ipaPath)]) _ = runner.executeCommand(command) } func verifyXcode(xcodePath: String) { let command = RubyCommand(commandID: "", methodName: "verify_xcode", className: nil, args: [RubyCommand.Argument(name: "xcode_path", value: xcodePath)]) _ = runner.executeCommand(command) } func versionBumpPodspec(path: String, bumpType: String = "patch", versionNumber: String? = nil, versionAppendix: String? = nil) { let command = RubyCommand(commandID: "", methodName: "version_bump_podspec", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "bump_type", value: bumpType), RubyCommand.Argument(name: "version_number", value: versionNumber), RubyCommand.Argument(name: "version_appendix", value: versionAppendix)]) _ = runner.executeCommand(command) } func versionGetPodspec(path: String) { let command = RubyCommand(commandID: "", methodName: "version_get_podspec", className: nil, args: [RubyCommand.Argument(name: "path", value: path)]) _ = runner.executeCommand(command) } func xcarchive() { let command = RubyCommand(commandID: "", methodName: "xcarchive", className: nil, args: []) _ = runner.executeCommand(command) } func xcbuild() { let command = RubyCommand(commandID: "", methodName: "xcbuild", className: nil, args: []) _ = runner.executeCommand(command) } func xcclean() { let command = RubyCommand(commandID: "", methodName: "xcclean", className: nil, args: []) _ = runner.executeCommand(command) } func xcexport() { let command = RubyCommand(commandID: "", methodName: "xcexport", className: nil, args: []) _ = runner.executeCommand(command) } @discardableResult func xcodeInstall(version: String, username: String, teamId: String? = nil) -> String { let command = RubyCommand(commandID: "", methodName: "xcode_install", className: nil, args: [RubyCommand.Argument(name: "version", value: version), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "team_id", value: teamId)]) return runner.executeCommand(command) } @discardableResult func xcodeServerGetAssets(host: String, botName: String, integrationNumber: String? = nil, username: String = "", password: String? = nil, targetFolder: String = "./xcs_assets", keepAllAssets: Bool = false, trustSelfSignedCerts: Bool = true) -> [String] { let command = RubyCommand(commandID: "", methodName: "xcode_server_get_assets", className: nil, args: [RubyCommand.Argument(name: "host", value: host), RubyCommand.Argument(name: "bot_name", value: botName), RubyCommand.Argument(name: "integration_number", value: integrationNumber), RubyCommand.Argument(name: "username", value: username), RubyCommand.Argument(name: "password", value: password), RubyCommand.Argument(name: "target_folder", value: targetFolder), RubyCommand.Argument(name: "keep_all_assets", value: keepAllAssets), RubyCommand.Argument(name: "trust_self_signed_certs", value: trustSelfSignedCerts)]) return parseArray(fromString: runner.executeCommand(command)) } func xcodebuild() { let command = RubyCommand(commandID: "", methodName: "xcodebuild", className: nil, args: []) _ = runner.executeCommand(command) } func xcov() { let command = RubyCommand(commandID: "", methodName: "xcov", className: nil, args: []) _ = runner.executeCommand(command) } func xctest() { let command = RubyCommand(commandID: "", methodName: "xctest", className: nil, args: []) _ = runner.executeCommand(command) } func xcversion(version: String) { let command = RubyCommand(commandID: "", methodName: "xcversion", className: nil, args: [RubyCommand.Argument(name: "version", value: version)]) _ = runner.executeCommand(command) } @discardableResult func zip(path: String, outputPath: String? = nil, verbose: Bool = true) -> String { let command = RubyCommand(commandID: "", methodName: "zip", className: nil, args: [RubyCommand.Argument(name: "path", value: path), RubyCommand.Argument(name: "output_path", value: outputPath), RubyCommand.Argument(name: "verbose", value: verbose)]) return runner.executeCommand(command) } // These are all the parsing functions needed to transform our data into the expected types func parseArray(fromString: String, function: String = #function) -> [String] { verbose(message: "parsing an Array from data: \(fromString), from function: \(function)") let potentialArray: String if fromString.count < 2 { potentialArray = "[\(fromString)]" } else { potentialArray = fromString } let array: [String] = try! JSONSerialization.jsonObject(with: potentialArray.data(using: .utf8)!, options: []) as! [String] return array } func parseDictionary(fromString: String, function: String = #function) -> [String : String] { verbose(message: "parsing an Array from data: \(fromString), from function: \(function)") let potentialDictionary: String if fromString.count < 2 { verbose(message: "Dictionary value too small: \(fromString), from function: \(function)") potentialDictionary = "{}" } else { potentialDictionary = fromString } let dictionary: [String : String] = try! JSONSerialization.jsonObject(with: potentialDictionary.data(using: .utf8)!, options: []) as! [String : String] return dictionary } func parseBool(fromString: String, function: String = #function) -> Bool { verbose(message: "parsing a Bool from data: \(fromString), from function: \(function)") return NSString(string: fromString).boolValue } func parseInt(fromString: String, function: String = #function) -> Int { verbose(message: "parsing a Bool from data: \(fromString), from function: \(function)") return NSString(string: fromString).integerValue } let deliverfile: Deliverfile = Deliverfile() let gymfile: Gymfile = Gymfile() let matchfile: Matchfile = Matchfile() let precheckfile: Precheckfile = Precheckfile() let scanfile: Scanfile = Scanfile() let screengrabfile: Screengrabfile = Screengrabfile() let snapshotfile: Snapshotfile = Snapshotfile() // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
c441c2d3d2ebba6ca5e9724194201067
92.232841
218
0.404473
7.194842
false
false
false
false
thammin/RainbowBridge
RainbowBridge/RainbowBridgeController.swift
1
14645
// // RainbowBridgeController.swift // RainbowBridge // // Created by 林 柏楊 on 2015/09/11. // Copyright © 2015年 林 柏楊. All rights reserved. // import WebKit import PeerKit import AudioToolbox import AVFoundation import LocalAuthentication import MultipeerConnectivity class RainbowBridgeController: WKUserContentController { // reference to webView var webView: WKWebView! = nil // some references /// code reader references var captureOutputCallbacks = Array<(String -> ())>() var captureSession: AVCaptureSession? var videoLayer: AVCaptureVideoPreviewLayer? /// sound player references var soundPlayers: [AVAudioPlayer] = [] /** Set the target webView as reference :param: view Target's view */ func setTargetView(view: WKWebView) { self.webView = view } /** Native api wrapper TODO: add parameters as arguments :param: withObject JSON object */ func callNativeApi(withObject object: AnyObject) { if object["wrappedApiName"] as? String != nil { // exeucte Javascript callback if callbackId is passed func cb(returnedValue: String?) { if object["callbackId"] as? String != nil { callback(object["callbackId"]! as! String, returnedValue: returnedValue) } } let wrappedApiName = object["wrappedApiName"]! as! String switch wrappedApiName { case "joinPeerGroup": self._joinPeerGroup(object["peerGroupName"]! as! String, cb: { cb($0) }) case "sendEventToPeerGroup": self._sendEventToPeerGroup(object["event"]! as! String, object: object["object"]! as AnyObject?, cb: { cb($0) }) case "leavePeerGroup": self._leavePeerGroup({ cb($0) }) case "downloadAndCache": self._downloadAndCache(object["url"]! as! String, path: object["path"]! as! String, isOverwrite: object["isOverwrite"]! as! Bool, cb: { cb($0) }) case "clearCache": self._clearCache(object["path"]! as! String, cb: { cb($0) }) case "initializeSound": self._initializeSound(object["file"]! as! String, cb: { cb($0) }) case "disposeSound": self._disposeSound(object["index"]! as! Int, cb: { cb($0) }) case "playSound": self._playSound(object["index"]! as! Int, isRepeat: object["isRepeat"]! as! Int, cb: { cb($0) }) case "scanMetadata": self._scanMetadata(object["metadataTypes"]! as! Array, cb: { cb($0) }) case "playVibration": self._playVibration({ cb($0) }) case "authenticateTouchId": self._authenticateTouchId(reason: object["reason"]! as! String, cb: { cb($0) }) default: print("Invalid wrapped api name") } } } /** Execute Javascript callback :param: id An unique Id that linked with callback :param: returnedValue A String value to be return to Javascript callback */ func callback(id: String, returnedValue: String?) { let evaluateString = "window.rainbowBridge.executeCallback('\(id)', \(returnedValue! as String))" self.webView.evaluateJavaScript(evaluateString, completionHandler: nil) } /// /// _ _ _ _ ___ _ /// | \ | | | | (_) / _ \ (_) /// | \| | __ _| |_ ___ _____ / /_\ \_ __ _ ___ /// | . ` |/ _` | __| \ \ / / _ \ | _ | '_ \| / __| /// | |\ | (_| | |_| |\ V / __/ | | | | |_) | \__ \ /// \_| \_/\__,_|\__|_| \_/ \___| \_| |_/ .__/|_|___/ /// | | /// |_| /** Join a peer group with specified name :param: peerGroupName unique name of the group :param: cb Javascript callback */ func _joinPeerGroup(peerGroupName: String, cb: String -> ()) { // when connecting to a peer PeerKit.onConnecting = { (myPeerId, targetPeerId) -> () in cb("{ type: 'onConnecting', myPeerId: '\(myPeerId.displayName)', targetPeerId: '\(targetPeerId.displayName)'}") } // when connection to a peer had established PeerKit.onConnect = { (myPeerId, targetPeerId) -> () in cb("{ type: 'onConnected', myPeerId: '\(myPeerId.displayName)', targetPeerId: '\(targetPeerId.displayName)'}") } // when connection to a peer had been released PeerKit.onDisconnect = { (myPeerId, targetPeerId) -> () in cb("{ type: 'onDisconnected', myPeerId: '\(myPeerId.displayName)', targetPeerId: '\(targetPeerId.displayName)'}") } // when event received from a peer PeerKit.onEvent = { (targetPeerId, event, object) -> () in do { let jsonData = try NSJSONSerialization.dataWithJSONObject(object!, options: NSJSONWritingOptions.PrettyPrinted) let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String cb("{ type: 'onEvent', targetPeerId: '\(targetPeerId)', event: '\(event)', object: \(jsonString)}") } catch let error as NSError { print(error.localizedDescription) } } PeerKit.transceiver = Transceiver(displayName: PeerKit.myName) PeerKit.transceive(peerGroupName) } /** Send event with optional object to peer group :param: event unique event name :param: object optional object :param: cb Javascript callback */ func _sendEventToPeerGroup(event: String, object: AnyObject?, cb: String -> ()) { let peers = PeerKit.session?.connectedPeers as [MCPeerID]? ?? [] PeerKit.sendEvent(event, object: object, toPeers: peers) let peersJson = peers.map { (let peer) -> String in return peer.displayName } cb("{ connectedPeers: \(peersJson)}") } /** Leave any peer group we had joined :param: cb Javascript callback */ func _leavePeerGroup(cb: String -> ()) { PeerKit.stopTransceiving() cb("true") } /** Download file with specified url and cache to the Application Support Directory :param: url file's url :param: path relative path to be save in Application Support Directory :param: isOverwrite allow to overwrite if same file is exist, disable this attribute will skip the download :param: cb Javascript callback */ func _downloadAndCache(url: String, path: String, isOverwrite: Bool, cb: String -> ()) { let fileManager = NSFileManager.defaultManager() let dir = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true).first let file = dir?.stringByAppendingString(path) // create Application Support directory if not existed if (fileManager.fileExistsAtPath(dir!)) { do { try fileManager.createDirectoryAtPath(dir!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print(error.localizedDescription) } } // skip download if file is already existed if (fileManager.fileExistsAtPath(file!) && !isOverwrite) { cb("{ message: 'The file is already existed.', file: '\(file!)' }") return } let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil) let request = NSURLRequest(URL: NSURL(string: url)!) let downloadTask = session.downloadTaskWithRequest(request, completionHandler: { (tempUrl, res, err) -> Void in do { let data = try NSData(contentsOfURL: tempUrl!, options: NSDataReadingOptions.DataReadingMappedAlways) fileManager.createFileAtPath(file!, contents: data, attributes: nil) } catch let error as NSError { print(error.localizedDescription) } cb("{ message: 'File had been downloaded sucessful.', file: '\(file!)' }") }) downloadTask.resume() } /** Clear the cached file in the Application Support Directory :param: path relative path to be save in Application Support Directory :param: cb Javascript callback */ func _clearCache(path: String, cb: String -> ()) { let fileManager = NSFileManager.defaultManager() let dir = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true).first let file = dir?.stringByAppendingString(path) do { try fileManager.removeItemAtPath(file!) } catch let error as NSError { print(error.localizedDescription) } cb("{ message: 'File had been cleared.', file: '\(file!)' }") } /** Initialize sound with AVAudioPlayer :param: file the full path of cached sound :param: cb Javascript callback */ func _initializeSound(file: String, cb: String -> ()) { do { let player = try AVAudioPlayer.init(contentsOfURL: NSURL.fileURLWithPath(file)) player.prepareToPlay() self.soundPlayers.append(player) } catch let error as NSError { print(error.localizedDescription) } cb("{ index: \(self.soundPlayers.count - 1) }") } /** Dispose sound instance :param: index index of sound :param: cb Javascript callback */ func _disposeSound(index: Int, cb: String -> ()) { self.soundPlayers[index].stop() self.soundPlayers.removeAtIndex(index) cb("true") } /** Play cached sound :param: index index of sound :param: isRepeat play with looping :param: cb Javascript callback */ func _playSound(index: Int, isRepeat: Int, cb: String -> ()) { self.soundPlayers[index].play() self.soundPlayers[index].numberOfLoops = -isRepeat cb("true") } /** Scan specified type of metadata using camera :param: metadataTypes code types :param: cb JAvascript callback */ func _scanMetadata(metadataTypes: [String], cb: String -> ()) { self.captureSession = AVCaptureSession() var backCamera: AVCaptureDevice! for device in AVCaptureDevice.devices() { if device.position == AVCaptureDevicePosition.Back { backCamera = device as! AVCaptureDevice } } do { let videoInput = try AVCaptureDeviceInput(device: backCamera) if self.captureSession?.canAddInput(videoInput) != nil { self.captureSession?.addInput(videoInput) } } catch let error as NSError { print(error.localizedDescription) } let metadataOutput: AVCaptureMetadataOutput! = AVCaptureMetadataOutput() if self.captureSession?.canAddOutput(metadataOutput) != nil { self.captureSession?.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) metadataOutput.metadataObjectTypes = metadataTypes } self.videoLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) self.videoLayer!.frame = self.webView.bounds self.videoLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill self.webView.layer.addSublayer(self.videoLayer!) self.captureOutputCallbacks.append(cb) self.captureSession?.startRunning() } /** Play vibration :param: cb Javascript callback */ func _playVibration(cb: String -> ()) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) cb("true") } /** Touch id authentication :param: reason message to be viewed when authentication prompted up :param: cb Javascript callback */ func _authenticateTouchId(reason reason: String, cb: String -> ()) { let authContext = LAContext() if authContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: nil) { authContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: {(success: Bool, error: NSError?) -> Void in cb(String(stringInterpolationSegment: success)) }) } } } extension RainbowBridgeController: WKScriptMessageHandler { func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if message.body is NSNull { print("Null is not allowed.") return } do { let json = try NSJSONSerialization.JSONObjectWithData(message.body.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) self.callNativeApi(withObject: json) } catch let error as NSError { print(error.localizedDescription) } } } extension RainbowBridgeController: AVCaptureMetadataOutputObjectsDelegate { func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if metadataObjects.count > 0 { let data: AVMetadataMachineReadableCodeObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject self.captureSession?.stopRunning() self.captureSession = nil self.videoLayer?.removeFromSuperlayer() self.videoLayer = nil let jsonString = "{type:'\(data.type)', stringValue:'\(data.stringValue)'}" if self.captureOutputCallbacks.count > 0 { self.captureOutputCallbacks[0](jsonString) // add print to remove the `Expression resolves to an unused function` warning print(self.captureOutputCallbacks.removeAtIndex(0)) } } } }
mit
ec8823454e201c2050ca48f979d7ab15
36.806202
169
0.592139
5.099338
false
false
false
false
OpenLocate/openlocate-ios
Source/LocationService.swift
1
12292
// // LocationService.swift // // Copyright (c) 2017 OpenLocate // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreLocation protocol LocationServiceType { var transmissionInterval: TimeInterval { get set } var isStarted: Bool { get } func start() func stop() func postData(onComplete: ((Bool) -> Void)?) func backgroundFetchLocation(onCompletion: @escaping ((Bool) -> Void)) } private let locationsKey = "locations" final class LocationService: LocationServiceType { let isStartedKey = "OpenLocate_isStarted" let endpointsInfoKey = "OpenLocate_EndpointsInfo" let endpointLastTransmitDate = "lastTransmitDate" let maxNumberOfDaysStored = 10 let maxForegroundLocationUpdateInterval: TimeInterval = 15 * 60.0 // 15 minutes let collectingFieldsConfiguration: CollectingFieldsConfiguration var transmissionInterval: TimeInterval var isStarted: Bool { return UserDefaults.standard.bool(forKey: isStartedKey) } private let locationManager: LocationManagerType private let httpClient: Postable private let locationDataSource: LocationDataSourceType private var advertisingInfo: AdvertisingInfo private let executionQueue: DispatchQueue = DispatchQueue(label: "openlocate.queue.async", qos: .background) private let endpoints: [Configuration.Endpoint] private var isPostingLocations = false private var lastTransmissionDate: Date? private var endpointsInfo: [String: [String: Any]] private let dispatchGroup = DispatchGroup() private var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid init( postable: Postable, locationDataSource: LocationDataSourceType, endpoints: [Configuration.Endpoint], advertisingInfo: AdvertisingInfo, locationManager: LocationManagerType, transmissionInterval: TimeInterval, logConfiguration: CollectingFieldsConfiguration) { httpClient = postable self.locationDataSource = locationDataSource self.locationManager = locationManager self.advertisingInfo = advertisingInfo self.endpoints = endpoints self.transmissionInterval = transmissionInterval self.collectingFieldsConfiguration = logConfiguration if let endpointsInfo = UserDefaults.standard.dictionary(forKey: endpointsInfoKey) as? [String: [String: Any]] { self.endpointsInfo = endpointsInfo } else { self.endpointsInfo = [String: [String: Any]]() } } deinit { NotificationCenter.default.removeObserver(self) } func start() { debugPrint("Location service started for urls : \(endpoints.map({$0.url}))") locationManager.subscribe { [weak self] locations in self?.addUpdatedLocations(locations: locations) } UserDefaults.standard.set(true, forKey: isStartedKey) UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } // swiftlint:disable notification_center_detachment func stop() { locationManager.cancel() locationDataSource.clear() UserDefaults.standard.set(false, forKey: isStartedKey) UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalNever) NotificationCenter.default.removeObserver(self) } func backgroundFetchLocation(onCompletion: @escaping ((Bool) -> Void)) { if let lastKnownLocation = locationManager.lastLocation { addUpdatedLocations(locations: [(location: lastKnownLocation, context: .passive)]) } locationManager.fetchLocation(onCompletion: onCompletion) } } extension LocationService { private func addUpdatedLocations(locations: [(location: CLLocation, context: OpenLocateLocation.Context)]) { self.executionQueue.async { [weak self] in guard let strongSelf = self else { return } let collectingFields = DeviceCollectingFields.configure(with: strongSelf.collectingFieldsConfiguration) let openLocateLocations: [OpenLocateLocation] = locations.map { let info = CollectingFields.Builder(configuration: strongSelf.collectingFieldsConfiguration) .set(location: $0.location) .set(network: NetworkInfo.currentNetworkInfo()) .set(deviceInfo: collectingFields) .build() return OpenLocateLocation(timestamp: $0.location.timestamp, advertisingInfo: strongSelf.advertisingInfo, collectingFields: info, context: $0.context) } strongSelf.locationDataSource.addAll(locations: openLocateLocations) //debugPrint(strongSelf.locationDataSource.all()) strongSelf.postLocationsIfNeeded() } } func postLocationsIfNeeded() { if let earliestLocation = locationDataSource.first(), let createdAt = earliestLocation.createdAt, abs(createdAt.timeIntervalSinceNow) > self.transmissionInterval { if let lastTransmissionDate = self.lastTransmissionDate, abs(lastTransmissionDate.timeIntervalSinceNow) < self.transmissionInterval / 2 { return } DispatchQueue.main.asyncAfter(deadline: .now() + 4.0, execute: { [weak self] in self?.postData() }) } } func postData(onComplete: ((Bool) -> Void)? = nil) { if isPostingLocations == true || endpoints.isEmpty { return } isPostingLocations = true beginBackgroundTask() var isSuccessfull = true let endingDate = Calendar.current.date(byAdding: .second, value: -1, to: Date()) ?? Date() for endpoint in endpoints { dispatchGroup.enter() do { let date = lastKnownTransmissionDate(for: endpoint) let locations = locationDataSource.all(starting: date, ending: endingDate) let params = [locationsKey: locations.map { $0.json }] let requestParameters = URLRequestParamters(url: endpoint.url.absoluteString, params: params, queryParams: nil, additionalHeaders: endpoint.headers) try httpClient.post( parameters: requestParameters, success: { [weak self] _, _ in if let lastLocation = locations.last, let createdAt = lastLocation.createdAt { self?.setLastKnownTransmissionDate(for: endpoint, with: createdAt) } self?.dispatchGroup.leave() }, failure: { [weak self] _, error in debugPrint("failure in posting locations!!! Error: \(error)") isSuccessfull = false self?.dispatchGroup.leave() } ) } catch let error { print(error.localizedDescription) isSuccessfull = false dispatchGroup.leave() } } dispatchGroup.notify(queue: .main) { [weak self] in guard let strongSelf = self else { return } strongSelf.lastTransmissionDate = Date() strongSelf.locationDataSource.clear(before: strongSelf.transmissionDateCutoff()) strongSelf.isPostingLocations = false strongSelf.endBackgroundTask() if let onComplete = onComplete { onComplete(isSuccessfull) } } } private func lastKnownTransmissionDate(for endpoint: Configuration.Endpoint) -> Date { let key = infoKeyForEndpoint(endpoint) if let endpointInfo = endpointsInfo[key], let date = endpointInfo[endpointLastTransmitDate] as? Date, date <= Date() { return date } return Date.distantPast } private func setLastKnownTransmissionDate(for endpoint: Configuration.Endpoint, with date: Date) { let key = infoKeyForEndpoint(endpoint) endpointsInfo[key] = [endpointLastTransmitDate: date] persistEndPointsInfo() } private func transmissionDateCutoff() -> Date { var cutoffDate = Date() for (_, endpointInfo) in endpointsInfo { if let date = endpointInfo[endpointLastTransmitDate] as? Date { if date < cutoffDate { cutoffDate = date } } else { cutoffDate = Date.distantPast } } if let maxCutoffDate = Calendar.current.date(byAdding: .day, value: -maxNumberOfDaysStored, to: Date()), maxCutoffDate > cutoffDate { return maxCutoffDate } return cutoffDate } private func infoKeyForEndpoint(_ endpoint: Configuration.Endpoint) -> String { return endpoint.url.absoluteString.lowercased() } private func persistEndPointsInfo() { UserDefaults.standard.set(endpointsInfo, forKey: endpointsInfoKey) UserDefaults.standard.synchronize() } private func beginBackgroundTask() { backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in self?.endBackgroundTask() } } private func endBackgroundTask() { UIApplication.shared.endBackgroundTask(backgroundTask) backgroundTask = UIBackgroundTaskInvalid } @objc private func applicationDidBecomeActive(notification: NSNotification) { if UIApplication.shared.applicationState == .active { if let lastKnownLocation = locationManager.lastLocation { addUpdatedLocations(locations: [(location: lastKnownLocation, context: .passive)]) if abs(lastKnownLocation.timestamp.timeIntervalSinceNow) > maxForegroundLocationUpdateInterval { locationManager.fetchLocation(onCompletion: { _ in }) } } } } static func isAuthorizationKeysValid() -> Bool { let always = Bundle.main.object(forInfoDictionaryKey: "NSLocationAlwaysUsageDescription") let inUse = Bundle.main.object(forInfoDictionaryKey: "NSLocationWhenInUseUsageDescription") let alwaysAndinUse = Bundle.main.object(forInfoDictionaryKey: "NSLocationAlwaysAndWhenInUseUsageDescription") if #available(iOS 11, *) { return always != nil && inUse != nil && alwaysAndinUse != nil } return always != nil } }
mit
6d119ddf585763a81091b7cf7ee65411
38.146497
119
0.638139
5.546931
false
false
false
false
bolshedvorsky/swift-corelibs-foundation
Foundation/NSString.swift
3
67760
// 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 // import CoreFoundation public typealias unichar = UInt16 extension unichar : ExpressibleByUnicodeScalarLiteral { public typealias UnicodeScalarLiteralType = UnicodeScalar public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) } } /// Returns a localized string, using the main bundle if one is not specified. public func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value: value, table: tableName) } #if os(OSX) || os(iOS) internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC #endif extension NSString { public struct EncodingConversionOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let allowLossy = EncodingConversionOptions(rawValue: 1) public static let externalRepresentation = EncodingConversionOptions(rawValue: 2) internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20) } public struct EnumerationOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let byLines = EnumerationOptions(rawValue: 0) public static let byParagraphs = EnumerationOptions(rawValue: 1) public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2) public static let byWords = EnumerationOptions(rawValue: 3) public static let bySentences = EnumerationOptions(rawValue: 4) public static let reverse = EnumerationOptions(rawValue: 1 << 8) public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9) public static let localized = EnumerationOptions(rawValue: 1 << 10) internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20) } } extension NSString { public struct CompareOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let caseInsensitive = CompareOptions(rawValue: 1) public static let literal = CompareOptions(rawValue: 2) public static let backwards = CompareOptions(rawValue: 4) public static let anchored = CompareOptions(rawValue: 8) public static let numeric = CompareOptions(rawValue: 64) public static let diacriticInsensitive = CompareOptions(rawValue: 128) public static let widthInsensitive = CompareOptions(rawValue: 256) public static let forcedOrdering = CompareOptions(rawValue: 512) public static let regularExpression = CompareOptions(rawValue: 1024) internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags { #if os(OSX) || os(iOS) return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral) #else return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral) #endif } } } internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? { struct local { static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = { let cache = NSCache<NSString, NSRegularExpression>() cache.name = "NSRegularExpressionCache" cache.countLimit = 10 return cache }() } let key = "\(options):\(pattern)" if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) { return regex } do { let regex = try NSRegularExpression(pattern: pattern, options: options) local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject) return regex } catch { } return nil } internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? { let theRange = NSRange(location: 0, length: str.length) var cLength = 0 var used = 0 var options: NSString.EncodingConversionOptions = [] if externalRep { options.formUnion(.externalRepresentation) } if lossy { options.formUnion(.allowLossy) } if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) { if fatalOnError { fatalError("Conversion on encoding failed") } return nil } let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1) if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) { fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation") } buffer.advanced(by: cLength).initialize(to: 0) return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here } internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool { if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */ return false } return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029 } internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool { if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */ return false } return ch == 0x0a || ch == 0x0d || ch == 0x2029 } open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID()) internal var _storage: String open var length: Int { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } return _storage.utf16.count } open func character(at index: Int) -> unichar { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } let start = _storage.utf16.startIndex return _storage.utf16[_storage.utf16.index(start, offsetBy: index)] } public override convenience init() { let characters = Array<unichar>(repeating: 0, count: 1) self.init(characters: characters, length: 0) } internal init(_ string: String) { _storage = string } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") { let str = aDecoder._decodePropertyListForKey("NS.string") as! String self.init(string: str) } else { let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") { guard let buffer = $0 else { return nil } return Data(buffer: buffer) } guard let data = decodedData else { return nil } self.init(data: data, encoding: String.Encoding.utf8.rawValue) } } public required convenience init(string aString: String) { self.init(aString) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSString.self { return self } let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length) getCharacters(characters, range: NSRange(location: 0, length: length)) let result = NSString(characters: characters, length: length) characters.deinitialize(count: length) characters.deallocate() return result } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSString.self || type(of: self) === NSMutableString.self { if let contents = _fastContents { return NSMutableString(characters: contents, length: length) } } let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length) getCharacters(characters, range: NSRange(location: 0, length: length)) let result = NSMutableString(characters: characters, length: length) characters.deinitialize(count: 1) characters.deallocate() return result } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.string") } else { aCoder.encode(self) } } public init(characters: UnsafePointer<unichar>, length: Int) { _storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { _storage = String(describing: value) } public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) { guard let str = CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else { return nil } self.init(string: str._swiftObject) } internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._core.isASCII { return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self) } } return nil } internal var _fastContents: UnsafePointer<UniChar>? { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if !_storage._core.isASCII { return UnsafePointer<UniChar>(_storage._core.startUTF16) } } return nil } internal var _encodingCantBeStoredInEightBitCFString: Bool { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return !_storage._core.isASCII } return false } override open var _cfTypeID: CFTypeID { return CFStringGetTypeID() } open override func isEqual(_ object: Any?) -> Bool { guard let string = (object as? NSString)?._swiftObject else { return false } return self.isEqual(to: string) } open override var description: String { return _swiftObject } open override var hash: Int { return Int(bitPattern:CFStringHashNSString(self._cfObject)) } } extension NSString { public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) { for idx in 0..<range.length { buffer[idx] = character(at: idx + range.location) } } public func substring(from: Int) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return String(_storage.utf16.suffix(from: _storage.utf16.index(_storage.utf16.startIndex, offsetBy: from)))! } else { return substring(with: NSRange(location: from, length: length - from)) } } public func substring(to: Int) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return String(_storage.utf16.prefix(upTo: _storage.utf16.index(_storage.utf16.startIndex, offsetBy: to)))! } else { return substring(with: NSRange(location: 0, length: to)) } } public func substring(with range: NSRange) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { let start = _storage.utf16.startIndex let min = _storage.utf16.index(start, offsetBy: range.location) let max = _storage.utf16.index(start, offsetBy: range.location + range.length) return String(decoding: _storage.utf16[min..<max], as: UTF16.self) } else { let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length) getCharacters(buff, range: range) let result = String(describing: buff) buff.deinitialize(count: 1) buff.deallocate() return result } } public func compare(_ string: String) -> ComparisonResult { return compare(string, options: [], range: NSRange(location: 0, length: length)) } public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult { return compare(string, options: mask, range: NSRange(location: 0, length: length)) } public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult { return compare(string, options: mask, range: compareRange, locale: nil) } public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult { var res: CFComparisonResult if let loc = locale { res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject) } else { res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil) } return ComparisonResult._fromCF(res) } public func caseInsensitiveCompare(_ string: String) -> ComparisonResult { return compare(string, options: .caseInsensitive, range: NSRange(location: 0, length: length)) } public func localizedCompare(_ string: String) -> ComparisonResult { return compare(string, options: [], range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC()) } public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult { return compare(string, options: .caseInsensitive, range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC()) } public func localizedStandardCompare(_ string: String) -> ComparisonResult { return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC()) } public func isEqual(to aString: String) -> Bool { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return _storage == aString } else { return length == aString.length && compare(aString, options: .literal, range: NSRange(location: 0, length: length)) == .orderedSame } } public func hasPrefix(_ str: String) -> Bool { return range(of: str, options: .anchored, range: NSRange(location: 0, length: length)).location != NSNotFound } public func hasSuffix(_ str: String) -> Bool { return range(of: str, options: [.anchored, .backwards], range: NSRange(location: 0, length: length)).location != NSNotFound } public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String { var currentSubstring: CFMutableString? let isLiteral = mask.contains(.literal) var lastMatch = NSRange() let selfLen = length let otherLen = str.length var low = 0 var high = selfLen var probe = (low + high) / 2 if (probe > otherLen) { probe = otherLen // A little heuristic to avoid some extra work } if selfLen == 0 || otherLen == 0 { return "" } var numCharsBuffered = 0 var arrayBuffer = [unichar](repeating: 0, count: 100) let other = str._nsObject return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in // Now do the binary search. Note that the probe value determines the length of the substring to check. while true { let range = NSRange(location: 0, length: isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence if range.length > numCharsBuffered { // Buffer more characters if needed getCharacters(selfChars, range: NSRange(location: numCharsBuffered, length: range.length - numCharsBuffered)) numCharsBuffered = range.length } if currentSubstring == nil { currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull) } else { CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length) } if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSRange(location: 0, length: otherLen)).length != 0 { // Match lastMatch = range low = probe + 1 } else { high = probe } if low >= high { break } probe = (low + high) / 2 } return lastMatch.length != 0 ? substring(with: lastMatch) : "" } } public func contains(_ str: String) -> Bool { return range(of: str, options: [], range: NSRange(location: 0, length: length), locale: nil).location != NSNotFound } public func localizedCaseInsensitiveContains(_ str: String) -> Bool { return range(of: str, options: .caseInsensitive, range: NSRange(location: 0, length: length), locale: Locale.current).location != NSNotFound } public func localizedStandardContains(_ str: String) -> Bool { return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSRange(location: 0, length: length), locale: Locale.current).location != NSNotFound } public func localizedStandardRange(of str: String) -> NSRange { return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSRange(location: 0, length: length), locale: Locale.current) } public func range(of searchString: String) -> NSRange { return range(of: searchString, options: [], range: NSRange(location: 0, length: length), locale: nil) } public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange { return range(of: searchString, options: mask, range: NSRange(location: 0, length: length), locale: nil) } public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange { return range(of: searchString, options: mask, range: searchRange, locale: nil) } internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange { var matchedRange = NSRange(location: NSNotFound, length: 0) let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSRegularExpression.MatchingOptions = mask.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange) } return matchedRange } public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange { let findStrLen = searchString.length let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)") if mask.contains(.regularExpression) { return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale) } if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares return NSRange(location: NSNotFound, length: 0) } var result = CFRange() let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in if let loc = locale { return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep) } else { return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep) } } if res { return NSRange(location: result.location, length: result.length) } else { return NSRange(location: NSNotFound, length: 0) } } public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange { return rangeOfCharacter(from: searchSet, options: [], range: NSRange(location: 0, length: length)) } public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange { return rangeOfCharacter(from: searchSet, options: mask, range: NSRange(location: 0, length: length)) } public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange { let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)") var result = CFRange() let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep) } if res { return NSRange(location: result.location, length: result.length) } else { return NSRange(location: NSNotFound, length: 0) } } public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange { let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster) return NSRange(location: range.location, length: range.length) } public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange { let length = self.length var start: Int var end: Int if range.location == length { start = length } else { start = rangeOfComposedCharacterSequence(at: range.location).location } var endOfRange = NSMaxRange(range) if endOfRange == length { end = length } else { if range.length > 0 { endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range. } end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange)) } return NSRange(location: start, length: end - start) } public func appending(_ aString: String) -> String { return _swiftObject + aString } public var doubleValue: Double { var start: Int = 0 var result = 0.0 let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in result = value } return result } public var floatValue: Float { var start: Int = 0 var result: Float = 0.0 let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in result = value } return result } public var intValue: Int32 { return Scanner(string: _swiftObject).scanInt32() ?? 0 } public var integerValue: Int { let scanner = Scanner(string: _swiftObject) var value: Int = 0 let _ = scanner.scanInt(&value) return value } public var longLongValue: Int64 { return Scanner(string: _swiftObject).scanInt64() ?? 0 } public var boolValue: Bool { let scanner = Scanner(string: _swiftObject) // skip initial whitespace if present let _ = scanner.scanCharactersFromSet(.whitespaces) // scan a single optional '+' or '-' character, followed by zeroes if scanner.scanString("+") == nil { let _ = scanner.scanString("-") } // scan any following zeroes let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0")) return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil } public var uppercased: String { return uppercased(with: nil) } public var lowercased: String { return lowercased(with: nil) } public var capitalized: String { return capitalized(with: nil) } public var localizedUppercase: String { return uppercased(with: Locale.current) } public var localizedLowercase: String { return lowercased(with: Locale.current) } public var localizedCapitalized: String { return capitalized(with: Locale.current) } public func uppercased(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringUppercase(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } public func lowercased(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringLowercase(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } public func capitalized(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) { let len = length var ch: unichar precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)") if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often startPtr?.pointee = 0 endPtr?.pointee = range.length return } /* Find the starting point first */ if let startPtr = startPtr { var start: Int = 0 if range.location == 0 { start = 0 } else { var buf = _NSStringBuffer(string: self, start: range.location, end: len) /* Take care of the special case where start happens to fall right between \r and \n */ ch = buf.currentCharacter buf.rewind() if ch == 0x0a && buf.currentCharacter == 0x0d { buf.rewind() } while true { if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) { start = buf.location + 1 break } else if buf.location <= 0 { start = 0 break } else { buf.rewind() } } startPtr.pointee = start } } if (endPtr != nil || contentsEndPtr != nil) { var endOfContents = 1 var lineSeparatorLength = 1 var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len) /* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */ ch = buf.currentCharacter if ch == 0x0a { endOfContents = buf.location buf.rewind() if buf.currentCharacter == 0x0d { lineSeparatorLength = 2 endOfContents -= 1 } } else { while true { if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) { endOfContents = buf.location /* This is actually end of contentsRange */ buf.advance() /* OK for this to go past the end */ if ch == 0x0d && buf.currentCharacter == 0x0a { lineSeparatorLength = 2 } break } else if buf.location == len { endOfContents = len lineSeparatorLength = 0 break } else { buf.advance() ch = buf.currentCharacter } } } contentsEndPtr?.pointee = endOfContents endPtr?.pointee = endOfContents + lineSeparatorLength } } public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) { _getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true) } public func lineRange(for range: NSRange) -> NSRange { var start = 0 var lineEnd = 0 getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range) return NSRange(location: start, length: lineEnd - start) } public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) { _getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false) } public func paragraphRange(for range: NSRange) -> NSRange { var start = 0 var parEnd = 0 getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range) return NSRange(location: start, length: parEnd - start) } public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateSubstrings(in: NSRange(location: 0, length: length), options:.byLines) { substr, substrRange, enclosingRange, stop in block(substr!, stop) } } public var utf8String: UnsafePointer<Int8>? { return _bytesInEncoding(self, String.Encoding.utf8, false, false, false) } public var fastestEncoding: UInt { return String.Encoding.unicode.rawValue } public var smallestEncoding: UInt { if canBeConverted(to: String.Encoding.ascii.rawValue) { return String.Encoding.ascii.rawValue } return String.Encoding.unicode.rawValue } public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? { let len = length var reqSize = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) if !CFStringIsEncodingAvailable(cfStringEncoding) { return nil } let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize) if convertedLen != len { return nil // Not able to do it all... } if 0 < reqSize { var data = Data(count: reqSize) data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen { return reqSize } else { fatalError("didn't convert all characters") } } return data } return Data() } public func data(using encoding: UInt) -> Data? { return data(using: encoding, allowLossyConversion: false) } public func canBeConverted(to encoding: UInt) -> Bool { if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue { return true } return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length } public func cString(using encoding: UInt) -> UnsafePointer<Int8>? { return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false) } public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool { var used = 0 if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._core.isASCII { used = min(self.length, maxBufferCount - 1) _storage._core.startASCII.withMemoryRebound(to: Int8.self, capacity: used) { buffer.moveAssign(from: $0, count: used) } buffer.advanced(by: used).initialize(to: 0) return true } } if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSRange(location: 0, length: self.length), remaining: nil) { buffer.advanced(by: used).initialize(to: 0) return true } return false } public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool { var totalBytesWritten = 0 var numCharsProcessed = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) var result = true if length > 0 { if CFStringIsEncodingAvailable(cfStringEncoding) { let lossyOk = options.contains(.allowLossy) let externalRep = options.contains(.externalRepresentation) let failOnPartial = options.contains(.failOnPartialEncodingConversion) let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount) numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten) if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 { result = false } } else { result = false /* ??? Need other encodings */ } } usedBufferCount?.pointee = totalBytesWritten leftover?.pointee = NSRange(location: range.location + numCharsProcessed, length: range.length - numCharsProcessed) return result } public func maximumLengthOfBytes(using enc: UInt) -> Int { let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc) let result = CFStringGetMaximumSizeForEncoding(length, cfEnc) return result == kCFNotFound ? 0 : result } public func lengthOfBytes(using enc: UInt) -> Int { let len = length var numBytes: CFIndex = 0 let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc) let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes) return convertedLen != len ? 0 : numBytes } open class var availableStringEncodings: UnsafePointer<UInt> { struct once { static let encodings: UnsafePointer<UInt> = { let cfEncodings = CFStringGetListOfAvailableEncodings()! var idx = 0 var numEncodings = 0 while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId { idx += 1 numEncodings += 1 } let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1) theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator numEncodings -= 1 while numEncodings >= 0 { theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee) numEncodings -= 1 } return UnsafePointer<UInt>(theEncodingList) }() } return once.encodings } open class func localizedName(of encoding: UInt) -> String { if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) { // TODO: read the localized version from the Foundation "bundle" return theString._swiftObject } return "" } open class var defaultCStringEncoding: UInt { return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding()) } open var decomposedStringWithCanonicalMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormD) return string._swiftObject } open var precomposedStringWithCanonicalMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormC) return string._swiftObject } open var decomposedStringWithCompatibilityMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormKD) return string._swiftObject } open var precomposedStringWithCompatibilityMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormKC) return string._swiftObject } open func components(separatedBy separator: String) -> [String] { let len = length var lrange = range(of: separator, options: [], range: NSRange(location: 0, length: len)) if lrange.length == 0 { return [_swiftObject] } else { var array = [String]() var srange = NSRange(location: 0, length: len) while true { let trange = NSRange(location: srange.location, length: lrange.location - srange.location) array.append(substring(with: trange)) srange.location = lrange.location + lrange.length srange.length = len - srange.location lrange = range(of: separator, options: [], range: srange) if lrange.length == 0 { break } } array.append(substring(with: srange)) return array } } open func components(separatedBy separator: CharacterSet) -> [String] { let len = length var range = rangeOfCharacter(from: separator, options: [], range: NSRange(location: 0, length: len)) if range.length == 0 { return [_swiftObject] } else { var array = [String]() var srange = NSRange(location: 0, length: len) while true { let trange = NSRange(location: srange.location, length: range.location - srange.location) array.append(substring(with: trange)) srange.location = range.location + range.length srange.length = len - srange.location range = rangeOfCharacter(from: separator, options: [], range: srange) if range.length == 0 { break } } array.append(substring(with: srange)) return array } } open func trimmingCharacters(in set: CharacterSet) -> String { let len = length var buf = _NSStringBuffer(string: self, start: 0, end: len) while !buf.isAtEnd, let character = UnicodeScalar(buf.currentCharacter), set.contains(character) { buf.advance() } let startOfNonTrimmedRange = buf.location // This points at the first char not in the set if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line. return "" } else if startOfNonTrimmedRange < len - 1 { buf.location = len - 1 while let character = UnicodeScalar(buf.currentCharacter), set.contains(character), buf.location >= startOfNonTrimmedRange { buf.rewind() } let endOfNonTrimmedRange = buf.location return substring(with: NSRange(location: startOfNonTrimmedRange, length: endOfNonTrimmedRange + 1 - startOfNonTrimmedRange)) } else { return substring(with: NSRange(location: startOfNonTrimmedRange, length: 1)) } } open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String { let len = length if newLength <= len { // The simple cases (truncation) return newLength == len ? _swiftObject : substring(with: NSRange(location: 0, length: newLength)) } let padLen = padString.length if padLen < 1 { fatalError("empty pad string") } if padIndex >= padLen { fatalError("out of range padIndex") } let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)! CFStringPad(mStr, padString._cfObject, newLength, padIndex) return mStr._swiftObject } open func folding(options: CompareOptions = [], locale: Locale?) -> String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringFold(string, options._cfValue(), locale?._cfObject) return string._swiftObject } internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String { let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement) } return "" } open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String { if options.contains(.regularExpression) { return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange) } let str = mutableCopy(with: nil) as! NSMutableString if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 { return _swiftObject } else { return str._swiftObject } } open func replacingOccurrences(of target: String, with replacement: String) -> String { return replacingOccurrences(of: target, with: replacement, options: [], range: NSRange(location: 0, length: length)) } open func replacingCharacters(in range: NSRange, with replacement: String) -> String { let str = mutableCopy(with: nil) as! NSMutableString str.replaceCharacters(in: range, with: replacement) return str._swiftObject } open func applyingTransform(_ transform: String, reverse: Bool) -> String? { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, _cfObject) if (CFStringTransform(string, nil, transform._cfObject, reverse)) { return string._swiftObject } else { return nil } } internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws { let length = self.length var numBytes = 0 let theRange = NSRange(location: 0, length: length) if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [ NSURLErrorKey: dest, ]) } var mData = Data(count: numBytes) // The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?) var used = 0 // This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers. try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [ NSURLErrorKey: dest, ]) } } data = mData } internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws { var data = Data() try _getExternalRepresentation(&data, url, enc) try data.write(to: url, options: useAuxiliaryFile ? .atomic : []) } open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { try _writeTo(url, useAuxiliaryFile, enc) } open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc) } public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // ignore the no-copy-ness self.init(characters: characters, length: length) if freeBuffer { // cant take a hint here... free(UnsafeMutableRawPointer(characters)) } } public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) { let count = Int(strlen(nullTerminatedCString)) if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, { let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: count) return String._fromCodeUnitSequence(UTF8.self, input: buffer) }) as String? { self.init(str) } else { return nil } } public convenience init(format: String, arguments argList: CVaListPointer) { let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)! self.init(str._swiftObject) } public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) { let str: CFString if let loc = locale { if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self { str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList) } else { fatalError("locale parameter must be a NSLocale or a NSDictionary") } } else { str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList) } self.init(str._swiftObject) } public convenience init(format: NSString, _ args: CVarArg...) { let str = withVaList(args) { (vaPtr) -> CFString? in CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr) }! self.init(str._swiftObject) } public convenience init?(data: Data, encoding: UInt) { if data.isEmpty { self.init("") } else { guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true) }) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } } public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) { let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len) guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // just copy for now since the internal storage will be a copy anyhow self.init(bytes: bytes, length: len, encoding: encoding) if freeBuffer { // dont take the hint free(bytes) } } public convenience init(contentsOf url: URL, encoding enc: UInt) throws { let readResult = try NSData(contentsOf: url, options: []) let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length) guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to bridge CFString to String." ]) } } public convenience init(contentsOfFile path: String, encoding enc: UInt) throws { try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc) } public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws { let readResult = try NSData(contentsOf: url, options:[]) let encoding: UInt let offset: Int let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity:readResult.length) if readResult.length >= 4 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE && bytePtr[2] == 0x00 && bytePtr[3] == 0x00 { encoding = String.Encoding.utf32LittleEndian.rawValue offset = 4 } else if readResult.length >= 2 && bytePtr[0] == 0xFE && bytePtr[1] == 0xFF { encoding = String.Encoding.utf16BigEndian.rawValue offset = 2 } else if readResult.length >= 2 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE { encoding = String.Encoding.utf16LittleEndian.rawValue offset = 2 } else if readResult.length >= 4 && bytePtr[0] == 0x00 && bytePtr[1] == 0x00 && bytePtr[2] == 0xFE && bytePtr[3] == 0xFF { encoding = String.Encoding.utf32BigEndian.rawValue offset = 4 } else { //Need to work on more conditions. This should be the default encoding = String.Encoding.utf8.rawValue offset = 0 } enc?.pointee = encoding // Since the encoding being passed includes the byte order the BOM wont be checked or skipped, so pass offset to // manually skip the BOM header. guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr + offset, readResult.length - offset, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to bridge CFString to String." ]) } } public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws { try self.init(contentsOf: URL(fileURLWithPath: path), usedEncoding: enc) } } extension NSString : ExpressibleByStringLiteral { } open class NSMutableString : NSString { open func replaceCharacters(in range: NSRange, with aString: String) { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } let start = _storage.utf16.startIndex let min = _storage.utf16.index(start, offsetBy: range.location).samePosition(in: _storage)! let max = _storage.utf16.index(start, offsetBy: range.location + range.length).samePosition(in: _storage)! _storage.replaceSubrange(min..<max, with: aString) } public required override init(characters: UnsafePointer<unichar>, length: Int) { super.init(characters: characters, length: length) } public required init(capacity: Int) { super.init(characters: [], length: 0) } public convenience required init?(coder aDecoder: NSCoder) { guard let str = NSString(coder: aDecoder) else { return nil } self.init(string: String._unconditionallyBridgeFromObjectiveC(str)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { if value.hasPointerRepresentation { super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.utf8CodeUnitCount)))) } else { var uintValue = value.unicodeScalar.value super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1))) } } public required init(string aString: String) { super.init(aString) } internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) { if type(of: self) == NSMutableString.self { _storage.append(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } else { replaceCharacters(in: NSRange(location: self.length, length: 0), with: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } } internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) { if type(of: self) == NSMutableString.self { _storage.append(String(cString: characters)) } } } extension NSMutableString { public func insert(_ aString: String, at loc: Int) { replaceCharacters(in: NSRange(location: loc, length: 0), with: aString) } public func deleteCharacters(in range: NSRange) { replaceCharacters(in: range, with: "") } public func append(_ aString: String) { replaceCharacters(in: NSRange(location: length, length: 0), with: aString) } public func setString(_ aString: String) { replaceCharacters(in: NSRange(location: 0, length: length), with: aString) } internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int { let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement) } return 0 } public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int { let backwards = options.contains(.backwards) let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds") if options.contains(.regularExpression) { return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange) } if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) { let numOccurrences = CFArrayGetCount(findResults) for cnt in 0..<numOccurrences { let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1) replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement) } return numOccurrences } else { return 0 } } public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool { var cfRange = CFRangeMake(range.location, range.length) return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) { resultingRange?.pointee.location = rangep.pointee.location resultingRange?.pointee.length = rangep.pointee.length return true } return false } } } extension String { // this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters internal var length: Int { return utf16.count } } extension NSString : _CFBridgeable, _SwiftBridgeable { typealias SwiftType = String internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) } internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) } } extension NSMutableString { internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) } } extension CFString : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSString typealias SwiftType = String internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) } internal var _swiftObject: String { return _nsObject._swiftObject } } extension String : _NSBridgeable, _CFBridgeable { typealias NSType = NSString typealias CFType = CFString internal var _nsObject: NSType { return _bridgeToObjectiveC() } internal var _cfObject: CFType { return _nsObject._cfObject } } #if !(os(OSX) || os(iOS)) extension String { public func hasPrefix(_ prefix: String) -> Bool { if prefix.isEmpty { return true } let cfstring = self._cfObject let range = CFRangeMake(0, CFStringGetLength(cfstring)) let opts = CFStringCompareFlags( kCFCompareAnchored | kCFCompareNonliteral) return CFStringFindWithOptions(cfstring, prefix._cfObject, range, opts, nil) } public func hasSuffix(_ suffix: String) -> Bool { if suffix.isEmpty { return true } let cfstring = self._cfObject let range = CFRangeMake(0, CFStringGetLength(cfstring)) let opts = CFStringCompareFlags( kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral) return CFStringFindWithOptions(cfstring, suffix._cfObject, range, opts, nil) } } #endif extension NSString : _StructTypeBridgeable { public typealias _StructType = String public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
apache-2.0
9e5725417e858eaa3ec260daa613d63a
43.631094
274
0.637919
5.12869
false
false
false
false
feighter09/Cloud9
SoundCloud Pro/Collective.swift
1
981
// // Collective.swift // SoundCloud Pro // // Created by Austin Feight on 8/23/15. // Copyright © 2015 Lost in Flight. All rights reserved. // import SwiftyJSON class Collective { let id: Int let name: String let collectiveDescription: String let collectiveShortDescription: String init(id: Int, name: String, collectiveDescription: String, collectiveShortDescription: String) { self.id = id self.name = name self.collectiveDescription = collectiveDescription self.collectiveShortDescription = collectiveShortDescription } convenience init(json: JSON) { let id = json["id"].int! let name = json["name"].string! let collectiveDescription = json["description"].string! let collectiveShortDescription = json["short_description"].string! self.init(id: id, name: name, collectiveDescription: collectiveDescription, collectiveShortDescription: collectiveShortDescription) } }
lgpl-3.0
12458ad2a47d3bb7285e76871467c212
25.486486
96
0.70102
4.242424
false
false
false
false
yanagiba/swift-lint
Tests/RuleTests/RemoveGetForReadOnlyComputedPropertyRuleTests.swift
2
4062
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import Lint class RemoveGetForReadOnlyComputedPropertyRuleTests : XCTestCase { func testProperties() { let rule = RemoveGetForReadOnlyComputedPropertyRule() XCTAssertEqual(rule.identifier, "remove_get_for_readonly_computed_property") XCTAssertEqual(rule.name, "Remove Get For Read-Only Computed Property") XCTAssertEqual(rule.fileName, "RemoveGetForReadOnlyComputedPropertyRule.swift") XCTAssertEqual(rule.description, """ A computed property with a getter but no setter is known as a *read-only computed property*. You can simplify the declaration of a read-only computed property by removing the get keyword and its braces. """) XCTAssertEqual(rule.examples?.count, 1) XCTAssertEqual(rule.examples?[0], """ var foo: Int { get { return 1 } } // var foo: Int { // return 1 // } """) XCTAssertNil(rule.thresholds) XCTAssertNil(rule.additionalDocument) XCTAssertEqual(rule.severity, .minor) XCTAssertEqual(rule.category, .badPractice) } func testNotReadOnlyComputedProperty() { let issues = "var i = 1; var j: Int { get { return i } set { i = newValue } }" .inspect(withRule: RemoveGetForReadOnlyComputedPropertyRule()) XCTAssertTrue(issues.isEmpty) } func testReadOnlyComputedPropertyWithoutGet() { let issues = "var i = 1; var j: Int { return i }" .inspect(withRule: RemoveGetForReadOnlyComputedPropertyRule()) XCTAssertTrue(issues.isEmpty) } func testReadOnlyComputedPropertyWithGet() { let issues = "var i: Int { get { return 0 } }" .inspect(withRule: RemoveGetForReadOnlyComputedPropertyRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "remove_get_for_readonly_computed_property") XCTAssertEqual(issue.description, "read-only computed property `i` can be simplified by removing the `get` keyword and its braces") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .minor) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 1) XCTAssertEqual(range.start.column, 1) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 1) XCTAssertEqual(range.end.column, 32) guard let correction = issue.correction, correction.suggestions.count == 1 else { XCTFail("Failed in getting a suggestion.") return } let suggestion = correction.suggestions[0] XCTAssertEqual(suggestion, """ var i: Int { return 0 } """) } func testReadOnlyComputedPropertyWithGetAndAttributesOrModifier() { let issues = "var i: Int { @foo get { return 0 } }; var j: Int { mutating get { return 1 } }" .inspect(withRule: RemoveGetForReadOnlyComputedPropertyRule()) XCTAssertTrue(issues.isEmpty) } static var allTests = [ ("testProperties", testProperties), ("testNotReadOnlyComputedProperty", testNotReadOnlyComputedProperty), ("testReadOnlyComputedPropertyWithoutGet", testReadOnlyComputedPropertyWithoutGet), ("testReadOnlyComputedPropertyWithGet", testReadOnlyComputedPropertyWithGet), ("testReadOnlyComputedPropertyWithGetAndAttributesOrModifier", testReadOnlyComputedPropertyWithGetAndAttributesOrModifier), ] }
apache-2.0
98cbb08b21b1651c6b455e5772fd5780
36.611111
103
0.718858
4.595023
false
true
false
false
kildevaeld/DataBinding
Pod/Classes/UIViewController+DataBinding.swift
1
1632
// // UIViewController+DataBinding.swift // Pods // // Created by Rasmus Kildevæld on 21/06/15. // // import Foundation import UIKit import JRSwizzle extension UIViewController { public var didPush: Bool { let p: AnyObject! = objc_getAssociatedObject(self, &kDidPushKey); if p == nil { return false } let i = p as! Int return i == 1 ? true : false } public func presentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() ->Void)?, withData:AnyObject? ) { self.presentViewController(viewControllerToPresent, animated: flag) { () -> Void in if let vc = viewControllerToPresent as? FADataRepresentationProtocol { vc.arrangeWithData(withData as! NSObject) } } } func swizzled_presentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { objc_setAssociatedObject(self, &kDidPushKey, 1, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)); self.swizzled_presentViewController(viewControllerToPresent, animated: flag, completion: completion) //objc_setAssociatedObject(self, "fa_data_representation_push", 0, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)); } static func swizzle () { self.jr_swizzleMethod("presentViewController:animated:completion:", withMethod: "swizzled_presentViewController:animated:completion:", error: nil) } }
mit
500d63c590ef8317bd46ac157e406199
31.64
154
0.641937
5.128931
false
false
false
false
DarrenKong/firefox-ios
XCUITests/NavigationTest.swift
1
12249
/* 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 XCTest let website_1 = ["url": "www.mozilla.org", "label": "Internet for people, not profit — Mozilla", "value": "mozilla.org"] let website_2 = ["url": "www.example.com", "label": "Example", "value": "example"] let urlAddons = "addons.mozilla.org" let urlGoogle = "www.google.com" let requestMobileSiteLabel = "Request Mobile Site" let requestDesktopSiteLabel = "Request Desktop Site" class NavigationTest: BaseTestCase { func testNavigation() { navigator.goto(URLBarOpen) let urlPlaceholder = "Search or enter address" XCTAssert(app.textFields["url"].exists) let defaultValuePlaceholder = app.textFields["url"].placeholderValue! // Check the url placeholder text and that the back and forward buttons are disabled XCTAssert(urlPlaceholder == defaultValuePlaceholder) if iPad() { app.buttons["goBack"].tap() XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled) XCTAssertFalse(app.buttons["Forward"].isEnabled) app.textFields["url"].tap() } else { XCTAssertFalse(app.buttons["TabToolbar.backButton"].isEnabled) XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled) } // Once an url has been open, the back button is enabled but not the forward button navigator.openURL(website_1["url"]!) waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: website_1["value"]!) if iPad() { XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled) XCTAssertFalse(app.buttons["Forward"].isEnabled) } else { XCTAssertTrue(app.buttons["TabToolbar.backButton"].isEnabled) XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled) } // Once a second url is open, back button is enabled but not the forward one till we go back to url_1 navigator.openURL(website_2["url"]!) waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: website_2["value"]!) if iPad() { XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled) XCTAssertFalse(app.buttons["Forward"].isEnabled) // Go back to previous visited web site app.buttons["URLBarView.backButton"].tap() } else { XCTAssertTrue(app.buttons["TabToolbar.backButton"].isEnabled) XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled) // Go back to previous visited web site app.buttons["TabToolbar.backButton"].tap() } waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: website_1["value"]!) if iPad() { app.buttons["Forward"].tap() } else { // Go forward to next visited web site app.buttons["TabToolbar.forwardButton"].tap() } waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: website_2["value"]!) } func testTapSignInShowsFxAFromTour() { // Open FxAccount from tour option in settings menu and go throughout all the screens there navigator.goto(Intro_FxASignin) checkFirefoxSyncScreenShown() // Go back to NewTabScreen navigator.goto(HomePanelsScreen) waitforExistence(app.buttons["HomePanels.TopSites"]) } func testTapSigninShowsFxAFromSettings() { navigator.goto(SettingsScreen) // Open FxAccount from settings menu and check the Sign in to Firefox scren let signInToFirefoxStaticText = app.tables["AppSettingsTableViewController.tableView"].staticTexts["Sign in to Sync"] signInToFirefoxStaticText.tap() checkFirefoxSyncScreenShown() // After that it is possible to go back to Settings let settingsButton = app.navigationBars["Client.FxAContentView"].buttons["Settings"] settingsButton.tap() } func testTapSignInShowsFxAFromRemoteTabPanel() { navigator.goto(HomePanel_TopSites) // Open FxAccount from remote tab panel and check the Sign in to Firefox scren navigator.goto(HomePanel_History) XCTAssertTrue(app.tables["History List"].staticTexts["Synced Devices"].isEnabled) app.tables["History List"].staticTexts["Synced Devices"].tap() app.tables.buttons["Sign in"].tap() checkFirefoxSyncScreenShown() app.navigationBars["Client.FxAContentView"].buttons["Done"].tap() navigator.nowAt(HomePanel_History) } private func checkFirefoxSyncScreenShown() { waitforExistence(app.webViews.staticTexts["Sign in"]) XCTAssertTrue(app.webViews.textFields["Email"].exists) XCTAssertTrue(app.webViews.secureTextFields["Password"].exists) XCTAssertTrue(app.webViews.buttons["Sign in"].exists) } func testScrollsToTopWithMultipleTabs() { navigator.goto(TabTray) navigator.openURL(website_1["url"]!) waitForValueContains(app.textFields["url"], value: website_1["value"]!) // Element at the TOP. TBChanged once the web page is correclty shown let topElement = app.webViews.staticTexts["The new"] // Element at the BOTTOM let bottomElement = app.webViews.links.staticTexts["Contact Us"] // Scroll to bottom bottomElement.tap() waitUntilPageLoad() if iPad() { app.buttons["URLBarView.backButton"].tap() } else { app.buttons["TabToolbar.backButton"].tap() } waitUntilPageLoad() // Scroll to top topElement.tap() waitforExistence(topElement) } private func checkMobileView() { let mobileViewElement = app.webViews.links.staticTexts["Use precise location"] waitforExistence(mobileViewElement) XCTAssertTrue (mobileViewElement.exists, "Mobile view is not available") } private func checkDesktopView() { let desktopViewElement = app.webViews.links.staticTexts["About Google"] waitforExistence(desktopViewElement) XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available") } private func clearData() { navigator.performAction(Action.AcceptClearPrivateData) navigator.goto(NewTabScreen) } func testToggleBetweenMobileAndDesktopSiteFromSite() { clearData() let goToDesktopFromMobile = app.webViews.links.staticTexts["View classic desktop site"] // Open URL by default in mobile view. This web site works changing views using their links not with the menu options navigator.openURL(urlAddons, waitForLoading: false) waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: urlAddons) waitforExistence(goToDesktopFromMobile) // From the website go to Desktop view goToDesktopFromMobile.tap() waitUntilPageLoad() let desktopViewElement = app.webViews.links.staticTexts["View the new site"] waitforExistence(desktopViewElement) XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available") // From the website go back to Mobile view app.webViews.links.staticTexts["View the new site"].tap() waitUntilPageLoad() let mobileViewElement = app.webViews.links.staticTexts["View classic desktop site"] waitforExistence(mobileViewElement) XCTAssertTrue (mobileViewElement.exists, "Mobile view is not available") } func testToggleBetweenMobileAndDesktopSiteFromMenu() { clearData() navigator.openURL(urlGoogle) waitUntilPageLoad() waitForValueContains(app.textFields["url"], value: "google") // Mobile view by default, desktop view should be available navigator.browserPerformAction(.toggleDesktopOption) checkDesktopSite() checkDesktopView() // From desktop view it is posible to change to mobile view again navigator.nowAt(BrowserTab) navigator.browserPerformAction(.toggleDesktopOption) checkMobileSite() checkMobileView() } private func checkMobileSite() { app.buttons["TabLocationView.pageOptionsButton"].tap() waitforExistence(app.tables.cells["menu-RequestDesktopSite"].staticTexts[requestDesktopSiteLabel]) navigator.goto(BrowserTab) } private func checkDesktopSite() { app.buttons["TabLocationView.pageOptionsButton"].tap() waitforExistence(app.tables.cells["menu-RequestDesktopSite"].staticTexts[requestMobileSiteLabel]) navigator.goto(BrowserTab) } func testNavigationPreservesDesktopSiteOnSameHost() { clearData() navigator.openURL(urlGoogle) waitUntilPageLoad() // Mobile view by default, desktop view should be available navigator.browserPerformAction(.toggleDesktopOption) waitforNoExistence(app.tables["Context Menu"]) waitUntilPageLoad() checkDesktopView() // Select any link to navigate to another site and check if the view is kept in desktop view waitforExistence(app.webViews.links["Images"]) app.webViews.links["Images"].tap() // About Google appear on desktop view but not in mobile view waitforExistence(app.webViews.links["About Google"]) } func testReloadPreservesMobileOrDesktopSite() { clearData() navigator.openURL(urlGoogle) waitUntilPageLoad() // Mobile view by default, desktop view should be available navigator.browserPerformAction(.toggleDesktopOption) waitUntilPageLoad() // After reloading a website the desktop view should be kept if iPad() { app.buttons["Reload"].tap() } else { app.buttons["TabToolbar.stopReloadButton"].tap() } waitForValueContains(app.textFields["url"], value: "google") waitUntilPageLoad() checkDesktopView() // From desktop view it is posible to change to mobile view again navigator.nowAt(BrowserTab) navigator.browserPerformAction(.toggleDesktopOption) waitUntilPageLoad() // After reloading a website the mobile view should be kept if iPad() { app.buttons["Reload"].tap() } else { app.buttons["TabToolbar.stopReloadButton"].tap() } checkMobileView() } /* Disable test due to bug 1346157, the desktop view is not kept after going back and forward func testBackForwardNavigationRestoresMobileOrDesktopSite() { clearData() let desktopViewElement = app.webViews.links.staticTexts["Mobile"] // Open first url and keep it in mobile view navigator.openURL(urlGoogle) waitForValueContains(app.textFields["url"], value: urlGoogle) checkMobileView() // Open a second url and change it to desktop view navigator.openURL("www.linkedin.com") navigator.goto(PageOptionsMenu) waitforExistence(app.tables.cells["menu-RequestDesktopSite"].staticTexts[requestDesktopSiteLabel]) app.tables.cells["menu-RequestDesktopSite"].tap() waitforExistence(desktopViewElement) XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available") // Go back to first url and check that the view is still mobile view app.buttons["TabToolbar.backButton"].tap() waitForValueContains(app.textFields["url"], value: urlGoogle) checkMobileView() // Go forward to second url and check that the view is still desktop view app.buttons["TabToolbar.forwardButton"].tap() waitForValueContains(app.textFields["url"], value: "www.linkedin.com") waitforExistence(desktopViewElement) XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available after coming from another site in mobile view") } */ }
mpl-2.0
0037ae50bb643da32d55e7446955e50f
40.375
128
0.671103
5.109303
false
false
false
false
matthewcheok/JSONCodable
JSONCodableTests/PropertyItem.swift
1
1109
// // PropertyItem.swift // JSONCodable // // Created by Richard Fox on 6/19/16. // // import JSONCodable struct PropertyItem { let name: String let long: Double let lat: Double let rel: String let type: String } extension PropertyItem: JSONDecodable { init(object: JSONObject) throws { let decoder = JSONDecoder(object: object) rel = try decoder.decode("rel") type = try decoder.decode("class") name = try decoder.decode("properties.name") long = try decoder.decode("properties.location.coord.long") lat = try decoder.decode("properties.location.coord.lat") } } extension PropertyItem: JSONEncodable { func toJSON() throws -> Any { return try JSONEncoder.create { (encoder) -> Void in try encoder.encode(rel, key: "rel") try encoder.encode(type, key: "class") try encoder.encode(name, key: "properties.name") try encoder.encode(long, key: "properties.location.coord.long") try encoder.encode(lat, key: "properties.location.coord.lat") } } }
mit
724ed36083fc74db45acb405d40d91db
26.725
75
0.629396
3.97491
false
false
false
false
Game-of-whales/GOW-SDK-IOS
Example/test/AdView.swift
1
3681
// // AdView.swift // test // // Created by Denis Sachkov on 08.11.18. // Copyright © 2018 GameOfWhales. All rights reserved. // import UIKit import GameOfWhales class AdView : UIViewController, GWDelegate { func canStart(_ experiment: GWExperiment) -> Bool { return false; } func onExperimentEnded(_ experiment: GWExperiment) { } @IBOutlet var adstate:UILabel! @IBOutlet var foparTitle:UILabel! @IBOutlet var adload:UIButton! @IBOutlet var adshow:UIButton! @IBOutlet var fo_par_toggle:UIButton! @IBOutlet var futureOffersList:UILabel! var isFOShowing:Bool = true; var foList:String = ""; override func viewDidLoad() { super.viewDidLoad() GW.add(self); isFOShowing = true; foList = "" futureOffersList.text = "" } override func didReceiveMemoryWarning() { GW.remove(self) } override func viewDidDisappear(_ animated: Bool) { //remove self from delegates } @IBAction func LoadAd() { adstate.text = "ad loading" GW.loadAd() } func UpdateFOPar() { if (isFOShowing) { foparTitle.text = "Future offers:" futureOffersList.text = foList } else { do { foparTitle.text = "Parameters:" let params = GW.getProperties() let jsonData = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) let strdata = String(data: jsonData, encoding: String.Encoding.utf8) as String! //let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) futureOffersList.text = strdata } catch { futureOffersList.text = "Something wrong! And ErroR!" } } } @IBAction func ShowAd() { if (GW.isAdLoaded()) { adstate.text = "ad showing" GW.showAd() } else { adstate.text = "nothing to show, loading" GW.loadAd() } } @IBAction func ToggleFOPar() { isFOShowing = !isFOShowing UpdateFOPar() } func specialOfferAppeared(_ specialOffer: GWSpecialOffer) { } func specialOfferDisappeared(_ specialOffer: GWSpecialOffer) { } func onInitialized() { NSLog("SDK INITIALIZED"); } func futureSpecialOfferAppeared(_ specialOffer: GWSpecialOffer) { //let productIdentifier = specialOffer.product; //NSLog("BankView: Special offer appeared for %@", productIdentifier); let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss" let strDate = dateFormatter.string(from: specialOffer.activatedAt) let t = futureOffersList.text! + "\n " + specialOffer.product + ": will activated at " + strDate foList = foList + t; UpdateFOPar() } func onPushDelivered(_ specialOffer: GWSpecialOffer?, camp: String, title: String, message: String) { } func onPurchaseVerified(_ transactionID: String, state: String) { } func onAdLoaded() { adstate.text = "ad LOADED" } func onAdLoadFailed() { adstate.text = "ad load FAILED" } func onAdClosed() { adstate.text = "ad CLOSED" } }
mit
62aabb4283f17f6e1c0c8c47e97afed0
23.533333
106
0.55462
4.407186
false
false
false
false
mzaks/FlatBuffersSwiftPerformanceTest
FBTest/bench_decode_direct1.swift
1
2802
// // bench_decode_direct1.swift // FBTest // // Created by Maxim Zaks on 27.09.16. // Copyright © 2016 maxim.zaks. All rights reserved. // import Foundation extension FooBarContainer { public struct Direct1 : Hashable { private let reader : FBReader private let myOffset : Offset init(reader: FBReader, myOffset: Offset){ self.reader = reader self.myOffset = myOffset } public init?(_ reader: FBReader) { self.reader = reader guard let offest = reader.rootObjectOffset else { return nil } self.myOffset = offest } public var listCount : Int { return reader.getVectorLength(reader.getOffset(myOffset, propertyIndex: 0)) } public func getListElement(atIndex index : Int) -> FooBar.Direct1? { let offsetList = reader.getOffset(myOffset, propertyIndex: 0) if let ofs = reader.getVectorOffsetElement(offsetList, index: index) { return FooBar.Direct1(reader: reader, myOffset: ofs) } return nil } public var initialized : Bool { get { return reader.get(myOffset, propertyIndex: 1, defaultValue: false) } } public var fruit : Enum? { get { return Enum(rawValue: reader.get(myOffset, propertyIndex: 2, defaultValue: Enum.Apples.rawValue)) } } public var location : UnsafeBufferPointer<UInt8>? { get { return reader.getStringBuffer(reader.getOffset(myOffset, propertyIndex:3)) } } public var hashValue: Int { return Int(myOffset) } } } public func ==(t1 : FooBarContainer.Direct1, t2 : FooBarContainer.Direct1) -> Bool { return t1.reader.isEqual(t2.reader) && t1.myOffset == t2.myOffset } extension FooBar { public struct Direct1 : Hashable { private let reader : FBReader private let myOffset : Offset init(reader: FBReader, myOffset: Offset){ self.reader = reader self.myOffset = myOffset } public var sibling : Bar? { get { return reader.get(myOffset, propertyIndex: 0)} } public var name : UnsafeBufferPointer<UInt8>? { get { return reader.getStringBuffer(reader.getOffset(myOffset, propertyIndex:1)) } } public var rating : Float64 { get { return reader.get(myOffset, propertyIndex: 2, defaultValue: 0) } } public var postfix : UInt8 { get { return reader.get(myOffset, propertyIndex: 3, defaultValue: 0) } } public var hashValue: Int { return Int(myOffset) } } } public func ==(t1 : FooBar.Direct1, t2 : FooBar.Direct1) -> Bool { return t1.reader.isEqual(t2.reader) && t1.myOffset == t2.myOffset }
mit
bd0b336cd2cfc3cf9122cc27b91c7349
36.346667
144
0.612995
4.362928
false
false
false
false
practicalswift/swift
test/SILGen/extensions.swift
4
3540
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class Foo { // CHECK-LABEL: sil hidden [ossa] @$s10extensions3FooC3zim{{[_0-9a-zA-Z]*}}F func zim() {} } extension Foo { // CHECK-LABEL: sil hidden [ossa] @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F func zang() {} // CHECK-LABEL: sil hidden [ossa] @$s10extensions3FooC7zippitySivg var zippity: Int { return 0 } } struct Bar { // CHECK-LABEL: sil hidden [ossa] @$s10extensions3BarV4zung{{[_0-9a-zA-Z]*}}F func zung() {} } extension Bar { // CHECK-LABEL: sil hidden [ossa] @$s10extensions3BarV4zoom{{[_0-9a-zA-Z]*}}F func zoom() {} } // CHECK-LABEL: sil hidden [ossa] @$s10extensions19extensionReferencesyyAA3FooCF func extensionReferences(_ x: Foo) { // Non-objc extension methods are statically dispatched. // CHECK: function_ref @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F x.zang() // CHECK: function_ref @$s10extensions3FooC7zippitySivg _ = x.zippity } func extensionMethodCurrying(_ x: Foo) { _ = x.zang } // CHECK-LABEL: sil shared [thunk] [ossa] @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F // Extensions of generic types with stored property initializers // CHECK-LABEL: sil hidden [transparent] [ossa] @$s10extensions3BoxV1txSgvpfi : $@convention(thin) <T> () -> @out Optional<T> // CHECK: bb0(%0 : $*Optional<T>): // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optional<T>.Type // CHECK: inject_enum_addr %0 : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() struct Box<T> { let t: T? = nil } // CHECK-LABEL: sil hidden [ossa] @$s10extensions3BoxV1tACyxGx_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T> // CHECK: [[SELF_BOX:%.*]] = alloc_box $<τ_0_0> { var Box<τ_0_0> } <T> // CHECK-NEXT: [[UNINIT_SELF_BOX:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK-NEXT: [[SELF_ADDR:%.*]] = project_box [[UNINIT_SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T> // CHECK: [[INIT:%.*]] = function_ref @$s10extensions3BoxV1txSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK-NEXT: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: [[T_ADDR:%.*]] = struct_element_addr [[SELF_ADDR]] : $*Box<T>, #Box.t // CHECK-NEXT: copy_addr [take] [[RESULT]] to [[T_ADDR]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[RESULT]] : $*Optional<T> // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK-NEXT: [[RESULT_ADDR:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %1 to [initialization] %14 : $*T // CHECK-NEXT: inject_enum_addr [[RESULT]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*Box<T> // CHECK-NEXT: [[T_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*Box<T>, #Box.t // CHECK-NEXT: copy_addr [take] [[RESULT]] to [[T_ADDR:%.*]] : $*Optional<T> // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: dealloc_stack [[RESULT]] : $*Optional<T> // CHECK-NEXT: copy_addr [[SELF_ADDR]] to [initialization] %0 : $*Box<T> // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: destroy_value [[UNINIT_SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T> // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() extension Box { init(t: T) { self.t = t } }
apache-2.0
e4c9336e6a72b13915dcb78bacf861ea
40.529412
136
0.619263
2.86526
false
false
false
false