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
momotofu/UI-Color-Picker---Swift
ColorPicker/StateSwitcher.swift
1
7441
// // StateSwitcher.swift // ColorPicker // // Created by Christopher REECE on 2/4/15. // Copyright (c) 2015 Christopher Reece. All rights reserved. // import UIKit // declare swatch protocol protocol StateSwitcherDelegate: class { var state: HSBA {get set} } class StateSwitcher: UIView { private var _state: HSBA = .hue private let _nib: Shape! private var _nibClosestSlot: Shape? weak private var _timer: NSTimer? weak var Delegate:StateSwitcherDelegate? // drawing properties let width: CGFloat! let height: CGFloat! let circleSize: CGFloat! // declare x axis variables let hueX: CGFloat! let satX: CGFloat! let briX: CGFloat! let alpX: CGFloat! override func drawRect(rect: CGRect) { let context: CGContext = UIGraphicsGetCurrentContext() // background drawing if width > height { // draw path for sliders CGContextMoveToPoint(context, height / 4, height / 4 + 2) CGContextAddLineToPoint(context, width - (height / 4) + 1, height / 4 + 2) CGContextAddLineToPoint(context, width - (height / 4) + 1, height - (height / 4) - 1) CGContextAddLineToPoint(context, height / 4, height - (height / 4) - 1) CGContextClosePath(context) CGContextSetFillColorWithColor(context, UIColor.darkGrayColor().CGColor) CGContextDrawPath(context, kCGPathFill) } else { // draw path for sliders CGContextMoveToPoint(context, width / 4, width / 4) CGContextAddLineToPoint(context, height - (width / 4), width / 4) CGContextAddLineToPoint(context, height - (width / 4), width - (width / 4)) CGContextAddLineToPoint(context, width / 4, width - (width / 4)) CGContextClosePath(context) CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextDrawPath(context, kCGPathFill) } } override init(frame: CGRect) { // drawing properties width = max(frame.width, frame.height) height = min(frame.width, frame.height) circleSize = height! * 0.95 // declare x axis variables hueX = 0 satX = width! / 4 + circleSize! / 2 briX = width! / 2 + circleSize! alpX = width! - height! let nobSize = circleSize * 0.7 let slotPoints = [hueX, satX, briX, alpX] // create a nob let nibFrame = CGRectMake(0, 0, height, height) let nibColor = UIColor(white: 1, alpha: 0.9) _nib = Shape(frame: nibFrame, setColor: nibColor, shape: .circle, multiplier: 0.6, state: HSBA(rawValue: 1)!) super.init(frame: frame) // create slots for i in 0...3 { let frame = CGRectMake(slotPoints[i], 0, height, height) let slotColor = UIColor.darkGrayColor() let hueSlot: Shape = Shape(frame: frame, setColor: slotColor, shape: .circle, multiplier: 1, state: HSBA(rawValue: i + 1)!) addSubview(hueSlot) } addSubview(_nib) backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if let touch = touches.first as? UITouch { let touchPoint = touch.locationInView(self) for view in subviews { if CGRectContainsPoint(view.frame, touchPoint) { _nib!.shapeState = (view as! Shape).shapeState println("shape: \(_nib.shapeState.rawValue)") } } _nib!.center.x = touchPoint.x pointLimitations(_nib!, comparingPoint: touchPoint) Delegate?.state = _nib.shapeState } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if let touch = touches.first as? UITouch { let touchPoint = touch.locationInView(self) for view in subviews { if CGRectContainsPoint(view.frame, touchPoint) { _nib!.shapeState = (view as! Shape).shapeState } } _nib!.center.x = touchPoint.x pointLimitations(_nib!, comparingPoint: touchPoint) Delegate?.state = _nib.shapeState } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if let touch = touches.first as? UITouch { let touchPoint = touch.locationInView(self) for view in subviews { if _nibClosestSlot == nil { checkDistanceBetween(_nib, and: (view as! Shape)) } } } } func pointLimitations(shape: Shape?, comparingPoint: CGPoint) { if shape!.center.x >= width - height { shape!.frame.origin.x = width - height } else if shape!.center.x < 0 { shape!.frame.origin.x = 0 } } func checkDistanceBetween(nib: Shape?, and slot:Shape) { let xDif = nib!.center.x - slot.center.x let distance = abs(xDif) if distance <= width / 6 { _nibClosestSlot = slot let myRunLoop = NSRunLoop.currentRunLoop() let animationTimer = NSTimer(timeInterval: 0.025, target: self, selector: "gravitate:", userInfo: nil, repeats: true) myRunLoop.addTimer(animationTimer, forMode: NSDefaultRunLoopMode) println("timer should have fired") } } func gravitate(timer: NSTimer) { // if _nib!.center.x != _nibClosestSlot!.center.x { // if _nib!.center.x != _nibClosestSlot!.center.x { // get quadrant of _nib let nib = _nib!.center let neb = _nibClosestSlot!.center var angle = atan2f(Float(nib.y - neb.y), Float(nib.x - neb.x)) let gravity = CGFloat(Forces.gravity) _nib!.center.x += CGFloat(cosf(angle) * -1) * gravity Forces.gravity *= 1.05 let nibPoint = CGPointMake(_nib!.center.x, _nib!.center.y) if CGRectContainsPoint(_nibClosestSlot!.frame, nibPoint) { _nib!.center = neb _nib!.shapeState = _nibClosestSlot!.shapeState Delegate?.state = _nib.shapeState timer.invalidate() _nibClosestSlot = nil Forces.gravity = 1.0 } // } println("gravitate fired") } struct Forces { static private var _gravity: Float = 1.0 static var gravity: Float { get { return _gravity } set { _gravity = newValue } } } }
cc0-1.0
68b3b5d33891169236025b33a325aad5
25.960145
135
0.529902
4.760717
false
false
false
false
habr/ChatTaskAPI
IQKeyboardManager/Demo/Swift_Demo/ViewController/ScrollViewController.swift
15
2261
// // ScrollViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKit class ScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate { @IBOutlet private var scrollViewDemo : UIScrollView! @IBOutlet private var simpleTableView : UITableView! @IBOutlet private var scrollViewOfTableViews : UIScrollView! @IBOutlet private var tableViewInsideScrollView : UITableView! @IBOutlet private var scrollViewInsideScrollView : UIScrollView! @IBOutlet private var topTextField : UITextField! @IBOutlet private var bottomTextField : UITextField! @IBOutlet private var topTextView : UITextView! @IBOutlet private var bottomTextView : UITextView! override func viewDidLoad() { super.viewDidLoad() scrollViewDemo.contentSize = CGSizeMake(0, 321) scrollViewInsideScrollView.contentSize = CGSizeMake(0,321) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "\(indexPath.section) \(indexPath.row)" var cell = tableView.dequeueReusableCellWithIdentifier(identifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier) cell?.selectionStyle = UITableViewCellSelectionStyle.None cell?.backgroundColor = UIColor.clearColor() let textField = UITextField(frame: CGRectInset(cell!.contentView.bounds, 5, 5)) textField.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleWidth] textField.placeholder = identifier textField.borderStyle = UITextBorderStyle.RoundedRect cell?.contentView.addSubview(textField) } return cell! } override func shouldAutorotate() -> Bool { return true } }
mit
919ee320061aa7cc6158951d5cbb28f5
34.328125
154
0.698364
5.95
false
false
false
false
liuxuan30/SwiftCharts
SwiftCharts/Layers/ChartGuideLinesLayer.swift
7
8152
// // ChartGuideLinesLayer.swift // SwiftCharts // // Created by ischuetz on 26/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartGuideLinesLayerSettings { let linesColor: UIColor let linesWidth: CGFloat public init(linesColor: UIColor = UIColor.grayColor(), linesWidth: CGFloat = 0.3) { self.linesColor = linesColor self.linesWidth = linesWidth } } public class ChartGuideLinesDottedLayerSettings: ChartGuideLinesLayerSettings { let dotWidth: CGFloat let dotSpacing: CGFloat public init(linesColor: UIColor, linesWidth: CGFloat, dotWidth: CGFloat = 2, dotSpacing: CGFloat = 2) { self.dotWidth = dotWidth self.dotSpacing = dotSpacing super.init(linesColor: linesColor, linesWidth: linesWidth) } } public enum ChartGuideLinesLayerAxis { case X, Y, XAndY } public class ChartGuideLinesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer { private let settings: T private let onlyVisibleX: Bool private let onlyVisibleY: Bool private let axis: ChartGuideLinesLayerAxis public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: T, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) { self.settings = settings self.onlyVisibleX = onlyVisibleX self.onlyVisibleY = onlyVisibleY self.axis = axis super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) { fatalError("override") } override public func chartViewDrawing(#context: CGContextRef, chart: Chart) { let originScreenLoc = self.innerFrame.origin let xScreenLocs = onlyVisibleX ? self.xAxis.visibleAxisValuesScreenLocs : self.xAxis.axisValuesScreenLocs let yScreenLocs = onlyVisibleY ? self.yAxis.visibleAxisValuesScreenLocs : self.yAxis.axisValuesScreenLocs if self.axis == .X || self.axis == .XAndY { for xScreenLoc in xScreenLocs { let x1 = xScreenLoc let y1 = originScreenLoc.y let x2 = x1 let y2 = originScreenLoc.y + self.innerFrame.height self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2)) } } if self.axis == .Y || self.axis == .XAndY { for yScreenLoc in yScreenLocs { let x1 = originScreenLoc.x let y1 = yScreenLoc let x2 = originScreenLoc.x + self.innerFrame.width let y2 = y1 self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2)) } } } } public typealias ChartGuideLinesLayer = ChartGuideLinesLayer_<Any> public class ChartGuideLinesLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesLayerSettings> { override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: ChartGuideLinesLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY) } override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) { ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor) } } public typealias ChartGuideLinesDottedLayer = ChartGuideLinesDottedLayer_<Any> public class ChartGuideLinesDottedLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesDottedLayerSettings> { override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: ChartGuideLinesDottedLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY) } override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) { ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing) } } public class ChartGuideLinesForValuesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer { private let settings: T private let axisValuesX: [ChartAxisValue] private let axisValuesY: [ChartAxisValue] public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: T, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) { self.settings = settings self.axisValuesX = axisValuesX self.axisValuesY = axisValuesY super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } private func drawGuideline(context: CGContextRef, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint, dotWidth: CGFloat, dotSpacing: CGFloat) { ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: width, color: color, dotWidth: dotWidth, dotSpacing: dotSpacing) } private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) { fatalError("override") } override public func chartViewDrawing(#context: CGContextRef, chart: Chart) { let originScreenLoc = self.innerFrame.origin for axisValue in self.axisValuesX { let screenLoc = self.xAxis.screenLocForScalar(axisValue.scalar) let x1 = screenLoc let y1 = originScreenLoc.y let x2 = x1 let y2 = originScreenLoc.y + self.innerFrame.height self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2)) } for axisValue in self.axisValuesY { let screenLoc = self.yAxis.screenLocForScalar(axisValue.scalar) let x1 = originScreenLoc.x let y1 = screenLoc let x2 = originScreenLoc.x + self.innerFrame.width let y2 = y1 self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2)) } } } public typealias ChartGuideLinesForValuesLayer = ChartGuideLinesForValuesLayer_<Any> public class ChartGuideLinesForValuesLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesLayerSettings> { public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY) } override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) { ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor) } } public typealias ChartGuideLinesForValuesDottedLayer = ChartGuideLinesForValuesDottedLayer_<Any> public class ChartGuideLinesForValuesDottedLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesDottedLayerSettings> { public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesDottedLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY) } override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) { ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing) } }
apache-2.0
8f2742f2890b338c1c7295fc5117e771
45.056497
235
0.705594
4.354701
false
false
false
false
altyus/clubhouse-ios-api
Pod/Classes/ClubhouseAPI.swift
1
1762
// // ClubhouseAPI.swift // Pods // // Created by Al Tyus on 3/13/16. // // import Foundation import Alamofire import SwiftyJSON public class ClubhouseAPI { // MARK: - Types public typealias SuccessList = ([AnyObject]) -> Void public typealias SuccessObject = (JSON) -> Void public typealias Failure = (ErrorType?) -> Void // MARK: - Properties public static let sharedInstance: ClubhouseAPI = ClubhouseAPI() internal let baseURLString = "https://api.clubhouse.io/api/v1/" public var apiToken: String? // MARK: - Initializers public class func configure(apiToken: String) { ClubhouseAPI.sharedInstance.apiToken = apiToken } //MARK: - Functions public static func URLRequest(method: Alamofire.Method, path: String) -> NSMutableURLRequest { guard let apiToken = ClubhouseAPI.sharedInstance.apiToken, baseURL = NSURL(string: ClubhouseAPI.sharedInstance.baseURLString) else { fatalError("Token must be set") } let URL = baseURL.URLByAppendingPathComponent(path).URLByAppendingQueryParameters(["token": apiToken]) let mutableURLReuqest = NSMutableURLRequest(URL: URL) mutableURLReuqest.HTTPMethod = method.rawValue return mutableURLReuqest } internal func request(request: URLRequestConvertible, success: (AnyObject) -> Void, failure: Failure) { Alamofire.request(request) .validate() .responseJSON { response in switch response.result { case .Success(let value): success(value) case .Failure(let error): failure(error) } } } }
mit
f5d898f8a6597b25abfd1d9c34979f60
28.864407
140
0.624858
4.775068
false
false
false
false
tiehuaz/iOS-Application-for-AURIN
AurinProject/SidebarMenu/HTTPGetJSON.swift
1
1876
import Foundation /*these functions are used ot send HTTP request and parse returned JSON data*/ func JSONParseDict(jsonString:String) -> Dictionary<String, AnyObject> { if let data: NSData = jsonString.dataUsingEncoding( NSUTF8StringEncoding){ do{ if let jsonObj = try NSJSONSerialization.JSONObjectWithData( data, options: NSJSONReadingOptions(rawValue: 0)) as? Dictionary<String, AnyObject>{ return jsonObj } }catch{ print("Error") } } return [String: AnyObject]() } func HTTPsendRequest(request: NSMutableURLRequest, callback: (String, String?) -> Void) { let task = NSURLSession.sharedSession().dataTaskWithRequest( request, completionHandler : { data, response, error in if error != nil { callback("", (error!.localizedDescription) as String) } else { callback( NSString(data: data!, encoding: NSUTF8StringEncoding) as! String, nil ) } }) task.resume() } func HTTPGetJSON( url: String, callback: (Dictionary<String, AnyObject>, String?) -> Void) { let request = NSMutableURLRequest(URL: NSURL(string: url)!) request.setValue("application/json", forHTTPHeaderField: "Accept") HTTPsendRequest(request) { (data: String, error: String?) -> Void in if error != nil { callback(Dictionary<String, AnyObject>(), error) } else { let jsonObj = JSONParseDict(data) callback(jsonObj, nil) } } }
apache-2.0
630f665f7dee111e2d5da41b7c31faff
30.266667
98
0.518124
5.583333
false
false
false
false
jisudong555/swift
weibo/weibo/AppDelegate.swift
1
2213
// // AppDelegate.swift // weibo // // Created by jisudong on 16/4/7. // Copyright © 2016年 jisudong. All rights reserved. // import UIKit let SwitchRootViewControllerNotification = "SwitchRootViewControllerNotification" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(switchRootViewController(_:)), name: SwitchRootViewControllerNotification, object: nil) UINavigationBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().tintColor = UIColor.orangeColor() window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() window?.rootViewController = defaultController() window?.makeKeyAndVisible() return true } func switchRootViewController(notify: NSNotification) { if notify.object as! Bool { window?.rootViewController = TabBarController() } else { window?.rootViewController = WelcomeViewController() } } func defaultController() -> UIViewController { if UserAccount.userLogin() { return isNewVersion() ? NewfeatureCollectionViewController() : WelcomeViewController() } return TabBarController() } func isNewVersion() -> Bool { let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] let sanboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? "" if currentVersion?.compare(sanboxVersion) == NSComparisonResult.OrderedDescending { NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString") return true } return false } }
mit
aaf3cfc3a2412b7fac5511a2c7c7f6cc
30.126761
170
0.670588
6.054795
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/Driver+Test.swift
2
39109
// // Driver+Test.swift // RxTests // // Created by Krunoslav Zaher on 10/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift import RxCocoa import XCTest import RxTests class DriverTest : RxTest { var backgroundScheduler = SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .Default) override func tearDown() { super.tearDown() } } // test helpers that make sure that resulting driver operator honors definition // * only one subscription is made and shared - shareReplay(1) // * subscription is made on main thread - subscribeOn(ConcurrentMainScheduler.instance) // * events are observed on main thread - observeOn(MainScheduler.instance) // * it can't error out - it needs to have catch somewhere extension DriverTest { func subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription<R: Equatable>(driver: Driver<R>, subscribedOnBackground: () -> ()) -> [R] { var firstElements = [R]() var secondElements = [R]() let subscribeFinished = self.expectationWithDescription("subscribeFinished") var expectation1: XCTestExpectation! var expectation2: XCTestExpectation! backgroundScheduler.schedule(()) { _ in var subscribing1 = true let currentThread = NSThread.currentThread() _ = driver.asObservable().subscribe { e in if !subscribing1 { XCTAssertTrue(isMainThread()) } else { XCTAssertEqual(currentThread, NSThread.currentThread()) } switch e { case .Next(let element): firstElements.append(element) case .Error(let error): XCTFail("Error passed \(error)") case .Completed: expectation1.fulfill() } } subscribing1 = false var subscribing = true _ = driver.asDriver().asObservable().subscribe { e in if !subscribing { XCTAssertTrue(isMainThread()) } else { XCTAssertEqual(currentThread, NSThread.currentThread()) } switch e { case .Next(let element): secondElements.append(element) case .Error(let error): XCTFail("Error passed \(error)") case .Completed: expectation2.fulfill() } } subscribing = false // Subscription should be made on main scheduler // so this will make sure execution is continued after // subscription because of serial nature of main scheduler. MainScheduler.instance.schedule(()) { _ in subscribeFinished.fulfill() return NopDisposable.instance } return NopDisposable.instance } waitForExpectationsWithTimeout(1.0) { error in XCTAssertTrue(error == nil) } expectation1 = self.expectationWithDescription("finished1") expectation2 = self.expectationWithDescription("finished2") subscribedOnBackground() waitForExpectationsWithTimeout(1.0) { error in XCTAssertTrue(error == nil) } XCTAssertTrue(firstElements == secondElements) return firstElements } } // MARK: properties extension DriverTest { func testDriverSharing_WhenErroring() { let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(Int) let observer2 = scheduler.createObserver(Int) let observer3 = scheduler.createObserver(Int) var disposable1: Disposable! var disposable2: Disposable! var disposable3: Disposable! let coldObservable = scheduler.createColdObservable([ next(10, 0), next(20, 1), next(30, 2), next(40, 3), error(50, testError) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) scheduler.scheduleAt(200) { disposable1 = driver.asObservable().subscribe(observer1) } scheduler.scheduleAt(225) { disposable2 = driver.asObservable().subscribe(observer2) } scheduler.scheduleAt(235) { disposable1.dispose() } scheduler.scheduleAt(260) { disposable2.dispose() } // resubscription scheduler.scheduleAt(260) { disposable3 = driver.asObservable().subscribe(observer3) } scheduler.scheduleAt(285) { disposable3.dispose() } scheduler.start() XCTAssertEqual(observer1.events, [ next(210, 0), next(220, 1), next(230, 2) ]) XCTAssertEqual(observer2.events, [ next(225, 1), next(230, 2), next(240, 3), next(250, -1), completed(250) ]) XCTAssertEqual(observer3.events, [ next(270, 0), next(280, 1), ]) XCTAssertEqual(coldObservable.subscriptions, [ Subscription(200, 250), Subscription(260, 285), ]) } func testDriverSharing_WhenCompleted() { let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(Int) let observer2 = scheduler.createObserver(Int) let observer3 = scheduler.createObserver(Int) var disposable1: Disposable! var disposable2: Disposable! var disposable3: Disposable! let coldObservable = scheduler.createColdObservable([ next(10, 0), next(20, 1), next(30, 2), next(40, 3), error(50, testError) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) scheduler.scheduleAt(200) { disposable1 = driver.asObservable().subscribe(observer1) } scheduler.scheduleAt(225) { disposable2 = driver.asObservable().subscribe(observer2) } scheduler.scheduleAt(235) { disposable1.dispose() } scheduler.scheduleAt(260) { disposable2.dispose() } // resubscription scheduler.scheduleAt(260) { disposable3 = driver.asObservable().subscribe(observer3) } scheduler.scheduleAt(285) { disposable3.dispose() } scheduler.start() XCTAssertEqual(observer1.events, [ next(210, 0), next(220, 1), next(230, 2) ]) XCTAssertEqual(observer2.events, [ next(225, 1), next(230, 2), next(240, 3), next(250, -1), completed(250) ]) XCTAssertEqual(observer3.events, [ next(270, 0), next(280, 1), ]) XCTAssertEqual(coldObservable.subscriptions, [ Subscription(200, 250), Subscription(260, 285), ]) } } // MARK: conversions extension DriverTest { func testVariableAsDriver() { let hotObservable = Variable(1) let driver = Driver.zip(hotObservable.asDriver(), Driver.of(0, 0)) { all in return all.0 } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { hotObservable.value = 1 hotObservable.value = 2 } XCTAssertEqual(results, [1, 1]) } func testAsDriver_onErrorJustReturn() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_onErrorDriveWith() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorDriveWith: Driver.just(-1)) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_onErrorRecover() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver { e in return Driver.empty() } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2]) } } // MARK: deferred extension DriverTest { func testAsDriver_deferred() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = Driver.deferred { hotObservable.asDriver(onErrorJustReturn: -1) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } } // MARK: map extension DriverTest { func testAsDriver_map() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).map { (n: Int) -> Int in XCTAssertTrue(isMainThread()) return n + 1 } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [2, 3, 0]) } } // MARK: filter extension DriverTest { func testAsDriver_filter() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).filter { n in XCTAssertTrue(isMainThread()) return n % 2 == 0 } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [2]) } } // MARK: switch latest extension DriverTest { func testAsDriver_switchLatest() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Driver<Int>>() let hotObservable1 = MainThreadPrimitiveHotObservable<Int>() let hotObservable2 = MainThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: hotObservable1.asDriver(onErrorJustReturn: -1)).switchLatest() let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(hotObservable1.asDriver(onErrorJustReturn: -2))) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) hotObservable.on(.Next(hotObservable2.asDriver(onErrorJustReturn: -3))) hotObservable2.on(.Next(10)) hotObservable2.on(.Next(11)) hotObservable2.on(.Error(testError)) hotObservable.on(.Error(testError)) hotObservable1.on(.Completed) hotObservable.on(.Completed) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [ 1, 2, -2, 10, 11, -3 ]) } } // MARK: flatMapLatest extension DriverTest { func testAsDriver_flatMapLatest() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable1 = MainThreadPrimitiveHotObservable<Int>() let hotObservable2 = MainThreadPrimitiveHotObservable<Int>() let errorHotObservable = MainThreadPrimitiveHotObservable<Int>() let drivers: [Driver<Int>] = [ hotObservable1.asDriver(onErrorJustReturn: -2), hotObservable2.asDriver(onErrorJustReturn: -3), errorHotObservable.asDriver(onErrorJustReturn: -4), ] let driver = hotObservable.asDriver(onErrorJustReturn: 2).flatMapLatest { drivers[$0] } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(0)) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) hotObservable.on(.Next(1)) hotObservable2.on(.Next(10)) hotObservable2.on(.Next(11)) hotObservable2.on(.Error(testError)) hotObservable.on(.Error(testError)) errorHotObservable.on(.Completed) hotObservable.on(.Completed) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [ 1, 2, -2, 10, 11, -3 ]) } } // MARK: flatMapFirst extension DriverTest { func testAsDriver_flatMapFirst() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable1 = MainThreadPrimitiveHotObservable<Int>() let hotObservable2 = MainThreadPrimitiveHotObservable<Int>() let errorHotObservable = MainThreadPrimitiveHotObservable<Int>() let drivers: [Driver<Int>] = [ hotObservable1.asDriver(onErrorJustReturn: -2), hotObservable2.asDriver(onErrorJustReturn: -3), errorHotObservable.asDriver(onErrorJustReturn: -4), ] let driver = hotObservable.asDriver(onErrorJustReturn: 2).flatMapFirst { drivers[$0] } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(0)) hotObservable.on(.Next(1)) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Next(10)) hotObservable2.on(.Next(11)) hotObservable2.on(.Error(testError)) hotObservable.on(.Error(testError)) errorHotObservable.on(.Completed) hotObservable.on(.Completed) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [ 1, 2, -2, ]) } } // MARK: doOn extension DriverTest { func testAsDriver_doOn() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() var events = [Event<Int>]() let driver = hotObservable.asDriver(onErrorJustReturn: -1).doOn { e in XCTAssertTrue(isMainThread()) events.append(e) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) let expectedEvents = [.Next(1), .Next(2), .Next(-1), .Completed] as [Event<Int>] XCTAssertEqual(events, expectedEvents) } func testAsDriver_doOnNext() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() var events = [Int]() let driver = hotObservable.asDriver(onErrorJustReturn: -1).doOnNext { e in XCTAssertTrue(isMainThread()) events.append(e) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) let expectedEvents = [1, 2, -1] XCTAssertEqual(events, expectedEvents) } func testAsDriver_doOnCompleted() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() var completed = false let driver = hotObservable.asDriver(onErrorJustReturn: -1).doOnCompleted { e in XCTAssertTrue(isMainThread()) completed = true } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) XCTAssertEqual(completed, true) } } // MARK: distinct until change extension DriverTest { func testAsDriver_distinctUntilChanged1() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged() let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_distinctUntilChanged2() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged({ $0 }) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_distinctUntilChanged3() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged({ $0 == $1 }) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_distinctUntilChanged4() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged({ $0 }) { $0 == $1 } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } } // MARK: flat map extension DriverTest { func testAsDriver_flatMap() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).flatMap { (n: Int) -> Driver<Int> in XCTAssertTrue(isMainThread()) return Driver.just(n + 1) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [2, 3, 0]) } } // MARK: merge extension DriverTest { func testAsDriver_merge() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).map { (n: Int) -> Driver<Int> in XCTAssertTrue(isMainThread()) return Driver.just(n + 1) }.merge() let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [2, 3, 0]) } func testAsDriver_merge2() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).map { (n: Int) -> Driver<Int> in XCTAssertTrue(isMainThread()) return Driver.just(n + 1) }.merge(maxConcurrent: 1) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [2, 3, 0]) } } // MARK: debounce extension DriverTest { func testAsDriver_debounce() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).debounce(0.0) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [-1]) } func testAsDriver_throttle() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).throttle(0.0) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [-1]) } } // MARK: scan extension DriverTest { func testAsDriver_scan() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable.asDriver(onErrorJustReturn: -1).scan(0) { (a: Int, n: Int) -> Int in XCTAssertTrue(isMainThread()) return a + n } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.Next(1)) hotObservable.on(.Next(2)) hotObservable.on(.Error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 3, 2]) } } // MARK: concat extension DriverTest { func testAsDriver_concat_sequenceType() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = MainThreadPrimitiveHotObservable<Int>() let driver = AnySequence([hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)]).concat() let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable2.on(.Next(4)) hotObservable2.on(.Next(5)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1, 4, 5, -2]) } func testAsDriver_concat() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = MainThreadPrimitiveHotObservable<Int>() let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].concat() let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable2.on(.Next(4)) hotObservable2.on(.Next(5)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1, 4, 5, -2]) } } // MARK: combine latest extension DriverTest { func testAsDriver_combineLatest_array() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].combineLatest { a in a.reduce(0, combine: +) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable2.on(.Next(4)) hotObservable1.on(.Next(2)) hotObservable2.on(.Next(5)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [5, 6, 7, 4, -3]) } func testAsDriver_combineLatest() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = Driver.combineLatest(hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2), resultSelector: +) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable2.on(.Next(4)) hotObservable1.on(.Next(2)) hotObservable2.on(.Next(5)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [5, 6, 7, 4, -3]) } } // MARK: zip extension DriverTest { func testAsDriver_zip_array() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].zip { a in a.reduce(0, combine: +) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable2.on(.Next(4)) hotObservable1.on(.Next(2)) hotObservable2.on(.Next(5)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [5, 7, -3]) } func testAsDriver_zip() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = Driver.zip(hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2), resultSelector: +) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable2.on(.Next(4)) hotObservable1.on(.Next(2)) hotObservable2.on(.Next(5)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [5, 7, -3]) } } // MARK: withLatestFrom extension DriverTest { func testAsDriver_withLatestFrom() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable1.asDriver(onErrorJustReturn: -1).withLatestFrom(hotObservable2.asDriver(onErrorJustReturn: -2)) { f, s in "\(f)\(s)" } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable2.on(.Next(4)) hotObservable1.on(.Next(2)) hotObservable2.on(.Next(5)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, ["24", "-15"]) } func testAsDriver_withLatestFromDefaultOverload() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable1.asDriver(onErrorJustReturn: -1).withLatestFrom(hotObservable2.asDriver(onErrorJustReturn: -2)) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable2.on(.Next(4)) hotObservable1.on(.Next(2)) hotObservable2.on(.Next(5)) hotObservable1.on(.Error(testError)) hotObservable2.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [4, 5]) } } // MARK: skip extension DriverTest { func testAsDriver_skip() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable1.asDriver(onErrorJustReturn: -1).skip(1) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [2, -1]) } } // MARK: startWith extension DriverTest { func testAsDriver_startWith() { let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>() let driver = hotObservable1.asDriver(onErrorJustReturn: -1).startWith(0) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) hotObservable1.on(.Next(1)) hotObservable1.on(.Next(2)) hotObservable1.on(.Error(testError)) XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [0, 1, 2, -1]) } } //MARK: interval extension DriverTest { func testAsDriver_interval() { let testScheduler = TestScheduler(initialClock: 0) let firstObserver = testScheduler.createObserver(Int) let secondObserver = testScheduler.createObserver(Int) var disposable1: Disposable! var disposable2: Disposable! driveOnScheduler(testScheduler) { let interval = Driver<Int>.interval(100) testScheduler.scheduleAt(20) { disposable1 = interval.asObservable().subscribe(firstObserver) } testScheduler.scheduleAt(170) { disposable2 = interval.asObservable().subscribe(secondObserver) } testScheduler.scheduleAt(230) { disposable1.dispose() disposable2.dispose() } testScheduler.start() } XCTAssertEqual(firstObserver.events, [ next(120, 0), next(220, 1) ]) XCTAssertEqual(secondObserver.events, [ next(170, 0), next(220, 1) ]) } } //MARK: timer extension DriverTest { func testAsDriver_timer() { let testScheduler = TestScheduler(initialClock: 0) let firstObserver = testScheduler.createObserver(Int) let secondObserver = testScheduler.createObserver(Int) var disposable1: Disposable! var disposable2: Disposable! driveOnScheduler(testScheduler) { let interval = Driver<Int>.timer(100, period: 105) testScheduler.scheduleAt(20) { disposable1 = interval.asObservable().subscribe(firstObserver) } testScheduler.scheduleAt(170) { disposable2 = interval.asObservable().subscribe(secondObserver) } testScheduler.scheduleAt(230) { disposable1.dispose() disposable2.dispose() } testScheduler.start() } XCTAssertEqual(firstObserver.events, [ next(120, 0), next(225, 1) ]) XCTAssertEqual(secondObserver.events, [ next(170, 0), next(225, 1) ]) } }
mit
cdc4b5a63af818ad63524c7d40c684a5
32.860606
164
0.63969
5.2692
false
true
false
false
rokuz/omim
iphone/Maps/UI/Appearance/ThemeManager.swift
1
1916
@objc(MWMThemeManager) final class ThemeManager: NSObject { private static let autoUpdatesInterval: TimeInterval = 30 * 60 // 30 minutes in seconds private static let instance = ThemeManager() private weak var timer: Timer? private override init() { super.init() } private func update(theme: MWMTheme) { let actualTheme: MWMTheme = { theme in let isVehicleRouting = MWMRouter.isRoutingActive() && (MWMRouter.type() == .vehicle) switch theme { case .day: fallthrough case .vehicleDay: return isVehicleRouting ? .vehicleDay : .day case .night: fallthrough case .vehicleNight: return isVehicleRouting ? .vehicleNight : .night case .auto: guard isVehicleRouting else { return .day } switch FrameworkHelper.daytime(at: MWMLocationManager.lastLocation()) { case .day: return .vehicleDay case .night: return .vehicleNight } } }(theme) let nightMode = UIColor.isNightMode() let newNightMode: Bool = { theme in switch theme { case .day: fallthrough case .vehicleDay: return false case .night: fallthrough case .vehicleNight: return true case .auto: assert(false); return false } }(actualTheme) FrameworkHelper.setTheme(actualTheme) if nightMode != newNightMode { UIColor.setNightMode(newNightMode) (UIViewController.topViewController() as! MWMController).mwm_refreshUI() } } @objc static func invalidate() { instance.update(theme: MWMSettings.theme()) } @objc static var autoUpdates: Bool { get { return instance.timer != nil } set { if newValue { instance.timer = Timer.scheduledTimer(timeInterval: autoUpdatesInterval, target: self, selector: #selector(invalidate), userInfo: nil, repeats: true) } else { instance.timer?.invalidate() } invalidate() } } }
apache-2.0
8f7d315567132e26e0bffa1550b3de30
29.412698
157
0.660752
4.424942
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/SettingsViewController.swift
1
3962
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** * Custom UIViewController for Settings page. */ class SettingsViewController: HatchUIViewController{ /// Table view that contains all cells for Settings page @IBOutlet weak var tableView: UITableView! /// Button that opens the menu @IBOutlet weak var menuButton: UIButton! /// Label displaying the title of the Settings page @IBOutlet weak var titleLabel: UILabel! var cellTitles: [String] = [NSLocalizedString("ACCOUNTS", comment: ""), NSLocalizedString("TOUCH ID", comment: ""), NSLocalizedString("NOTIFICATIONS", comment: ""), NSLocalizedString("PROFILE PICTURE", comment: "")] /** Method that sets up the UI style and sets up button action receivers. */ override func viewDidLoad() { self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None self.menuButton.addTarget(self.navigationController, action: "menuButtonTapped:", forControlEvents: .TouchUpInside) self.titleLabel.setKernAttribute(4.0) } } extension SettingsViewController: UITableViewDataSource, UITableViewDelegate{ /** Delegate method to create individual settings cells - parameter tableView: - parameter indexPath: - returns: */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Disclosure Indicator Cell if (indexPath.row == 0 || indexPath.row == 3){ var disclosureCell = self.tableView.dequeueReusableCellWithIdentifier("disclosureCell", forIndexPath: indexPath) as? SettingsDisclosureIndicatorCell if disclosureCell == nil { disclosureCell = SettingsDisclosureIndicatorCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "disclosureCell") } disclosureCell?.configCell(cellTitles[indexPath.row]) return disclosureCell! } else { // UISwitch Cell var switchCell = self.tableView.dequeueReusableCellWithIdentifier("switchCell", forIndexPath: indexPath) as? SettingsUISwitchCell if switchCell == nil { switchCell = SettingsUISwitchCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "switchCell") } switchCell?.configCell(indexPath.row, title: cellTitles[indexPath.row]) return switchCell! } } /** Delegate method that returns the height for rows in the tableview. - parameter tableView: - parameter indexPath: - returns: Height for specified row. */ func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 65 } /** Delegate method that returns the number of rows in a specified section - parameter tableView: - parameter section: - returns: */ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.cellTitles.count } /** Delegate method to handle event of cell being tapped - parameter tableView: - parameter indexPath: */ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row == 0 || indexPath.row == 3){ // Animates title label as if it were button to give user feedback let disclosureCell = self.tableView.cellForRowAtIndexPath(indexPath) as! SettingsDisclosureIndicatorCell disclosureCell.animateLabelColorChange() } } }
epl-1.0
e682f7e148d05c961abfcfd9719f75d7
31.735537
160
0.629639
5.938531
false
false
false
false
tdginternet/TGCameraViewController
ExampleSwift/TGInitialViewController.swift
1
2525
// // ViewController.swift // ExampleSwift // // Created by Mario Cecchi on 7/20/16. // Copyright © 2016 Tudo Gostoso Internet. All rights reserved. // import UIKit class TGInitialViewController: UIViewController, TGCameraDelegate { @IBOutlet weak var photoView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // set custom tint color //TGCameraColor.setTint(.green) // save image to album TGCamera.setOption(kTGCameraOptionSaveImageToAlbum, value: true) // use the original image aspect instead of square //TGCamera.setOption(kTGCameraOptionUseOriginalAspect, value: true) // hide switch camera button //TGCamera.setOption(kTGCameraOptionHiddenToggleButton, value: true) // hide album button //TGCamera.setOption(kTGCameraOptionHiddenAlbumButton, value: true) // hide filter button //TGCamera.setOption(kTGCameraOptionHiddenFilterButton, value: true) photoView.clipsToBounds = true let clearButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action:#selector(clearTapped)) navigationItem.rightBarButtonItem = clearButton } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: TGCameraDelegate - Required methods func cameraDidCancel() { dismiss(animated: true, completion: nil) } func cameraDidTakePhoto(_ image: UIImage!) { photoView.image = image dismiss(animated: true, completion: nil) } func cameraDidSelectAlbumPhoto(_ image: UIImage!) { photoView.image = image dismiss(animated: true, completion: nil) } // MARK: TGCameraDelegate - Optional methods func cameraWillTakePhoto() { print("cameraWillTakePhoto") } func cameraDidSavePhoto(atPath assetURL: URL!) { print("cameraDidSavePhotoAtPath: \(assetURL)") } func cameraDidSavePhotoWithError(_ error: Error!) { print("cameraDidSavePhotoWithError \(error)") } // MARK: Actions @IBAction func takePhotoTapped() { let navigationController = TGCameraNavigationController.new(with: self) present(navigationController!, animated: true, completion: nil) } // MARK: Private methods func clearTapped() { photoView.image = nil } }
mit
f6ea04c6751a64853af06c331764216e
26.434783
116
0.64065
4.99802
false
false
false
false
mmrmmlrr/HandyText
HandyText/Font.swift
1
1526
// // Font.swift // HandyText // // Copyright © 2016 aleksey chernish. All rights reserved. // public struct Font { public enum Thickness { case extralight, light, regular, medium, bold, heavy, extraheavy } public let extralight: String public let extralightItalic: String public let light: String public let lightItalic: String public let regular: String public let italic: String public let medium: String public let mediumItalic: String public let bold: String public let boldItalic: String public let heavy: String public let heavyItalic: String public let extraheavy: String public let extraheavyItalic: String public init( extralight: String = "", extralightItalic: String = "", light: String = "", lightItalic: String = "", regular: String = "", italic: String = "", medium: String = "", mediumItalic: String = "", bold: String = "", boldItalic: String = "", heavy: String = "", heavyItalic: String = "", extraheavy: String = "", extraheavyItalic: String = "" ) { self.extralight = extralight self.extralightItalic = extralightItalic self.light = light self.lightItalic = lightItalic self.regular = regular self.italic = italic self.medium = medium self.mediumItalic = mediumItalic self.bold = bold self.boldItalic = boldItalic self.heavy = heavy self.heavyItalic = heavyItalic self.extraheavy = extraheavy self.extraheavyItalic = extraheavyItalic } }
mit
6e113513e31ef2ac0aebac8bb03f2638
24
68
0.672131
4.066667
false
false
false
false
notbenoit/tvOS-Twitch
Code/iOS/Controllers/Home/Cells/GameCell.swift
1
2024
// Copyright (c) 2015 Benoit Layer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ReactiveSwift import WebImage import DataSource final class GameCell: CollectionViewCell { static let identifier: String = "cellIdentifierGame" static let nib: UINib = UINib(nibName: "GameCell", bundle: nil) @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var labelName: UILabel! fileprivate let disposable = CompositeDisposable() override func prepareForReuse() { imageView.image = nil labelName.text = nil } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.twitchLightColor() disposable += self.cellModel.producer .map { $0 as? GameCellViewModel } .skipNil() .startWithValues { [weak self] in self?.configure(with: $0) } } private func configure(with item: GameCellViewModel) { labelName.text = item.gameName if let url = URL(string: item.gameImageURL) { imageView.sd_setImage(with: url) } } }
bsd-3-clause
76894252839eee370598b73fd8f54612
35.142857
80
0.751482
4.261053
false
false
false
false
mark-randall/Core-Data-Extensions
Pod/Classes/NSManagedObject+Fetching.swift
1
2952
// // NSManagedObject+Fetching.swift // CoreData2 // // Created by mrandall on 10/12/15. // Copyright © 2015 mrandall. All rights reserved. // import Foundation import CoreData //MARK: - Creating public extension NSManagedObject { /// Create Self entity name in NSManagedObjectContext /// /// parameter moc: NSManagedObjectContext /// returns String public class func entityNameInContext(_ moc: NSManagedObjectContext) -> String { let classString = NSStringFromClass(self) let components = NSStringFromClass(self).components(separatedBy: ".") return components.last ?? classString } /// Create Self in NSManagedObjectContext /// /// parameter: moc NSManagedObjectContext public class func createInContext(_ moc: NSManagedObjectContext) -> Self { return _createInContext(moc, type: self) } /// Create Self in NSManagedObjectContext /// /// parameter moc: NSManagedObjectContext /// parameter type: Class /// return type fileprivate class func _createInContext<T>(_ moc: NSManagedObjectContext, type: T.Type) -> T { let entityName = entityNameInContext(moc) let entity = NSEntityDescription.insertNewObject(forEntityName: entityName, into: moc) return entity as! T } } //MARK: - Fetching public extension NSManagedObject { /// Fetch all entities of type T /// /// parameter sort: [NSSortDescriptor] /// parameter moc: NSManagedObjectContext public class func fetchAll<T: NSFetchRequestResult>(sortOn sort: [NSSortDescriptor]? = nil, moc: NSManagedObjectContext) -> [T] { return self.fetchWithPredicate(nil, sort: sort, prefetchRelationships: nil, moc: moc) } /// Fetch entities of type T /// /// NOTE: Current the return type must be specified where method is called to satisfy T. /// Hopefully there is a better way in the future of Swift. [Self] is not allowed outside protocol definition /// /// parameter predicate: NSPredicate /// parameter sort: [NSSortDescriptor] /// parameter prefetchRelationships: [String] relationshipKeyPathsForPrefetching value /// parameter moc: NSManagedObjectContext public class func fetchWithPredicate<T: NSFetchRequestResult>( _ predicate: NSPredicate?, sort: [NSSortDescriptor]? = [], prefetchRelationships: [String]? = nil, moc: NSManagedObjectContext ) -> [T] { //create fetchRequest let entityName = self.entityNameInContext(moc) let request = NSFetchRequest<T>(entityName: entityName) request.predicate = predicate request.sortDescriptors = sort request.relationshipKeyPathsForPrefetching = prefetchRelationships //execute fetch do { return try moc.fetch(request).map { return $0 as! T } } catch { return [] } } }
mit
3c56db85702dd1f3f538c9300c885118
32.91954
133
0.664521
5.204586
false
false
false
false
dvor/Antidote
Antidote/OCTManagerMock.swift
1
8424
// 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 MobileCoreServices private enum Gender { case male case female } class OCTManagerMock: NSObject, OCTManager { var bootstrap: OCTSubmanagerBootstrap var calls: OCTSubmanagerCalls var chats: OCTSubmanagerChats var dns: OCTSubmanagerDNS var files: OCTSubmanagerFiles var friends: OCTSubmanagerFriends var objects: OCTSubmanagerObjects var user: OCTSubmanagerUser var realm: RLMRealm override init() { let configuration = RLMRealmConfiguration.default() configuration.inMemoryIdentifier = "test realm" realm = try! RLMRealm(configuration: configuration) bootstrap = OCTSubmanagerBootstrapMock() calls = OCTSubmanagerCallsMock() chats = OCTSubmanagerChatsMock() dns = OCTSubmanagerDNSMock() files = OCTSubmanagerFilesMock() friends = OCTSubmanagerFriendsMock() objects = OCTSubmanagerObjectsMock(realm: realm) user = OCTSubmanagerUserMock() super.init() populateRealm() } func configuration() -> OCTManagerConfiguration { return OCTManagerConfiguration() } func exportToxSaveFile() throws -> String { return "123" } func changeEncryptPassword(_ newPassword: String, oldPassword: String) -> Bool { return true } func isManagerEncrypted(withPassword password: String) -> Bool { return true } } private extension OCTManagerMock { func populateRealm() { realm.beginWriteTransaction() let f1 = addFriend(gender: .female, number: 1, connectionStatus: .TCP, status: .none) let f2 = addFriend(gender: .male, number: 1, connectionStatus: .TCP, status: .busy) let f3 = addFriend(gender: .female, number: 2, connectionStatus: .none, status: .none) let f4 = addFriend(gender: .male, number: 2, connectionStatus: .TCP, status: .away) let f5 = addFriend(gender: .male, number: 3, connectionStatus: .TCP, status: .none) let f6 = addFriend(gender: .female, number: 3, connectionStatus: .TCP, status: .away) let f7 = addFriend(gender: .male, number: 4, connectionStatus: .TCP, status: .away) let f8 = addFriend(gender: .female, number: 4, connectionStatus: .none, status: .none) let f9 = addFriend(gender: .female, number: 5, connectionStatus: .TCP, status: .none) let f10 = addFriend(gender: .male, number: 5, connectionStatus: .none, status: .none) let c1 = addChat(friend: f1) let c2 = addChat(friend: f2) let c3 = addChat(friend: f3) let c4 = addChat(friend: f4) let c5 = addChat(friend: f5) let c6 = addChat(friend: f6) let c7 = addChat(friend: f7) let c8 = addChat(friend: f8) let c9 = addChat(friend: f9) let c10 = addChat(friend: f10) addDemoConversationToChat(c1) addCallMessage(chat: c2, outgoing: false, answered: false, duration: 0.0) addTextMessage(chat: c3, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_1")) addCallMessage(chat: c4, outgoing: true, answered: true, duration: 1473.0) addTextMessage(chat: c5, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_2")) addFileMessage(chat: c6, outgoing: false, fileName: "party.png") addTextMessage(chat: c7, outgoing: true, text: String(localized: "app_store_screenshot_chat_message_3")) addTextMessage(chat: c8, outgoing: true, text: String(localized: "app_store_screenshot_chat_message_4")) addFileMessage(chat: c9, outgoing: true, fileName: "presentation_2016.pdf") addTextMessage(chat: c10, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_5")) c1.lastReadDateInterval = Date().timeIntervalSince1970 // unread message // c2.lastReadDateInterval = NSDate().timeIntervalSince1970 c3.lastReadDateInterval = Date().timeIntervalSince1970 c4.lastReadDateInterval = Date().timeIntervalSince1970 c5.lastReadDateInterval = Date().timeIntervalSince1970 c6.lastReadDateInterval = Date().timeIntervalSince1970 c7.lastReadDateInterval = Date().timeIntervalSince1970 c8.lastReadDateInterval = Date().timeIntervalSince1970 c9.lastReadDateInterval = Date().timeIntervalSince1970 c10.lastReadDateInterval = Date().timeIntervalSince1970 try! realm.commitWriteTransaction() } func addFriend(gender: Gender, number: Int, connectionStatus: OCTToxConnectionStatus, status: OCTToxUserStatus) -> OCTFriend { let friend = OCTFriend() friend.publicKey = "123" friend.connectionStatus = connectionStatus friend.isConnected = connectionStatus != .none friend.status = status switch gender { case .male: friend.nickname = String(localized: "app_store_screenshot_friend_male_\(number)") friend.avatarData = UIImagePNGRepresentation(UIImage(named: "male-\(number)")!) case .female: friend.nickname = String(localized: "app_store_screenshot_friend_female_\(number)") friend.avatarData = UIImagePNGRepresentation(UIImage(named: "female-\(number)")!) } realm.add(friend) return friend } func addChat(friend: OCTFriend) -> OCTChat { let chat = OCTChat() realm.add(chat) chat.friends.add(friend) return chat } func addDemoConversationToChat(_ chat: OCTChat) { addFileMessage(chat: chat, outgoing: false, fileName: "party.png") addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_1")) addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_2")) addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_3")) addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_4")) addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_5")) addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_6")) addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_7")) } func addTextMessage(chat: OCTChat, outgoing: Bool, text: String) { let messageText = OCTMessageText() messageText.text = text messageText.isDelivered = outgoing let message = addMessageAbstract(chat: chat, outgoing: outgoing) message.messageText = messageText } func addFileMessage(chat: OCTChat, outgoing: Bool, fileName: String) { let messageFile = OCTMessageFile() messageFile.fileName = fileName messageFile.internalFilePath = Bundle.main.path(forResource: "dummy-photo", ofType: "jpg") messageFile.fileType = .ready messageFile.fileUTI = kUTTypeImage as String let message = addMessageAbstract(chat: chat, outgoing: outgoing) message.messageFile = messageFile } func addCallMessage(chat: OCTChat, outgoing: Bool, answered: Bool, duration: TimeInterval) { let messageCall = OCTMessageCall() messageCall.callDuration = duration messageCall.callEvent = answered ? .answered : .unanswered let message = addMessageAbstract(chat: chat, outgoing: outgoing) message.messageCall = messageCall } func addMessageAbstract(chat: OCTChat, outgoing: Bool) -> OCTMessageAbstract { let message = OCTMessageAbstract() if !outgoing { let friend = chat.friends.firstObject() as! OCTFriend message.senderUniqueIdentifier = friend.uniqueIdentifier } message.chatUniqueIdentifier = chat.uniqueIdentifier message.dateInterval = Date().timeIntervalSince1970 realm.add(message) chat.lastMessage = message return message } }
mit
6b8d7d3bf9b4022c4ba0fae493dccca5
41.12
115
0.668922
4.531469
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/About/Settings/Sections/Language/LanagageCell.swift
1
2643
// // LanagageCell.swift // EclipseSoundscapes // // Created by Arlindo on 12/26/20. // Copyright © 2020 Eclipse Soundscapes. All rights reserved. // import RxSwift class LanguageCell: RxTableViewCell, SettingCell { private let infoLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.preferredFont(forTextStyle: .body) label.adjustsFontForContentSizeCategory = true label.numberOfLines = 0 return label }() private let settingsButton: RoundedButton = { let button = RoundedButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) button.titleLabel?.adjustsFontForContentSizeCategory = true button.addSqueeze() button.backgroundColor = SoundscapesColor.eclipseOrange return button }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { selectionStyle = .none contentView.addSubviews(infoLabel, settingsButton) [infoLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), infoLabel.bottomAnchor.constraint(equalTo: settingsButton.topAnchor, constant: -16), infoLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), infoLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), settingsButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), settingsButton.leftAnchor.constraint(equalTo: infoLabel.leftAnchor), settingsButton.rightAnchor.constraint(equalTo: infoLabel.rightAnchor), settingsButton.heightAnchor.constraint(greaterThanOrEqualToConstant: 50) ].forEach { $0.isActive = true } } func configure(with settingItem: SettingItem) { guard let languageSettingItem = settingItem as? LanguageSettingItem else { return } infoLabel.text = languageSettingItem.info settingsButton.setTitle(languageSettingItem.setingsButtonTitle, for: .normal) settingsButton.rx.tap .map { Action.openDeviceSettings } .bind(to: languageSettingItem.rx.react) .disposed(by: disposeBag) } }
gpl-3.0
10922dbda3ae0ca0bb5558c2c54bd764
36.742857
97
0.688115
5.19057
false
false
false
false
glessard/swift-channels
ChannelsTests/SelectTests.swift
1
7293
// // SelectTests.swift // Channels // // Created by Guillaume Lessard on 2015-01-15. // Copyright (c) 2015 Guillaume Lessard. All rights reserved. // import Darwin import Foundation import XCTest @testable import Channels class SelectUnbufferedTests: XCTestCase { var selectableCount: Int { return 10 } func MakeChannels() -> [Chan<Int>] { return (0..<selectableCount).map { _ in Chan<Int>.Make() } } func getIterations(_ sleepInterval: TimeInterval) -> Int { return sleepInterval < 0 ? ChannelsTests.performanceTestIterations : 100 } func SelectReceiverTest(sleepInterval: TimeInterval = -1) { let iterations = getIterations(sleepInterval) let channels = MakeChannels() let senders = channels.map { Sender($0) } let receivers = channels.map { Receiver($0) } async { if sleepInterval > 0 { for i in 0..<iterations { Foundation.Thread.sleep(forTimeInterval: sleepInterval) let index = Int(arc4random_uniform(UInt32(senders.count))) senders[index] <- i } Foundation.Thread.sleep(forTimeInterval: sleepInterval > 0 ? sleepInterval : 1e-6) for sender in senders { sender.close() } } else { for i in 0..<senders.count { let sender = senders[i] let messages = iterations/senders.count + ((i < iterations%senders.count) ? 1:0) DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!).async { for m in 0..<messages { sender.send(m) } sender.close() } } } } var i = 0 // Currently required to avoid a runtime crash: let selectables = receivers.map { $0 as Selectable } while let selection = select_chan(selectables) { if let receiver = selection.id as? Receiver<Int> { if let _ = receiver.extract(selection) { i += 1 } } } XCTAssert(i == iterations, "Received \(i) messages; expected \(iterations)") } func testPerformanceSelectReceiver() { self.measure { self.SelectReceiverTest() } } func testSelectReceiverWithSleep() { SelectReceiverTest(sleepInterval: 0.01) } func SelectSenderTest(sleepInterval: TimeInterval = -1) { let iterations = getIterations(sleepInterval) let channels = MakeChannels() let senders = channels.map { Sender($0) } let receivers = channels.map { Receiver($0) } async { var i = 0 // Currently required to avoid a runtime crash: let selectables = senders.map { $0 as Selectable } while i < iterations, let selection = select_chan(selectables) { if let sender = selection.id as? Sender<Int> { if sender.insert(selection, newElement: i) { i += 1 } } } for sender in senders { sender.close() } } var m = 0 if sleepInterval > 0 { let receiver = merge(receivers) while let _ = receiver.receive() { m += 1 Foundation.Thread.sleep(forTimeInterval: sleepInterval) } } else { let result = Channel<Int>.Make(channels.count) let g = DispatchGroup() let q = DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!) for i in 0..<channels.count { let receiver = receivers[i] q.async(group: g) { var i = 0 while let _ = receiver.receive() { i += 1 } result.tx <- i } } g.notify(queue: q) { result.tx.close() } while let count = <-result.rx { m += count } } XCTAssert(m == iterations, "Received \(m) messages; expected \(iterations)") } func testPerformanceSelectSender() { self.measure { self.SelectSenderTest() } } func testSelectSenderWithSleep() { SelectSenderTest(sleepInterval: 0.01) } fileprivate enum Sleeper { case receiver; case sender; case none } fileprivate func DoubleSelectTest(sleeper: Sleeper) { let sleepInterval = (sleeper == .none) ? -1.0 : 0.01 let iterations = getIterations(sleepInterval) let channels = MakeChannels() let senders = channels.map { Sender($0) } let receivers = channels.map { Receiver($0) } async { var i = 0 // Currently required to avoid a runtime crash: let selectables = senders.map { $0 as Selectable } while let selection = select_chan(selectables) { if let sender = selection.id as? Sender<Int> { if sender.insert(selection, newElement: i) { i += 1 if sleeper == .sender { Foundation.Thread.sleep(forTimeInterval: sleepInterval) } if i >= iterations { break } } } } for sender in senders { sender.close() } } var i = 0 // Currently required to avoid a runtime crash: let selectables = receivers.map { $0 as Selectable } while let selection = select_chan(selectables) { if let receiver = selection.id as? Receiver<Int> { if let _ = receiver.extract(selection) { i += 1 if sleeper == .receiver { Foundation.Thread.sleep(forTimeInterval: sleepInterval) } } } } XCTAssert(i == iterations, "Received \(i) messages; expected \(iterations)") } func testPerformanceDoubleSelect() { self.measure { self.DoubleSelectTest(sleeper: .none) } } func testDoubleSelectSlowGet() { DoubleSelectTest(sleeper: .receiver) } func testDoubleSelectSlowPut() { DoubleSelectTest(sleeper: .sender) } func testSelectAndCloseReceivers() { let channels = MakeChannels() let senders = channels.map { Sender(channelType: $0) } let receivers = channels.map { Receiver(channelType: $0) } let q = DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!) q.asyncAfter(deadline: DispatchTime.now() + Double(10_000_000) / Double(NSEC_PER_SEC)) { for sender in senders { sender.close() } } let selectables = receivers.map { $0 as Selectable } while let selection = select_chan(selectables) { if selection.id is Receiver<Int> { XCTFail("Should not return one of our Receivers") } } } func testSelectAndCloseSenders() { let channels = MakeChannels() let senders = channels.map { Sender(channelType: $0) } let q = DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!) q.asyncAfter(deadline: DispatchTime.now() + Double(10_000_000) / Double(NSEC_PER_SEC)) { for sender in senders { sender.close() } } for sender in senders { // fill up the buffers so that the select_chan() below will block while sender.isFull == false { sender <- 0 } } let selectables = senders.map { $0 as Selectable } while let selection = select_chan(selectables) { if selection.id is Sender<Int> { XCTFail("Should not return one of our Senders") } } } } class SelectBufferedTests: SelectUnbufferedTests { override func MakeChannels() -> [Chan<Int>] { return (0..<selectableCount).map { _ in Chan<Int>.Make(1) } } }
mit
d49456e2502165f07b72a2b60dbddecd
25.046429
94
0.607295
3.972222
false
true
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Views/Home/ZXCHomeController.swift
1
5759
// // ZXCHomeController.swift // WeiBo // // Created by Aioria on 2017/3/26. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit import YYModel class ZXCHomeController: ZXCVistorViewController { // lazy var statusList: [ZXCStatus] = [ZXCStatus]() fileprivate lazy var pullUpView: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) indicatorView.color = UIColor.red return indicatorView }() // fileprivate lazy var pullDownView: UIRefreshControl = { // // let refresh = UIRefreshControl() // // refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged) // // return refresh // }() fileprivate lazy var pullDownView: ZXCRefreshControl = { let refresh = ZXCRefreshControl() refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged) return refresh }() fileprivate lazy var labTip: UILabel = { let lab = UILabel() lab.text = "没有加载到最新数据" lab.isHidden = true lab.textColor = UIColor.white lab.backgroundColor = UIColor.orange lab.font = UIFont.systemFont(ofSize: 15) lab.textAlignment = .center return lab }() fileprivate lazy var homeViewModel: ZXCHomeViewModel = ZXCHomeViewModel() override func viewDidLoad() { super.viewDidLoad() if !isLogin { visitorView?.updateVisitorInfo(imgName: nil, message: nil) } else { loadData() setupUI() } } fileprivate func setupUI() { setupTableView() if let nav = self.navigationController { nav.view.insertSubview(labTip, belowSubview: nav.navigationBar) labTip.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.width, height: 35) } } fileprivate func setupTableView() { tableView.register(ZXCHomeTableViewCell.self, forCellReuseIdentifier: homeReuseID) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 tableView.separatorStyle = .none tableView.tableFooterView = pullUpView // self.refreshControl = pullDownView tableView.addSubview(pullDownView) } fileprivate func loadData() { // ZXCNetworkTools.sharedTools.requestHomeData(accessToken: ZXCUserAccountViewModel.sharedViewModel.accessToken!) { (response, error) in // // if error != nil { // } // // guard let dict = response as? [String: Any] else { // return // } // // let statusDic = dict["statuses"] as? [[String: Any]] // // let statusArray = NSArray.yy_modelArray(with: ZXCStatus.self, json: statusDic!) as! [ZXCStatus] // // self.statusList = statusArray // // self.tableView.reloadData() // } homeViewModel.requestHomeData(isPullup: pullUpView.isAnimating) { (isSuccess, message) in if self.pullUpView.isAnimating == false { if self.labTip.isHidden == false { return } self.tipAnimation(message: message) } self.endRefreshing() if isSuccess { self.tableView.reloadData() } } } fileprivate func endRefreshing() { pullUpView.stopAnimating() pullDownView.endRefreshing() } // MARK: DataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.homeViewModel.statusList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ZXCHomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: homeReuseID, for: indexPath) as! ZXCHomeTableViewCell cell.statusViewModel = homeViewModel.statusList[indexPath.row] // cell.textLabel?.text = homeViewModel.statusList[indexPath.row].user?.screen_name return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == homeViewModel.statusList.count - 1 && !pullUpView.isAnimating{ pullUpView.startAnimating() loadData() } } @objc fileprivate func pullDownrefreshAction () { loadData() } fileprivate func tipAnimation(message: String) { labTip.text = message labTip.isHidden = false UIView.animate(withDuration: 1, animations: { self.labTip.transform = CGAffineTransform(translationX: 0, y: self.labTip.height) }) { (_) in UIView.animate(withDuration: 1, animations: { self.labTip.transform = CGAffineTransform.identity }, completion: { (_) in self.labTip.isHidden = true }) } } }
mit
54249e99eda0eae96f0e8daed92c33a6
27.405941
143
0.554549
5.367633
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/Pods/FacebookShare/Sources/Share/Views/LikeButton.swift
1
4045
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit /** A button to like an object. Tapping the receiver will invoke an API call to the Facebook app through a fast-app-switch that allows the object to be liked. Upon return to the calling app, the view will update with the new state. If the currentAccessToken has "publish_actions" permission and the object is an Open Graph object, then the like can happen seamlessly without the fast-app-switch. */ public class LikeButton: UIView { private var sdkLikeButton: FBSDKLikeButton /// If `true`, a sound is played when the reciever is toggled. public var isSoundEnabled: Bool { get { return sdkLikeButton.soundEnabled } set { sdkLikeButton.soundEnabled = newValue } } /// The object to like public var object: LikableObject { get { return LikableObject(sdkObjectType: sdkLikeButton.objectType, sdkObjectId: sdkLikeButton.objectID) } set { let sdkRepresentation = newValue.sdkObjectRepresntation sdkLikeButton.objectType = sdkRepresentation.objectType sdkLikeButton.objectID = sdkRepresentation.objectId } } /** Create a new LikeButton with a given frame and object. - parameter frame: The frame to initialize with. - parameter object: The object to like. */ public init(frame: CGRect? = nil, object: LikableObject) { let sdkLikeButton = FBSDKLikeButton() let frame = frame ?? sdkLikeButton.bounds self.sdkLikeButton = sdkLikeButton super.init(frame: frame) self.object = object self.addSubview(sdkLikeButton) } /** Create a new LikeButton from an encoded interface file. - parameter aDecoder: The coder to initialize from. */ public required init?(coder aDecoder: NSCoder) { sdkLikeButton = FBSDKLikeButton() super.init(coder: aDecoder) addSubview(sdkLikeButton) } /** Performs logic for laying out subviews. */ public override func layoutSubviews() { super.layoutSubviews() sdkLikeButton.frame = CGRect(origin: .zero, size: bounds.size) } /** Resizes and moves the receiver view so it just encloses its subviews. */ public override func sizeToFit() { bounds.size = sizeThatFits(CGSize(width: CGFloat.max, height: CGFloat.max)) } /** Asks the view to calculate and return the size that best fits the specified size. - parameter size: A new size that fits the receiver’s subviews. - returns: A new size that fits the receiver’s subviews. */ public override func sizeThatFits(size: CGSize) -> CGSize { return sdkLikeButton.sizeThatFits(size) } /** Returns the natural size for the receiving view, considering only properties of the view itself. - returns: A size indicating the natural size for the receiving view based on its intrinsic properties. */ public override func intrinsicContentSize() -> CGSize { return sdkLikeButton.intrinsicContentSize() } }
mit
2e3be77d6e4cabbbdac772c59b01b191
32.396694
117
0.729522
4.520134
false
false
false
false
ziligy/JGScrollerController
JGScrollerController/JGTapButton.swift
1
8144
// // JGTapButton.swift // // Created by Jeff on 8/20/15. // Copyright © 2015 Jeff Greenberg. All rights reserved. // import UIKit enum TapButtonShape { case Round case Rectangle } enum TapButtonStyle { case Raised case Flat } @IBDesignable public class JGTapButton: UIButton { // MARK: Inspectables // select round or rectangle button shape @IBInspectable public var round: Bool = true { didSet { buttonShape = (round ? .Round : .Rectangle) } } // select raised or flat style @IBInspectable public var raised: Bool = true { didSet { buttonStyle = (raised ? .Raised : .Flat) } } // set title caption for button @IBInspectable public var title: String = "JGTapButton" { didSet { buttonTitle = title } } // optional button image @IBInspectable public var image: UIImage=UIImage() { didSet { setButtonImage() } } @IBInspectable public var imageInset: CGFloat = 0 { didSet { setButtonImage() } } // main background button color @IBInspectable public var mainColor: UIColor = UIColor.redColor() { didSet { buttonColor = mainColor } } // title font size @IBInspectable public var fontsize: CGFloat = 22.0 { didSet { titleFontSize = fontsize } } @IBInspectable public var fontColor: UIColor = UIColor.whiteColor() // MARK: Private variables private var buttonShape = TapButtonShape.Round private var buttonStyle = TapButtonStyle.Flat private var buttonTitle = "" private var buttonColor = UIColor.redColor() private var titleFontSize: CGFloat = 22.0 private var tapButtonFrame = CGRectMake(0, 0, 100, 100) // outline shape of button from draw private var outlinePath = UIBezierPath() // variables for glow animation private let tapGlowView = UIView() private let tapGlowBackgroundView = UIView() private var tapGlowColor = UIColor(white: 0.9, alpha: 1) private var tapGlowBackgroundColor = UIColor(white: 0.95, alpha: 1) private var tapGlowMask: CAShapeLayer? { get { let maskLayer = CAShapeLayer() maskLayer.path = outlinePath.CGPath return maskLayer } } // optional image for private var iconImageView = UIImageView(frame: CGRectMake(0, 0, 40, 40)) // MARK: Initialize func initMaster() { self.backgroundColor = UIColor.clearColor() self.addSubview(iconImageView) } override init(frame: CGRect) { super.init(frame: frame) initMaster() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initMaster() } convenience init(sideSize: CGFloat) { self.init(frame: CGRect(x: 0, y: 0, width: sideSize, height: sideSize)) } override public func prepareForInterfaceBuilder() { invalidateIntrinsicContentSize() self.backgroundColor = UIColor.clearColor() } // MARK: Layout override public func layoutSubviews() { super.layoutSubviews() iconImageView.layer.mask = tapGlowMask tapGlowBackgroundView.layer.mask = tapGlowMask } // override intrinsic size for uibutton public override func intrinsicContentSize() -> CGSize { return bounds.size } // MARK: draw override public func drawRect(rect: CGRect) { outlinePath = drawTapButton(buttonShape, buttonTitle: buttonTitle, fontsize: titleFontSize) tapGlowSetup() } private func tapGlowSetup() { tapGlowBackgroundView.backgroundColor = tapGlowBackgroundColor tapGlowBackgroundView.frame = bounds layer.addSublayer(tapGlowBackgroundView.layer) tapGlowBackgroundView.layer.addSublayer(tapGlowView.layer) tapGlowBackgroundView.alpha = 0 } private func drawTapButton(buttonShape: TapButtonShape, buttonTitle: String, fontsize: CGFloat) -> UIBezierPath { var bezierPath: UIBezierPath! if buttonStyle == .Raised { tapButtonFrame = CGRectMake(1, 1, CGRectGetWidth(self.bounds) - 2, CGRectGetHeight(self.bounds) - 2) } else { tapButtonFrame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) } let context = UIGraphicsGetCurrentContext() if buttonShape == .Round { bezierPath = UIBezierPath(ovalInRect: tapButtonFrame) } else { bezierPath = UIBezierPath(rect: tapButtonFrame) } buttonColor.setFill() bezierPath.fill() let shadow = UIColor.blackColor().CGColor let shadowOffset = CGSizeMake(3.1, 3.1) let shadowBlurRadius: CGFloat = 7 if buttonStyle == .Raised { CGContextSaveGState(context) CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow) fontColor.setStroke() bezierPath.lineWidth = 1 bezierPath.stroke() CGContextRestoreGState(context) } // MARK: Title Text if image == "" || iconImageView.image == nil { let buttonTitleTextContent = NSString(string: buttonTitle) CGContextSaveGState(context) if buttonStyle == .Raised { CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow) } let buttonTitleStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle buttonTitleStyle.alignment = NSTextAlignment.Center let buttonTitleFontAttributes = [NSFontAttributeName: UIFont(name: "AppleSDGothicNeo-Regular", size: fontsize)!, NSForegroundColorAttributeName: fontColor, NSParagraphStyleAttributeName: buttonTitleStyle] let buttonTitleTextHeight: CGFloat = buttonTitleTextContent.boundingRectWithSize(CGSizeMake(tapButtonFrame.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: buttonTitleFontAttributes, context: nil).size.height CGContextSaveGState(context) CGContextClipToRect(context, tapButtonFrame); buttonTitleTextContent.drawInRect(CGRectMake(tapButtonFrame.minX, tapButtonFrame.minY + (tapButtonFrame.height - buttonTitleTextHeight) / 2, tapButtonFrame.width, buttonTitleTextHeight), withAttributes: buttonTitleFontAttributes) CGContextRestoreGState(context) CGContextRestoreGState(context) } return bezierPath } private func setButtonImage() { iconImageView.frame = CGRectMake(imageInset, imageInset, CGRectGetWidth(self.frame) - imageInset*2, CGRectGetHeight(self.frame) - imageInset*2) iconImageView.image = self.image } // MARK: Tap events override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { UIView.animateWithDuration(0.1, animations: { self.tapGlowBackgroundView.alpha = 1 }, completion: nil) return super.beginTrackingWithTouch(touch, withEvent: event) } override public func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { super.endTrackingWithTouch(touch, withEvent: event) UIView.animateWithDuration(0.1, animations: { self.tapGlowBackgroundView.alpha = 1 }, completion: {(success: Bool) -> () in UIView.animateWithDuration(0.6 , animations: { self.tapGlowBackgroundView.alpha = 0 }, completion: nil) }) } }
mit
5b3a6d47d77c44c32bea45ec3a459f6f
31.313492
265
0.620656
5.403451
false
false
false
false
dfortuna/theCraic3
theCraic3/Main/Common/InputTagsTableViewCell.swift
1
1679
// // InputTagsTableViewCell.swift // theCraic3 // // Created by Denis Fortuna on 23/5/18. // Copyright © 2018 Denis. All rights reserved. // import UIKit protocol TagsProtocol: class { func emitAlertSpecialCharacters(sender: InputTagsTableViewCell) func tagAdded(sender: InputTagsTableViewCell) } class InputTagsTableViewCell: UITableViewCell { weak var delegate: TagsProtocol? var tagAdded = String() @IBOutlet weak var displayTagsScrollView: DisplayTagsScrollView! @IBOutlet weak var tagsTextField: UITextField! @IBAction func okButton(_ sender: UIButton) { if let tag = tagsTextField.text { if testStringForBallon(forString: tag) { self.tagAdded = tag self.delegate?.tagAdded(sender: self) displayTagsScrollView.setupUI(forTag: tag, isClickable: true) } else { self.delegate?.emitAlertSpecialCharacters(sender: self) } } tagsTextField.text = "" } func updateUI(tags: [String], withTitle: Bool) { displayTagsScrollView.layer.borderWidth = 0.3 displayTagsScrollView.layer.borderColor = UIColor.lightGray.cgColor if !tags.isEmpty { for tag in tags { displayTagsScrollView.setupUI(forTag: tag, isClickable: true) } } } func testStringForBallon(forString tag: String) -> Bool { let charctersNotAllowed = [".","$","[","]","#","/"] for character in charctersNotAllowed { if tag.range(of: character) != nil { return false } } return true } }
apache-2.0
a5cc4dfba8dd3f6415cefebf700286b1
28.964286
77
0.61323
4.474667
false
false
false
false
eamosov/thrift
lib/swift/Sources/TSSLSocketTransport.swift
14
8028
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Foundation import CoreFoundation #if !swift(>=4.2) // Swift 3/4 compatibility fileprivate extension RunLoopMode { static let `default` = defaultRunLoopMode } #endif #if os(Linux) public class TSSLSocketTransport { init(hostname: String, port: UInt16) { // FIXME! assert(false, "Security not available in Linux, TSSLSocketTransport Unavilable for now") } } #else let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian let htons = isLittleEndian ? _OSSwapInt16 : { $0 } let htonl = isLittleEndian ? _OSSwapInt32 : { $0 } public class TSSLSocketTransport: TStreamTransport { var sslHostname: String var sd: Int32 = 0 public init(hostname: String, port: UInt16) throws { sslHostname = hostname var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? /* create a socket structure */ var pin: sockaddr_in = sockaddr_in() var hp: UnsafeMutablePointer<hostent>? = nil for i in 0..<10 { hp = gethostbyname(hostname.cString(using: String.Encoding.utf8)!) if hp == nil { print("failed to resolve hostname \(hostname)") herror("resolv") if i == 9 { super.init(inputStream: nil, outputStream: nil) // have to init before throwing throw TSSLSocketTransportError(error: .hostanameResolution(hostname: hostname)) } Thread.sleep(forTimeInterval: 0.2) } else { break } } pin.sin_family = UInt8(AF_INET) pin.sin_addr = in_addr(s_addr: UInt32((hp?.pointee.h_addr_list.pointee?.pointee)!)) // Is there a better way to get this??? pin.sin_port = htons(port) /* create the socket */ sd = socket(Int32(AF_INET), Int32(SOCK_STREAM), Int32(IPPROTO_TCP)) if sd == -1 { super.init(inputStream: nil, outputStream: nil) // have to init before throwing throw TSSLSocketTransportError(error: .socketCreate(port: Int(port))) } /* open a connection */ // need a non-self ref to sd, otherwise the j complains let sd_local = sd let connectResult = withUnsafePointer(to: &pin) { connect(sd_local, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size)) } if connectResult == -1 { super.init(inputStream: nil, outputStream: nil) // have to init before throwing throw TSSLSocketTransportError(error: .connect) } CFStreamCreatePairWithSocket(kCFAllocatorDefault, sd, &readStream, &writeStream) CFReadStreamSetProperty(readStream?.takeRetainedValue(), .socketNativeHandle, kCFBooleanTrue) CFWriteStreamSetProperty(writeStream?.takeRetainedValue(), .socketNativeHandle, kCFBooleanTrue) var inputStream: InputStream? = nil var outputStream: OutputStream? = nil if readStream != nil && writeStream != nil { CFReadStreamSetProperty(readStream?.takeRetainedValue(), .socketSecurityLevel, kCFStreamSocketSecurityLevelTLSv1) let settings: [String: Bool] = [kCFStreamSSLValidatesCertificateChain as String: true] CFReadStreamSetProperty(readStream?.takeRetainedValue(), .SSLSettings, settings as CFTypeRef) CFWriteStreamSetProperty(writeStream?.takeRetainedValue(), .SSLSettings, settings as CFTypeRef) inputStream = readStream!.takeRetainedValue() inputStream?.schedule(in: .current, forMode: .default) inputStream?.open() outputStream = writeStream!.takeRetainedValue() outputStream?.schedule(in: .current, forMode: .default) outputStream?.open() readStream?.release() writeStream?.release() } super.init(inputStream: inputStream, outputStream: outputStream) self.input?.delegate = self self.output?.delegate = self } func recoverFromTrustFailure(_ myTrust: SecTrust, lastTrustResult: SecTrustResultType) -> Bool { let trustTime = SecTrustGetVerifyTime(myTrust) let currentTime = CFAbsoluteTimeGetCurrent() let timeIncrement = 31536000 // from TSSLSocketTransport.m let newTime = currentTime - Double(timeIncrement) if trustTime - newTime != 0 { let newDate = CFDateCreate(nil, newTime) SecTrustSetVerifyDate(myTrust, newDate!) var tr = lastTrustResult let success = withUnsafeMutablePointer(to: &tr) { trPtr -> Bool in if SecTrustEvaluate(myTrust, trPtr) != errSecSuccess { return false } return true } if !success { return false } } if lastTrustResult == .proceed || lastTrustResult == .unspecified { return false } print("TSSLSocketTransport: Unable to recover certificate trust failure") return true } public func isOpen() -> Bool { return sd > 0 } } extension TSSLSocketTransport: StreamDelegate { public func stream(_ aStream: Stream, handle eventCode: Stream.Event) { switch eventCode { case Stream.Event(): break case Stream.Event.hasBytesAvailable: break case Stream.Event.openCompleted: break case Stream.Event.hasSpaceAvailable: var proceed = false var trustResult: SecTrustResultType = .invalid var newPolicies: CFMutableArray? repeat { let trust: SecTrust = aStream.property(forKey: .SSLPeerTrust) as! SecTrust // Add new policy to current list of policies let policy = SecPolicyCreateSSL(false, sslHostname as CFString?) var ppolicy = policy // mutable for pointer let policies: UnsafeMutablePointer<CFArray?>? = nil if SecTrustCopyPolicies(trust, policies!) != errSecSuccess { break } withUnsafeMutablePointer(to: &ppolicy) { ptr in newPolicies = CFArrayCreateMutableCopy(nil, 0, policies?.pointee) CFArrayAppendValue(newPolicies, ptr) } // update trust policies if SecTrustSetPolicies(trust, newPolicies!) != errSecSuccess { break } // Evaluate the trust chain let success = withUnsafeMutablePointer(to: &trustResult) { trustPtr -> Bool in if SecTrustEvaluate(trust, trustPtr) != errSecSuccess { return false } return true } if !success { break } switch trustResult { case .proceed: proceed = true case .unspecified: proceed = true case .recoverableTrustFailure: proceed = self.recoverFromTrustFailure(trust, lastTrustResult: trustResult) case .deny: break case .fatalTrustFailure: break case .otherError: break case .invalid: break default: break } } while false if !proceed { print("TSSLSocketTransport: Cannot trust certificate. Result: \(trustResult)") aStream.close() } case Stream.Event.errorOccurred: break case Stream.Event.endEncountered: break default: break } } } #endif
apache-2.0
50a1b17c48faa03536044c6d72e7a0e8
33.016949
130
0.649601
4.739079
false
false
false
false
tad-iizuka/swift-sdk
Source/DiscoveryV1/Models/Document.swift
2
2923
/** * 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. **/ import Foundation import RestKit /** A document to upload to a collection. */ public struct Document: JSONDecodable { /// Unique identifier of the ingested document. public let documentID: String /// The unique identifier of the collection's configuration. public let configurationID: String? /// The creation date of the document in the format yyyy-MM-dd'T'HH:mm /// :ss.SSS'Z'. public let created: String? /// The timestamp of when the document was last updated in the format /// yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. public let updated: String? /// The status of the document in ingestion process. public let status: DocumentStatus /// The description of the document status. public let statusDescription: String? /// The array of notices produced by the document-ingestion process. public let notices: [Notice]? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize a `Document` model from JSON. public init(json: JSON) throws { documentID = try json.getString(at: "document_id") configurationID = try? json.getString(at: "configuration_id") created = try? json.getString(at: "created") updated = try? json.getString(at: "updated") guard let documentStatus = DocumentStatus(rawValue: try json.getString(at: "status")) else { throw JSON.Error.valueNotConvertible(value: json, to: DocumentStatus.self) } status = documentStatus statusDescription = try? json.getString(at: "status_description") notices = try? json.decodedArray(at: "notices", type: Notice.self) self.json = try json.getDictionaryObject() } /// Used internally to serialize a 'Document' model to JSON. public func toJSONObject() -> Any { return json } } /** Status of a document uploaded to a collection. */ public enum DocumentStatus: String { /// Available case available = "available" /// Availabe with notices case availableWithNotices = "available with notices" /// Deleted case deleted = "deleted" /// Failed case failed = "failed" /// Processing case processing = "processing" }
apache-2.0
852df74376b7de4a2f1358bf24bd4a14
32.215909
100
0.669176
4.462595
false
false
false
false
boqian2000/swift-algorithm-club
Trie/Trie/TrieTests/TrieTests.swift
1
5284
// // TrieTests.swift // TrieTests // // Created by Rick Zaccone on 2016-12-12. // Copyright © 2016 Rick Zaccone. All rights reserved. // import XCTest @testable import Trie class TrieTests: XCTestCase { var wordArray: [String]? var trie = Trie() /// Makes sure that the wordArray and trie are initialized before each test. override func setUp() { super.setUp() createWordArray() insertWordsIntoTrie() } /// Don't need to do anything here because the wordArray and trie should /// stay around. override func tearDown() { super.tearDown() } /// Reads words from the dictionary file and inserts them into an array. If /// the word array already has words, do nothing. This allows running all /// tests without repeatedly filling the array with the same values. func createWordArray() { guard wordArray == nil else { return } let resourcePath = Bundle.main.resourcePath! as NSString let fileName = "dictionary.txt" let filePath = resourcePath.appendingPathComponent(fileName) var data: String? do { data = try String(contentsOfFile: filePath, encoding: String.Encoding.utf8) } catch let error as NSError { XCTAssertNil(error) } XCTAssertNotNil(data) let dictionarySize = 162825 wordArray = data!.components(separatedBy: "\n") XCTAssertEqual(wordArray!.count, dictionarySize) } /// Inserts words into a trie. If the trie is non-empty, don't do anything. func insertWordsIntoTrie() { guard let wordArray = wordArray, trie.count == 0 else { return } for word in wordArray { trie.insert(word: word) } } /// Tests that a newly created trie has zero words. func testCreate() { let trie = Trie() XCTAssertEqual(trie.count, 0) } /// Tests the insert method func testInsert() { let trie = Trie() trie.insert(word: "cute") trie.insert(word: "cutie") trie.insert(word: "fred") XCTAssertTrue(trie.contains(word: "cute")) XCTAssertFalse(trie.contains(word: "cut")) trie.insert(word: "cut") XCTAssertTrue(trie.contains(word: "cut")) XCTAssertEqual(trie.count, 4) } /// Tests the remove method func testRemove() { let trie = Trie() trie.insert(word: "cute") trie.insert(word: "cut") XCTAssertEqual(trie.count, 2) trie.remove(word: "cute") XCTAssertTrue(trie.contains(word: "cut")) XCTAssertFalse(trie.contains(word: "cute")) XCTAssertEqual(trie.count, 1) } /// Tests the words property func testWords() { let trie = Trie() var words = trie.words XCTAssertEqual(words.count, 0) trie.insert(word: "foobar") words = trie.words XCTAssertEqual(words[0], "foobar") XCTAssertEqual(words.count, 1) } /// Tests the performance of the insert method. func testInsertPerformance() { self.measure() { let trie = Trie() for word in self.wordArray! { trie.insert(word: word) } } XCTAssertGreaterThan(trie.count, 0) XCTAssertEqual(trie.count, wordArray?.count) } /// Tests the performance of the insert method when the words are already /// present. func testInsertAgainPerformance() { self.measure() { for word in self.wordArray! { self.trie.insert(word: word) } } } /// Tests the performance of the contains method. func testContainsPerformance() { self.measure() { for word in self.wordArray! { XCTAssertTrue(self.trie.contains(word: word)) } } } /// Tests the performance of the remove method. Since setup has already put /// words into the trie, remove them before measuring performance. func testRemovePerformance() { for word in self.wordArray! { self.trie.remove(word: word) } self.measure() { self.insertWordsIntoTrie() for word in self.wordArray! { self.trie.remove(word: word) } } XCTAssertEqual(trie.count, 0) } /// Tests the performance of the words computed property. Also tests to see /// if it worked properly. func testWordsPerformance() { var words: [String]? self.measure { words = self.trie.words } XCTAssertEqual(words?.count, trie.count) for word in words! { XCTAssertTrue(self.trie.contains(word: word)) } } /// Tests the archiving and unarchiving of the trie. func testArchiveAndUnarchive() { let resourcePath = Bundle.main.resourcePath! as NSString let fileName = "dictionary-archive" let filePath = resourcePath.appendingPathComponent(fileName) NSKeyedArchiver.archiveRootObject(trie, toFile: filePath) let trieCopy = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Trie XCTAssertEqual(trieCopy.count, trie.count) } }
mit
09f29b237d22bd143c451f95aaa7e3f5
29.894737
87
0.599849
4.49617
false
true
false
false
haawa799/WaniKani-Kanji-Strokes
Pods/WaniKit/Pod/Classes/WaniKit operations/UserInfo/ParseUserInfoOperation.swift
1
746
// // ParseUserInfoOperation.swift // Pods // // Created by Andriy K. on 12/14/15. // // import UIKit public typealias UserInfoResponse = (UserInfo?) public typealias UserInfoResponseHandler = (Result<UserInfoResponse, NSError>) -> Void public class ParseUserInfoOperation: ParseOperation<UserInfoResponse> { override init(cacheFile: NSURL, handler: ResponseHandler) { super.init(cacheFile: cacheFile, handler: handler) name = "Parse User info" } override func parsedValue(rootDictionary: NSDictionary?) -> UserInfoResponse? { var user: UserInfo? if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary { user = UserInfo(dict: userInfo) } return user } }
mit
7d75407c2cc4156d8a0ae4ccfe8edf7b
23.9
99
0.72252
4.167598
false
false
false
false
naoto0822/transient-watch-ios
TransientWatch/Domain/Entity/AstroObj.swift
1
1108
// // AstroObj.swift // TransientWatch // // Created by naoto yamaguchi on 2015/04/12. // Copyright (c) 2015年 naoto yamaguchi. All rights reserved. // import UIKit class AstroObj: NSObject { // MARK: - Property var id: Int? var name: String? var ra: Float? var dec: Float? var astroClassId: Int? var fluxRate: Int? var link: String? // MARK: - LifeCycle init(response: [String: AnyObject?]) { super.init() let fluxRate = response["flux_rate"] as? Int let astroObj = response["astroObj"] as [String: AnyObject] let id = astroObj["id"] as? Int let name = astroObj["name"] as? String let ra = astroObj["ra"] as? Float let dec = astroObj["dec"] as? Float let astroClassId = astroObj["astro_class_id"] as? Int let link = astroObj["link"] as? String self.id = id self.name = name self.ra = ra self.dec = dec self.astroClassId = astroClassId self.fluxRate = fluxRate self.link = link } }
gpl-3.0
a35f5b2383bbceb284f03d9df2d5cb8c
23.043478
66
0.560579
3.579288
false
false
false
false
TotalDigital/People-iOS
People at Total/OAuth2RetryHandler.swift
1
2355
// // OAuth2RetryHandler.swift // People at Total // // Created by Florian Letellier on 14/03/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import Foundation import p2_OAuth2 import Alamofire /** An adapter for Alamofire. Set up your OAuth2 instance as usual, without forgetting to implement `handleRedirectURL()`, instantiate **one** `SessionManager` and use this class as the manager's `adapter` and `retrier`, like so: let oauth2 = OAuth2CodeGrant(settings: [...]) oauth2.authConfig.authorizeEmbedded = true // if you want embedded oauth2.authConfig.authorizeContext = <# your UIViewController / NSWindow #> let sessionManager = SessionManager() let retrier = OAuth2RetryHandler(oauth2: oauth2) sessionManager.adapter = retrier sessionManager.retrier = retrier self.alamofireManager = sessionManager sessionManager.request("https://api.github.com/user").validate().responseJSON { response in debugPrint(response) } */ class OAuth2RetryHandler: RequestRetrier, RequestAdapter { let loader: OAuth2DataLoader init(oauth2: OAuth2) { loader = OAuth2DataLoader(oauth2: oauth2) } /// Intercept 401 and do an OAuth2 authorization. public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { if let response = request.task?.response as? HTTPURLResponse, 401 == response.statusCode, let req = request.request { var dataRequest = OAuth2DataRequest(request: req, callback: { _ in }) dataRequest.context = completion loader.enqueue(request: dataRequest) loader.attemptToAuthorize() { authParams, error in self.loader.dequeueAndApply() { req in if let comp = req.context as? RequestRetryCompletion { comp(nil != authParams, 0.0) } } } } else { completion(false, 0.0) // not a 401, not our problem } } /// Sign the request with the access token. public func adapt(_ urlRequest: URLRequest) throws -> URLRequest { guard nil != loader.oauth2.accessToken else { return urlRequest } return try urlRequest.signed(with: loader.oauth2) } }
apache-2.0
13aa308444bd163e87231720d86a1d95
34.134328
140
0.661427
4.570874
false
false
false
false
cornerAnt/PilesSugar
PilesSugar/PilesSugar/Module/Club/ClubClub/Controller/ClubClubController.swift
1
3585
// // ClubClubController.swift // PilesSugar // // Created by SoloKM on 16/1/21. // Copyright © 2016年 SoloKM. All rights reserved. // import UIKit private let ClubClubCellID = "ClubClubCell" class ClubClubController: UITableViewController { var models = [ClubClubModel]() override func viewDidLoad() { super.viewDidLoad() setupTableView() } init(){ super.init(style: UITableViewStyle.Grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupTableView() { tableView!.registerNib(UINib(nibName: ClubClubCellID, bundle: nil), forCellReuseIdentifier: ClubClubCellID) tableView!.tableFooterView = UIView() tableView!.rowHeight = 50 tableView!.contentInset.top = 29 tableView!.sectionHeaderHeight = 0 tableView!.sectionFooterHeight = 10 loadNewData() // tableView!.mj_header = RefreshHeader.init(refreshingBlock: { () -> Void in // // self.loadNewData() // }) // tableView!.mj_header.beginRefreshing() } private func loadNewData(){ let url = "http://www.duitang.com/napi/club/list/by_user_id/?app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=Unknown%20iPhone&device_platform=iPhone6%2C1&include_fields=check_in&limit=0&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2.1&screen_height=568&screen_width=320&start=0&user_id=11189659" NetWorkTool.sharedInstance.get(url, parameters: nil, success: { (response) -> () in self.models = ClubClubModel.loadClubClubModels(response!) self.tableView.reloadData() // self.tableView!.mj_header.endRefreshing() }) { (error) -> () in DEBUGLOG(error) // self.tableView!.mj_header.endRefreshing() } } } // MARK: - TableviewDataSource extension ClubClubController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? models.count : 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ClubClubCellID, forIndexPath: indexPath) as! ClubClubCell if indexPath.section == 0 { cell.clubClubModel = models[indexPath.row] cell.nameLabel.textColor = UIColor.blackColor() }else { cell.photoImageView.image = UIImage(named: "more_club") cell.nameLabel.text = "浏览更多Club" cell.nameLabel.textColor = UIColor.grayColor() cell.unreadLabel.text = ">" } return cell } } // MARK: - TableviewDelegate extension ClubClubController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 { let vc = ClubMoreController() navigationController?.pushViewController(vc, animated: true) } } }
apache-2.0
b2d5494dbf9ec1a730d40024761e9159
25.279412
327
0.589256
4.803763
false
false
false
false
jameszaghini/bonjour-demo-osx-to-ios
bonjour-demo-mac/BonjourServer.swift
1
6091
// // BonjourServer.swift // bonjour-demo-mac // // Created by James Zaghini on 14/05/2015. // Copyright (c) 2015 James Zaghini. All rights reserved. // import Cocoa enum PacketTag: Int { case header = 1 case body = 2 } protocol BonjourServerDelegate { func connected() func disconnected() func handleBody(_ body: NSString?) func didChangeServices() } class BonjourServer: NSObject, NetServiceBrowserDelegate, NetServiceDelegate, GCDAsyncSocketDelegate { var delegate: BonjourServerDelegate! var coServiceBrowser: NetServiceBrowser! var devices: Array<NetService>! var connectedService: NetService! var sockets: [String : GCDAsyncSocket]! override init() { super.init() self.devices = [] self.sockets = [:] self.startService() } func parseHeader(_ data: Data) -> UInt { var out: UInt = 0 (data as NSData).getBytes(&out, length: MemoryLayout<UInt>.size) return out } func handleResponseBody(_ data: Data) { if let message = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { self.delegate.handleBody(message) } } func connectTo(_ service: NetService) { service.delegate = self service.resolve(withTimeout: 15) } // MARK: NSNetServiceBrowser helpers func stopBrowsing() { if self.coServiceBrowser != nil { self.coServiceBrowser.stop() self.coServiceBrowser.delegate = nil self.coServiceBrowser = nil } } func startService() { if self.devices != nil { self.devices.removeAll(keepingCapacity: true) } self.coServiceBrowser = NetServiceBrowser() self.coServiceBrowser.delegate = self self.coServiceBrowser.searchForServices(ofType: "_probonjore._tcp.", inDomain: "local.") } func send(_ data: Data) { print("send data") if let socket = self.getSelectedSocket() { var header = data.count let headerData = Data(bytes: &header, count: MemoryLayout<UInt>.size) socket.write(headerData, withTimeout: -1.0, tag: PacketTag.header.rawValue) socket.write(data, withTimeout: -1.0, tag: PacketTag.body.rawValue) } } func connectToServer(_ service: NetService) -> Bool { var connected = false let addresses: Array = service.addresses! var socket = self.sockets[service.name] if !(socket?.isConnected != nil) { socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main) while !connected && !addresses.isEmpty { let address: Data = addresses[0] do { if (try socket?.connect(toAddress: address) != nil) { self.sockets.updateValue(socket!, forKey: service.name) self.connectedService = service connected = true } } catch { print(error); } } } return true } // MARK: NSNetService Delegates func netServiceDidResolveAddress(_ sender: NetService) { print("did resolve address \(sender.name)") if self.connectToServer(sender) { print("connected to \(sender.name)") } } func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) { print("net service did no resolve. errorDict: \(errorDict)") } // MARK: GCDAsyncSocket Delegates func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { print("connected to host \(String(describing: host)), on port \(port)") sock.readData(toLength: UInt(MemoryLayout<UInt64>.size), withTimeout: -1.0, tag: 0) } func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { print("socket did disconnect \(String(describing: sock)), error: \(String(describing: err?._userInfo))") } func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { print("socket did read data. tag: \(tag)") if self.getSelectedSocket() == sock { if data.count == MemoryLayout<UInt>.size { let bodyLength: UInt = self.parseHeader(data) sock.readData(toLength: bodyLength, withTimeout: -1, tag: PacketTag.body.rawValue) } else { self.handleResponseBody(data) sock.readData(toLength: UInt(MemoryLayout<UInt>.size), withTimeout: -1, tag: PacketTag.header.rawValue) } } } func socketDidCloseReadStream(_ sock: GCDAsyncSocket) { print("socket did close read stream") } // MARK: NSNetServiceBrowser Delegates func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didFind aNetService: NetService, moreComing: Bool) { self.devices.append(aNetService) if !moreComing { self.delegate.didChangeServices() } } func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didRemove aNetService: NetService, moreComing: Bool) { self.devices.removeObject(aNetService) if !moreComing { self.delegate.didChangeServices() } } func netServiceBrowserDidStopSearch(_ aNetServiceBrowser: NetServiceBrowser) { self.stopBrowsing() } func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) { self.stopBrowsing() } // MARK: helpers func getSelectedSocket() -> GCDAsyncSocket? { var sock: GCDAsyncSocket? if self.connectedService != nil { sock = self.sockets[self.connectedService.name]! } return sock } }
mit
f7200a1ded376575f9e7ebb3d570f4d0
30.559585
122
0.592185
4.857257
false
false
false
false
gowansg/firefox-ios
Utils/DeferredUtils.swift
3
2082
/* 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/. */ // Haskell, baby. // Monadic bind/flatMap operator for Deferred. infix operator >>== { associativity left precedence 160 } public func >>== <T, U>(x: Deferred<Result<T>>, f: T -> Deferred<Result<U>>) -> Deferred<Result<U>> { return chainDeferred(x, f) } // A termination case. public func >>== <T, U>(x: Deferred<Result<T>>, f: T -> ()) { return x.upon { result in if let v = result.successValue { f(v) } } } // Monadic `do` for Deferred. infix operator >>> { associativity left precedence 150 } public func >>> <T, U>(x: Deferred<Result<T>>, f: () -> Deferred<Result<U>>) -> Deferred<Result<U>> { return x.bind { res in if res.isSuccess { return f(); } return deferResult(res.failureValue!) } } /** * Returns a thunk that return a Deferred that resolves to the provided value. */ public func always<T>(t: T) -> () -> Deferred<Result<T>> { return { deferResult(t) } } public func deferResult<T>(s: T) -> Deferred<Result<T>> { return Deferred(value: Result(success: s)) } public func deferResult<T>(e: ErrorType) -> Deferred<Result<T>> { return Deferred(value: Result(failure: e)) } public func chainDeferred<T, U>(a: Deferred<Result<T>>, f: T -> Deferred<Result<U>>) -> Deferred<Result<U>> { return a.bind { res in if let v = res.successValue { return f(v) } return Deferred(value: Result<U>(failure: res.failureValue!)) } } public func chainResult<T, U>(a: Deferred<Result<T>>, f: T -> Result<U>) -> Deferred<Result<U>> { return a.map { res in if let v = res.successValue { return f(v) } return Result<U>(failure: res.failureValue!) } } public func chain<T, U>(a: Deferred<Result<T>>, f: T -> U) -> Deferred<Result<U>> { return chainResult(a, { Result<U>(success: f($0)) }) }
mpl-2.0
32848589fb78e6824a59a8034389cb5f
28.742857
109
0.604227
3.424342
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Services/User/ApiUserService.swift
1
2564
// // Copyright © 2022 Ingresse. All rights reserved. // import Foundation public class ApiUserService: BaseService { public typealias CustomApiResult<U: Decodable> = ApiResult<U, ResponseError, ResponseError> public typealias UserTransactionsResponse = PagedResponse<UserTransactionResponse> public func getTransactions(request: UserTransactionsRequest, queue: DispatchQueue, completion: @escaping (CustomApiResult<UserTransactionsResponse>) -> Void) { let urlRequest = ApiUserURLRequest.GetTransactions(request: request, environment: client.environment, userAgent: client.userAgent, apiKey: client.apiKey, authToken: client.authToken) Network.apiRequest(queue: queue, networkURLRequest: urlRequest, completion: completion) } public func refundTransaction(request: RefundTransactionRequest, queue: DispatchQueue, completion: @escaping (CustomApiResult<TransactionRefundedResponse>) -> Void) { let urlRequest = ApiUserURLRequest.RefundTransaction(request: request, environment: client.environment, userAgent: client.userAgent, apiKey: client.apiKey, authToken: client.authToken) Network.apiRequest(queue: queue, networkURLRequest: urlRequest, completion: completion) } public func deleteUser(request: DeleteUserRequest, queue: DispatchQueue, completion: @escaping (CustomApiResult<DeleteUserResponse>) -> Void) { let urlRequest = ApiUserURLRequest.DeleteUser(request: request, environment: client.environment, userAgent: client.userAgent, apiKey: client.apiKey, authToken: client.authToken) Network.apiRequest(queue: queue, networkURLRequest: urlRequest, completion: completion) } }
mit
4303ed96f5ef7d0f7ef8e6091360a812
49.254902
113
0.51112
7.240113
false
false
false
false
sajeel/AutoScout
AutoScout/View & Controllers/MainViewController.swift
1
4406
// // MainViewController.swift // AutoScout // // Created by Sajjeel Khilji on 5/19/17. // Copyright © 2017 Saj. All rights reserved. // import UIKit import Foundation import MXParallaxHeader class MainViewController: MXSegmentedPagerController { let segmentedNames = ["Cars", "Fav"] private var carsDataSource: CustomTableViewDataSource! private var favsDataSource: CustomTableViewDataSource! private var carsViewModel: CarsViewModel? private var favsViewModel: FavViewModel? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. configurePager() } public func setViewModels(carsViewModel: ViewsModelData, favsViewModel: ViewsModelData) -> Void { self.carsViewModel = carsViewModel as? CarsViewModel self.favsViewModel = favsViewModel as? FavViewModel self.carsDataSource = CustomTableViewDataSource(viewModel: carsViewModel) self.favsDataSource = CustomTableViewDataSource(viewModel: favsViewModel) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() configureViewControllersAndModels() } func configureViewControllersAndModels() { for index in 0...segmentedNames.count { let indexKey = NSNumber.init(value: index) let viewController = self.pageViewControllers.object(forKey: indexKey) if viewController is CarsViewController{ let carsViewController = viewController as! CarsViewController carsViewController.tableView.dataSource = self.carsDataSource carsViewController.viewModel = self.carsViewModel self.carsViewModel?.delegate = carsViewController }else if viewController is FavViewController{ let favsViewController = viewController as! FavViewController favsViewController.tableView.dataSource = self.favsDataSource favsViewController.viewModel = self.favsViewModel self.favsViewModel?.delegate = favsViewController } } } func configurePager() { segmentedPager.backgroundColor = .white // Segmented Control customization segmentedPager.segmentedControl.selectionIndicatorLocation = .down segmentedPager.segmentedControl.backgroundColor = .white segmentedPager.segmentedControl.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.black] segmentedPager.segmentedControl.selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.orange] segmentedPager.segmentedControl.selectionStyle = .fullWidthStripe segmentedPager.segmentedControl.selectionIndicatorColor = .orange segmentedPager.bounces = true } func adjustTableView() { edgesForExtendedLayout = [] extendedLayoutIncludesOpaqueBars = false automaticallyAdjustsScrollViewInsets = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func segmentedPager(_ segmentedPager: MXSegmentedPager, titleForSectionAt index: Int) -> String { return segmentedNames[index] } override func segmentedPager(_ segmentedPager: MXSegmentedPager, didScrollWith parallaxHeader: MXParallaxHeader) { print("progress \(parallaxHeader.progress)") } } /* override func segmentedPager(_ segmentedPager: MXSegmentedPager, viewControllerForPageAt index: Int) -> UIViewController { let pageViewController: UIViewController = super.segmentedPager(segmentedPager, viewControllerForPageAt: index) if pageViewController is CarsViewController { (pageViewController as! CarsViewController).delegate = self.carsDataSource.viewModel as! CarsViewModelInput (pageViewController as! CarsViewController).tableView.dataSource = self.carsDataSource }else if pageViewController is FavViewController{ (pageViewController as! FavViewController).delegate = self.favsDataSource.viewModel as! FavViewModelInput (pageViewController as! FavViewController).tableView.dataSource = self.favsDataSource } return pageViewController; }*/
gpl-3.0
d1fcd08fb6378cd9562099288196e27d
36.016807
123
0.714188
5.728218
false
false
false
false
pdcgomes/RendezVous
RendezVous/StringColorizer.swift
1
12514
// // StringColorizer.swift // RendezVous // // Created by Pedro Gomes on 11/09/2015. // Copyright © 2015 Pedro Gomes. All rights reserved. // import Foundation //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public enum AnsiColorCode : UInt, CustomStringConvertible { case Black = 0 case Red = 1 case Green = 2 case Yellow = 3 case Blue = 4 case Magenta = 5 case Cyan = 6 case White = 7 case Default = 9 //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public init?(rawValue: UInt) { var value: UInt switch rawValue { case 30...39: value = rawValue - 30; break case 40...49: value = rawValue - 40; break case 60...69: value = rawValue - 60; break default: value = rawValue } switch value { case 0: self = .Black; break case 1: self = .Red; break case 2: self = .Green; break case 3: self = .Yellow; break case 4: self = .Blue; break case 5: self = .Magenta; break case 6: self = .Cyan; break case 7: self = .White; break case 9: self = .Default; break default: return nil } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// static func values() -> [AnsiColorCode] { var values = [AnsiColorCode]() for v: UInt in 0...7 { if let enumValue = AnsiColorCode(rawValue: v) { values.append(enumValue) } } return values } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func lightColor() -> UInt { switch self.rawValue { case 0...7: return self.rawValue + 60 default: return self.rawValue } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func foregroundColor() -> UInt { return self.rawValue + 30 } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func backgroundColor() -> UInt { return self.rawValue + 40 } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public var description: String { switch self { case Black: return "Black" case Red: return "Red" case Green: return "Green" case Yellow: return "Yellow" case Blue: return "Blue" case Magenta: return "Magenta" case Cyan: return "Cyan" case White: return "White" case Default: return "" } } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public enum AnsiModeCode : UInt, CustomStringConvertible { case Default = 0 case Bold = 1 case Italic = 3 case Underline = 4 case Inverse = 7 case Hide = 8 case Strike = 9 //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// static func values() -> [AnsiModeCode] { var values = [AnsiModeCode]() for v: UInt in 0...9 { if let enumValue = AnsiModeCode(rawValue: v) { values.append(enumValue) } } return values } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public var description: String { switch self { case Bold: return "Bold" case Italic: return "Italic" case Underline: return "Underline" case Inverse: return "Inverse" case Hide: return "Hide" case Strike: return "Strikethrough" case Default: return "" } } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// struct ANSISequence: CustomStringConvertible { var modeCode: UInt var foregroundCode: UInt var backgroundCode: UInt var string: String //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// init(foreground: AnsiColorCode = .Default, background: AnsiColorCode = .Default, mode: AnsiModeCode = .Default, string: String) { self.foregroundCode = foreground.foregroundColor() self.backgroundCode = background.backgroundColor() self.modeCode = mode.rawValue self.string = string } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// var description: String { let codeSequence = [modeCode, foregroundCode, backgroundCode] .map({ String($0) }) .joinWithSeparator(";") return "\u{001b}[\(codeSequence)m" + string + "\u{001b}[0m" } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public extension String { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public func colorize(text: AnsiColorCode = .Default, background: AnsiColorCode = .Default, mode: AnsiModeCode = .Default) -> String { let (hasSequence, sequence) = extractANSISequence() if hasSequence { let seq = sequence! return ANSISequence( foreground: (text == .Default ? AnsiColorCode(rawValue: seq.foregroundCode)! : text), background: (background == .Default ? AnsiColorCode(rawValue: seq.backgroundCode)! : background), mode: (mode == .Default ? AnsiModeCode(rawValue: seq.modeCode)! : mode), string: seq.string).description } return ANSISequence( foreground: text, background: background, mode: mode, string: self).description } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public static func printColorSamples() -> Void { let colorCodes = AnsiColorCode.values().map { $0 } let maxLen = Int(colorCodes.reduce(0) { return $1.description.characters.count > $0 ? $1.description.characters.count : $0 }) for f in colorCodes { for b in colorCodes { let foreground = f.description.leftJustify(maxLen + 1) let background = b.description.leftJustify(maxLen + 1) print("\(foreground) on \(background)".colorize(f, background: b)) } } } //////////////////////////////////////////////////////////////////////////////// // If we already have existing ANSI sequences, return them //////////////////////////////////////////////////////////////////////////////// private func extractANSISequence() -> (Bool, ANSISequence?) { let result = self =~ "\\u001B\\[([^m]*)m(.+?)\\u001B\\[0m" guard result else { return (false, nil) } let codes = result[1].componentsSeparatedByString(";").map({ UInt($0)! }) let mode = AnsiModeCode(rawValue: UInt(codes[0]))! let foreground = AnsiColorCode(rawValue: UInt(codes[1]))! let background = AnsiColorCode(rawValue: UInt(codes[2]))! return (true, ANSISequence( foreground: foreground, background: background, mode: mode, string: result[2])) } } //////////////////////////////////////////////////////////////////////////////// // Convenience methods and properties //////////////////////////////////////////////////////////////////////////////// public extension String { //////////////////////////////////////////////////////////////////////////////// // Convenince text colorizer properties //////////////////////////////////////////////////////////////////////////////// var black: String { return self.colorize(.Black) } var red: String { return self.colorize(.Red) } var green: String { return self.colorize(.Green) } var yellow: String { return self.colorize(.Yellow) } var blue: String { return self.colorize(.Blue) } var magenta: String { return self.colorize(.Magenta)} var cyan: String { return self.colorize(.Cyan) } var white: String { return self.colorize(.White) } //////////////////////////////////////////////////////////////////////////////// // Convenience background colorizer properties //////////////////////////////////////////////////////////////////////////////// var on_black: String { return self.colorize(background: .Black) } var on_red: String { return self.colorize(background: .Red) } var on_green: String { return self.colorize(background: .Green) } var on_yellow: String { return self.colorize(background: .Yellow) } var on_blue: String { return self.colorize(background: .Blue) } var on_magenta: String { return self.colorize(background: .Magenta)} var on_cyan: String { return self.colorize(background: .Cyan) } var on_white: String { return self.colorize(background: .White) } //////////////////////////////////////////////////////////////////////////////// // Convenience mode setting properties //////////////////////////////////////////////////////////////////////////////// var bold: String { return self.colorize(mode: .Bold) } var underline: String { return self.colorize(mode: .Underline)} var italic: String { return self.colorize(mode: .Italic) } var inverse: String { return self.colorize(mode: .Inverse) } var strike: String { return self.colorize(mode: .Strike) } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public extension String { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func leftJustify(padding: Int) -> String { if self.characters.count >= padding { return self } var justifiedStr = self for _ in 0..<(padding - self.characters.count) { justifiedStr.appendContentsOf(" ") } return justifiedStr } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func rightJustify(padding: Int) -> String { if self.characters.count >= padding { return self } var justifiedStr = "" for _ in 0..<(padding - self.characters.count) { justifiedStr.appendContentsOf(" ") } justifiedStr.appendContentsOf(self) return justifiedStr } }
mit
c30ee3f4f12e7b49f0891b17474cc1b2
39.234727
137
0.377527
6.151917
false
false
false
false
Azurelus/Swift-Useful-Files
Sources/Extensions/UIFont+Extension.swift
1
1224
// // UIFont+Extension.swift // Swift-Useful-Files // // Created by Maksym Husar on 9/7/17. // Copyright © 2017 Husar Maksym. All rights reserved. // import UIKit extension UIFont { enum FontFamily: String { case sanFrancisco = ".SFUIText" //case someOther = "OTHER" } enum FontWeight { case light case regular case medium case bold case semibold func string(for family: FontFamily) -> String? { switch self { case .light: return "Light" case .regular: return nil case .medium: return "Medium" case .bold: return "Bold" case .semibold: return "Semibold" } } } class func font(ofSize size: CGFloat, weight: FontWeight = .regular, family: FontFamily = .sanFrancisco) -> UIFont { var fontName = family.rawValue if let weightString = weight.string(for: family) { fontName += "-\(weightString)" } guard let selectedFont = UIFont(name: fontName, size: size) else { preconditionFailure("Error! Custom font doesn't found") } return selectedFont } }
mit
e1cce7f3d239036885111aea9cb67800
25.586957
120
0.563369
4.479853
false
false
false
false
phimage/Phiole
PhioleColor.swift
1
11524
// // PhioleColor.swift // Phiole /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) 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 // Check if property XcodeColors set for plugin https://github.com/robbiehanson/XcodeColors let XCODE_COLORS: Bool = { let dict = NSProcessInfo.processInfo().environment if let env = dict["XcodeColors"] where env == "YES" { return true } return false }() public extension Phiole { private struct key { static let colorize = UnsafePointer<Void>(bitPattern: Selector("colorize").hashValue) static let outputColor = UnsafePointer<Void>(bitPattern: Selector("outputColor").hashValue) static let errorColor = UnsafePointer<Void>(bitPattern: Selector("errorColor").hashValue) } // Bool to deactivate default colorization public var colorize: Bool { get { if let o = objc_getAssociatedObject(self, key.colorize) as? Bool { return o } else { let obj = true objc_setAssociatedObject(self, key.colorize, obj, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return obj } } set { objc_setAssociatedObject(self, key.colorize, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var outputColor: Color { get { if let o = objc_getAssociatedObject(self, key.outputColor) as? Int { return Color(rawValue: o)! } else { let obj = Color.None objc_setAssociatedObject(self, key.outputColor, obj.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return obj } } set { objc_setAssociatedObject(self, key.outputColor, newValue.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) colorize = true } } public var errorColor: Color { get { if let o = objc_getAssociatedObject(self, key.errorColor) as? Int { return Color(rawValue: o)! } else { let obj = Color.None objc_setAssociatedObject(self, key.errorColor, obj.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return obj } } set { objc_setAssociatedObject(self, key.errorColor, newValue.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) colorize = true } } // MARK: coloration and font enhancement private struct PhioleColor { var red, green, blue: UInt8 } public enum Color: Int, StringDecorator { case Black, Red, Green, Yellow, Blue, Cyan, Purple, Gray, DarkGray,BrightRed,BrightGreen,BrightYellow,BrightBlue,BrightMagenta,BrightCyan,White, None public static let allValues = [Black,Red,Green,Yellow,Blue,Cyan,Purple,Gray, DarkGray,BrightRed,BrightGreen,BrightYellow,BrightBlue,BrightMagenta,BrightCyan,White,None] public static let ESCAPE_SEQUENCE = "\u{001b}[" public static let TERMINAL_COLORS_RESET = "\u{0030}\u{006d}" public static let XCODE_COLORS_FG = "fg" public static let XCODE_COLORS_RESET_FG = "fg;" public static let XCODE_COLORS_BG = "bg" public static let XCODE_COLORS_RESET_BG = "bg;" public static let XCODE_COLORS_RESET = ";" public static let COLORS_RESET = XCODE_COLORS ? XCODE_COLORS_RESET : TERMINAL_COLORS_RESET public var foregroundCode: String? { if XCODE_COLORS { if let c = self.xcodeColor { return "\(Color.XCODE_COLORS_FG)\(c.red),\(c.green),\(c.blue);" } return nil } switch self { case Black : return "30m" case Red : return "31m" case Green : return "32m" case Yellow : return "33m" case Blue : return "34m" case Purple : return "35m" case Cyan : return "36m" case Gray : return "37m" // bold case DarkGray : return "1;30m" case BrightRed : return "1;31m" case BrightGreen : return "1;32m" case BrightYellow : return "1;33m" case BrightBlue : return "1;34m" case BrightMagenta : return "1;35m" case BrightCyan : return "1;36m" case White : return "1;37m" case None : return nil } } public var backgroundCode: String? { if XCODE_COLORS { if let c = self.xcodeColor { return "\(Color.XCODE_COLORS_BG)\(c.red),\(c.green),\(c.blue);" } return nil } switch self { case Black : return "40m" case Red : return "41m" case Green : return "42m" case Yellow : return "43m" case Blue : return "44m" case Purple : return "45m" case Cyan : return "46m" case Gray : return "47m" case DarkGray : return "1;40m" case BrightRed : return "1;41m" case BrightGreen : return "1;42m" case BrightYellow : return "1;43m" case BrightBlue : return "1;44m" case BrightMagenta : return "1;45m" case BrightCyan : return "1;46m" case White : return "1;47m" case None : return nil } } /*private var terminalColor: PhioleColor? { switch self { case Black : return PhioleColor(red: 0, green: 0, blue: 0) case Red : return PhioleColor(red:194, green: 54, blue: 33) case Green : return PhioleColor(red: 37, green: 188, blue: 36) case Yellow : return PhioleColor(red:173, green: 173, blue: 39) case Blue : return PhioleColor(red: 73, green: 46, blue: 225) case Purple : return PhioleColor(red:211, green: 56, blue: 211) case Cyan : return PhioleColor(red: 51, green: 187, blue: 200) case Gray : return PhioleColor(red:203, green: 204, blue: 205) case DarkGray : return PhioleColor(red:129, green: 131, blue: 131) case BrightRed : return PhioleColor(red:252, green: 57, blue: 31) case BrightGreen : return PhioleColor(red: 49, green: 231, blue: 34) case BrightYellow : return PhioleColor(red:234, green: 236, blue: 35) case BrightBlue : return PhioleColor(red: 88, green: 51, blue: 255) case BrightMagenta : return PhioleColor(red:249, green: 53, blue: 248) case BrightCyan : return PhioleColor(red: 20, green: 240, blue: 240) case White : return PhioleColor(red:233, green: 235, blue: 235) case None : return nil } }*/ private var xcodeColor: PhioleColor? { switch self { case Black : return PhioleColor(red: 0, green: 0, blue: 0) case Red : return PhioleColor(red:205, green: 0, blue: 0) case Green : return PhioleColor(red: 0, green: 205, blue: 0) case Yellow : return PhioleColor(red:205, green: 205, blue: 0) case Blue : return PhioleColor(red: 0, green: 0, blue: 238) case Purple : return PhioleColor(red:205, green: 0, blue: 205) case Cyan : return PhioleColor(red: 0, green: 205, blue: 205) case Gray : return PhioleColor(red:229, green: 229, blue: 229) case DarkGray : return PhioleColor(red:127, green: 127, blue: 127) case BrightRed : return PhioleColor(red:255, green: 0, blue: 0) case BrightGreen : return PhioleColor(red: 0, green: 255, blue: 0) case BrightYellow : return PhioleColor(red:255, green: 255, blue: 0) case BrightBlue : return PhioleColor(red: 92, green: 92, blue: 255) case BrightMagenta : return PhioleColor(red:255, green: 0, blue: 255) case BrightCyan : return PhioleColor(red: 0, green: 255, blue: 255) case White : return PhioleColor(red:255, green: 255, blue: 255) case None : return nil } } // MARK: functions public func fg(string: String) -> String { if let code = self.foregroundCode { return Color.ESCAPE_SEQUENCE + code + string + Color.ESCAPE_SEQUENCE + Color.COLORS_RESET } return string } public func bg(string: String) -> String { if let code = self.backgroundCode { return Color.ESCAPE_SEQUENCE + code + string + Color.ESCAPE_SEQUENCE + Color.COLORS_RESET } return string } public func decorate(string: String) -> String { return fg(string) } public static func decorate(string: String, fg: Color, bg: Color) -> String { if let fcode = fg.foregroundCode, bcode = bg.backgroundCode { return Color.ESCAPE_SEQUENCE + fcode + ESCAPE_SEQUENCE + bcode + string + Color.ESCAPE_SEQUENCE + Color.COLORS_RESET } if fg.foregroundCode != nil { return fg.fg(string) } if bg.backgroundCode != nil { return bg.bg(string) } return string } } /*public enum FontStyle { case Bold case Italic case Underline case Reverse public var on: String { switch self { case Bold : return "1m" case Italic : return "3m" case Underline : return "4m" case Reverse : return "7m" } } public var off: String { switch self { case Bold : return "22m" case Italic : return "23m" case Underline : return "24m" case Reverse : return "27m" } } public func decorate(string: String) -> String { return self.on + string + self.off } }*/ }
mit
c616556955b4cf25a8f511042a6e4e8d
38.737931
136
0.572371
4.137882
false
false
false
false
the-grid/Portal
Portal/Models/SiteConfig.swift
1
1635
import Argo import Curry import Foundation import Ogra /// A site configuration. public struct SiteConfig { public var color: ColorConfig? public var favicon: NSURL? public var layout: Float? public var logo: NSURL? public var typography: Float? public init( color: ColorConfig? = .None, favicon: NSURL? = .None, layout: Float? = .None, logo: NSURL? = .None, typography: Float? = .None ) { self.color = color self.favicon = favicon self.layout = layout self.logo = logo self.typography = typography } } // MARK: - Decodable extension SiteConfig: Decodable { public static func decode(json: JSON) -> Decoded<SiteConfig> { return curry(self.init) <^> json <|? "color" <*> json <|? "favicon" <*> json <|? "layout_spectrum" <*> json <|? "logo" <*> json <|? "typography_spectrum" } } // MARK: - Encodable extension SiteConfig: Encodable { public func encode() -> JSON { return .Object([ "color": color.encode(), "favicon": favicon.encode(), "layout_spectrum": layout.encode(), "logo": logo.encode(), "typography_spectrum": typography.encode() ]) } } // MARK: - Equatable extension SiteConfig: Equatable {} public func == (lhs: SiteConfig, rhs: SiteConfig) -> Bool { return lhs.color == rhs.color && lhs.favicon == rhs.favicon && lhs.layout == rhs.layout && lhs.logo == rhs.logo && lhs.typography == rhs.typography }
mit
cd2ef14973319f81ce518b7832d3ad8e
22.695652
66
0.557187
4.181586
false
true
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/TabPeekViewController.swift
7
9575
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import WebKit protocol TabPeekDelegate: AnyObject { func tabPeekDidAddBookmark(_ tab: Tab) @discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem? func tabPeekRequestsPresentationOf(_ viewController: UIViewController) func tabPeekDidCloseTab(_ tab: Tab) } class TabPeekViewController: UIViewController, WKNavigationDelegate { fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks") fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard") fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab") weak var tab: Tab? fileprivate weak var delegate: TabPeekDelegate? fileprivate var fxaDevicePicker: UINavigationController? fileprivate var isBookmarked: Bool = false fileprivate var isInReadingList: Bool = false fileprivate var hasRemoteClients: Bool = false fileprivate var ignoreURL: Bool = false fileprivate var screenShot: UIImageView? fileprivate var previewAccessibilityLabel: String! fileprivate var webView: WKWebView? // Preview action items. override var previewActionItems: [UIPreviewActionItem] { get { return previewActions } } lazy var previewActions: [UIPreviewActionItem] = { var actions = [UIPreviewActionItem]() let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false if !self.ignoreURL && !urlIsTooLongToSave { if !self.isBookmarked { actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { [weak self] previewAction, viewController in guard let wself = self, let tab = wself.tab else { return } wself.delegate?.tabPeekDidAddBookmark(tab) }) } if self.hasRemoteClients { actions.append(UIPreviewAction(title: Strings.SendToDeviceTitle, style: .default) { [weak self] previewAction, viewController in guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return } wself.delegate?.tabPeekRequestsPresentationOf(clientPicker) }) } // only add the copy URL action if we don't already have 3 items in our list // as we are only allowed 4 in total and we always want to display close tab if actions.count < 3 { actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) {[weak self] previewAction, viewController in guard let wself = self, let url = wself.tab?.canonicalURL else { return } UIPasteboard.general.url = url SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view) }) } } actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { [weak self] previewAction, viewController in guard let wself = self, let tab = wself.tab else { return } wself.delegate?.tabPeekDidCloseTab(tab) }) return actions }() @available(iOS 13, *) func contextActions(defaultActions: [UIMenuElement]) -> UIMenu { var actions = [UIAction]() let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false if !self.ignoreURL && !urlIsTooLongToSave { if !self.isBookmarked { actions.append(UIAction(title: TabPeekViewController.PreviewActionAddToBookmarks, image: UIImage.templateImageNamed("menu-Bookmark"), identifier: nil) { [weak self] _ in guard let wself = self, let tab = wself.tab else { return } wself.delegate?.tabPeekDidAddBookmark(tab) }) } if self.hasRemoteClients { actions.append(UIAction(title: Strings.SendToDeviceTitle, image: UIImage.templateImageNamed("menu-Send"), identifier: nil) { [weak self] _ in guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return } wself.delegate?.tabPeekRequestsPresentationOf(clientPicker) }) } actions.append(UIAction(title: TabPeekViewController.PreviewActionCopyURL, image: UIImage.templateImageNamed("menu-Copy-Link"), identifier: nil) {[weak self] _ in guard let wself = self, let url = wself.tab?.canonicalURL else { return } UIPasteboard.general.url = url SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view) }) } actions.append(UIAction(title: TabPeekViewController.PreviewActionCloseTab, image: UIImage.templateImageNamed("menu-CloseTabs"), identifier: nil) { [weak self] _ in guard let wself = self, let tab = wself.tab else { return } wself.delegate?.tabPeekDidCloseTab(tab) }) return UIMenu(title: "", children: actions) } init(tab: Tab, delegate: TabPeekDelegate?) { self.tab = tab self.delegate = delegate super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) webView?.navigationDelegate = nil self.webView = nil } override func viewDidLoad() { super.viewDidLoad() if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel { previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel) } // if there is no screenshot, load the URL in a web page // otherwise just show the screenshot setupWebView(tab?.webView) guard let screenshot = tab?.screenshot else { return } setupWithScreenshot(screenshot) } fileprivate func setupWithScreenshot(_ screenshot: UIImage) { let imageView = UIImageView(image: screenshot) self.view.addSubview(imageView) imageView.snp.makeConstraints { make in make.edges.equalTo(self.view) } screenShot = imageView screenShot?.accessibilityLabel = previewAccessibilityLabel } fileprivate func setupWebView(_ webView: WKWebView?) { guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return } let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration) clonedWebView.allowsLinkPreview = false clonedWebView.accessibilityLabel = previewAccessibilityLabel self.view.addSubview(clonedWebView) clonedWebView.snp.makeConstraints { make in make.edges.equalTo(self.view) } clonedWebView.navigationDelegate = self self.webView = clonedWebView clonedWebView.load(URLRequest(url: url)) } func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: DevicePickerViewControllerDelegate) { assert(Thread.current.isMainThread) guard let tab = self.tab else { return } guard let displayURL = tab.url?.absoluteString, !displayURL.isEmpty else { return } browserProfile.places.isBookmarked(url: displayURL) >>== { isBookmarked in self.isBookmarked = isBookmarked } browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(.main) { guard let clientGUIDs = $0.successValue else { return } self.hasRemoteClients = !clientGUIDs.isEmpty let clientPickerController = DevicePickerViewController() clientPickerController.pickerDelegate = clientPickerDelegate clientPickerController.profile = browserProfile clientPickerController.profileNeedsShutdown = false if let url = tab.url?.absoluteString { clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil) } self.fxaDevicePicker = UINavigationController(rootViewController: clientPickerController) } let result = browserProfile.readingList.getRecordWithURL(displayURL).value.successValue self.isInReadingList = !(result?.url.isEmpty ?? true) self.ignoreURL = isIgnoredURL(displayURL) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { screenShot?.removeFromSuperview() screenShot = nil } }
mpl-2.0
006f9354ea20d93d162a4515b2f92045
45.033654
294
0.666736
5.364146
false
false
false
false
ldt25290/MyInstaMap
ThirdParty/Alamofire/Source/Request.swift
1
24233
// // Request.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } /// The number of times the request has been retried. open internal(set) var retryCount: UInt = 0 let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case .data(let originalTask, let task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case .download(let originalTask, let task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case .upload(let originalTask, let task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case .stream(let originalTask, let task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false ; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -v"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { guard let user = credential.user, let password = credential.password else { continue } components.append("-u \(user):\(password)") } } else { if let credential = delegate.credential, let user = credential.user, let password = credential.password { components.append("-u \(user):\(password)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } #if swift(>=3.2) components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"") #else components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") #endif } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.sync { session.dataTask(with: urlRequest) } } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let requestable = originalTask as? Requestable { return requestable.urlRequest } return nil } /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.sync { session.downloadTask(withResumeData: resumeData) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { return urlRequest } return nil } /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task as Any] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } guard let uploadable = originalTask as? Uploadable else { return nil } switch uploadable { case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): return urlRequest } } /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open class StreamRequest: Request { enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.sync { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.sync { session.streamTask(with: netService) } } return task } } } #endif
mit
3fa68451a217b50efb51887a14125ca7
36.167178
131
0.641728
5.137375
false
false
false
false
sunfei/realm-cocoa
Realm/Tests/Swift2.0/SwiftLinkTests.swift
3
7906
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import Realm class SwiftLinkTests: RLMTestCase { // Swift models func testBasicLink() { let realm = realmWithTestPath() let owner = SwiftOwnerObject() owner.name = "Tim" owner.dog = SwiftDogObject() owner.dog!.dogName = "Harvie" realm.beginWriteTransaction() realm.addObject(owner) realm.commitWriteTransaction() let owners = SwiftOwnerObject.allObjectsInRealm(realm) let dogs = SwiftDogObject.allObjectsInRealm(realm) XCTAssertEqual(owners.count, UInt(1), "Expecting 1 owner") XCTAssertEqual(dogs.count, UInt(1), "Expecting 1 dog") XCTAssertEqual((owners[0] as! SwiftOwnerObject).name, "Tim", "Tim is named Tim") XCTAssertEqual((dogs[0] as! SwiftDogObject).dogName, "Harvie", "Harvie is named Harvie") let tim = owners[0] as! SwiftOwnerObject XCTAssertEqual(tim.dog!.dogName, "Harvie", "Tim's dog should be Harvie") } func testMultipleOwnerLink() { let realm = realmWithTestPath() let owner = SwiftOwnerObject() owner.name = "Tim" owner.dog = SwiftDogObject() owner.dog!.dogName = "Harvie" realm.beginWriteTransaction() realm.addObject(owner) realm.commitWriteTransaction() XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner") XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog") realm.beginWriteTransaction() let fiel = SwiftOwnerObject.createInRealm(realm, withValue: ["Fiel", NSNull()]) fiel.dog = owner.dog realm.commitWriteTransaction() XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, UInt(2), "Expecting 2 owners") XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog") } func testLinkRemoval() { let realm = realmWithTestPath() let owner = SwiftOwnerObject() owner.name = "Tim" owner.dog = SwiftDogObject() owner.dog!.dogName = "Harvie" realm.beginWriteTransaction() realm.addObject(owner) realm.commitWriteTransaction() XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner") XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog") realm.beginWriteTransaction() realm.deleteObject(owner.dog!) realm.commitWriteTransaction() XCTAssertNil(owner.dog, "Dog should be nullified when deleted") // refresh owner and check let owner2 = SwiftOwnerObject.allObjectsInRealm(realm).firstObject() as! SwiftOwnerObject XCTAssertNotNil(owner2, "Should have 1 owner") XCTAssertNil(owner2.dog, "Dog should be nullified when deleted") XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(0), "Expecting 0 dogs") } // FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects // func testCircularLinks() { // let realm = realmWithTestPath() // // let obj = SwiftCircleObject() // obj.data = "a" // obj.next = obj // // realm.beginWriteTransaction() // realm.addObject(obj) // obj.next.data = "b" // realm.commitWriteTransaction() // // let obj2 = SwiftCircleObject.allObjectsInRealm(realm).firstObject() as SwiftCircleObject // XCTAssertEqual(obj2.data, "b", "data should be 'b'") // XCTAssertEqual(obj2.data, obj2.next.data, "objects should be equal") // } // Objective-C models func testBasicLink_objc() { let realm = realmWithTestPath() let owner = OwnerObject() owner.name = "Tim" owner.dog = DogObject() owner.dog.dogName = "Harvie" realm.beginWriteTransaction() realm.addObject(owner) realm.commitWriteTransaction() let owners = OwnerObject.allObjectsInRealm(realm) let dogs = DogObject.allObjectsInRealm(realm) XCTAssertEqual(owners.count, UInt(1), "Expecting 1 owner") XCTAssertEqual(dogs.count, UInt(1), "Expecting 1 dog") XCTAssertEqual((owners[0] as! OwnerObject).name!, "Tim", "Tim is named Tim") XCTAssertEqual((dogs[0] as! DogObject).dogName!, "Harvie", "Harvie is named Harvie") let tim = owners[0] as! OwnerObject XCTAssertEqual(tim.dog.dogName!, "Harvie", "Tim's dog should be Harvie") } func testMultipleOwnerLink_objc() { let realm = realmWithTestPath() let owner = OwnerObject() owner.name = "Tim" owner.dog = DogObject() owner.dog.dogName = "Harvie" realm.beginWriteTransaction() realm.addObject(owner) realm.commitWriteTransaction() XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner") XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog") realm.beginWriteTransaction() let fiel = OwnerObject.createInRealm(realm, withValue: ["Fiel", NSNull()]) fiel.dog = owner.dog realm.commitWriteTransaction() XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, UInt(2), "Expecting 2 owners") XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog") } func testLinkRemoval_objc() { let realm = realmWithTestPath() let owner = OwnerObject() owner.name = "Tim" owner.dog = DogObject() owner.dog.dogName = "Harvie" realm.beginWriteTransaction() realm.addObject(owner) realm.commitWriteTransaction() XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner") XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog") realm.beginWriteTransaction() realm.deleteObject(owner.dog) realm.commitWriteTransaction() XCTAssertNil(owner.dog, "Dog should be nullified when deleted") // refresh owner and check let owner2 = OwnerObject.allObjectsInRealm(realm).firstObject() as! OwnerObject XCTAssertNotNil(owner2, "Should have 1 owner") XCTAssertNil(owner2.dog, "Dog should be nullified when deleted") XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(0), "Expecting 0 dogs") } // FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects // func testCircularLinks_objc() { // let realm = realmWithTestPath() // // let obj = CircleObject() // obj.data = "a" // obj.next = obj // // realm.beginWriteTransaction() // realm.addObject(obj) // obj.next.data = "b" // realm.commitWriteTransaction() // // let obj2 = CircleObject.allObjectsInRealm(realm).firstObject() as CircleObject // XCTAssertEqual(obj2.data, "b", "data should be 'b'") // XCTAssertEqual(obj2.data, obj2.next.data, "objects should be equal") // } }
apache-2.0
9ba5248d41cb7a43fcabac4a85c12720
36.117371
103
0.649001
4.791515
false
true
false
false
silence0201/Swift-Study
Swifter/05Tuple.playground/Contents.swift
1
440
//: Playground - noun: a place where people can play import UIKit func swapMe1<T>(a: inout T ,b: inout T) { let temp = a a = b b = temp } func swapMe2<T>(a: inout T, b: inout T) { (a,b) = (b,a) } var a = 1 var b = 2 (a,b) swapMe1(a: &a, b: &b) (a,b) swapMe2(a: &a, b: &b) (a,b) let rect = CGRect(x: 0, y: 0, width: 100, height: 100) let (small, large) = rect.divided(atDistance: 20, from: .minXEdge) small large
mit
806056b831c8cd9b6d1f5f3cb576ce2c
12.333333
66
0.568182
2.233503
false
false
false
false
frograin/FluidValidator
Pod/Classes/Core/FailMessage.swift
1
1173
// // FailMessage.swift // TestValidator // // Created by FrogRain on 31/01/16. // Copyright © 2016 FrogRain. All rights reserved. // import Foundation open class FailMessage : NSObject { open var summary:ErrorMessage open var localizedSubject:String? open var errors:Array<ErrorMessage> fileprivate var opaqueDict:Dictionary<String, FailMessage> override init() { self.summary = ErrorMessage() self.errors = Array<ErrorMessage>() self.opaqueDict = Dictionary<String, FailMessage>() super.init() } open func failingFields () -> [String] { return self.opaqueDict.keys.map { (key) -> String in key } } func setObject(_ object:FailMessage, forKey:String) { self.opaqueDict[forKey] = object; } override open func value(forKeyPath keyPath: String) -> Any? { let dict = self.opaqueDict as NSDictionary return dict.value(forKeyPath: keyPath) as? FailMessage } open func failMessageForPath(_ keyPath: String) -> FailMessage? { return self.value(forKeyPath: keyPath) as? FailMessage } }
mit
7dc065c3992057898bb97be32e82c3b9
25.044444
69
0.633106
4.29304
false
false
false
false
jbgann/gratuify
gratuify/ColorSettingsViewController.swift
1
6512
// // ColorSettingsViewController.swift // Gratuify // // Created by John Gann on 12/16/15. // Copyright © 2015 John Gann. All rights reserved. // import UIKit extension UIColor { var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha:CGFloat){ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r,g,b,a) } } class ColorSettingsViewController: UIViewController, UIPickerViewDelegate,UIPickerViewDataSource { @IBOutlet weak var compositeBlock: UIView! @IBOutlet weak var redBlock: UIView! @IBOutlet weak var greenBlock: UIView! @IBOutlet weak var blueBlock: UIView! @IBOutlet weak var colorTypePicker: UIPickerView! var redRot = 0.5 as CGFloat var blueRot = 0.5 as CGFloat var greenRot = 0.5 as CGFloat func packColor(aColor : UIColor, colorName : String){ let defaults = NSUserDefaults.standardUserDefaults() let redString = colorName + "RED" let greenString = colorName + "GREEN" let blueString = colorName + "BLUE" defaults.setObject(true, forKey: colorName) defaults.setObject(aColor.components.red,forKey : redString) defaults.setObject(aColor.components.green,forKey : greenString) defaults.setObject(aColor.components.blue,forKey : blueString) } func unPackColor(colorName: String) -> UIColor { var r : CGFloat var g: CGFloat var b: CGFloat let defaults = NSUserDefaults.standardUserDefaults() let redString = colorName + "RED" let greenString = colorName + "GREEN" let blueString = colorName + "BLUE" r = defaults.objectForKey(redString) as! CGFloat g = defaults.objectForKey(greenString)as! CGFloat b = defaults.objectForKey(blueString)as! CGFloat return UIColor(red: r, green: g, blue: b, alpha: 1.0) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { if pickerView == colorTypePicker{ return 1 } return 0 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ if pickerView == colorTypePicker { return 2 } return 0 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{ if row==1{ return "Text" } return "Background" } func pickerView(_pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){ setCompositeFromPicker() } override func viewDidLoad() { super.viewDidLoad() colorTypePicker.dataSource=self colorTypePicker!.delegate = self // Do any additional setup after loading the view. } override func viewWillAppear(animated : Bool){ super.viewWillAppear(animated) setCompositeFromPicker() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func setCompositeFromPicker(){ let choice = colorTypePicker.selectedRowInComponent(0) if choice == 1 { compositeBlock.backgroundColor=unPackColor("textColor") } if choice == 0{ compositeBlock.backgroundColor=unPackColor("backgroundColor") } } func packFromPicker(){ let choice = colorTypePicker.selectedRowInComponent(0) if choice == 1 { packColor(compositeBlock.backgroundColor!, colorName : "textColor") } if choice == 0{ packColor(compositeBlock.backgroundColor!, colorName : "backgroundColor") } } func updateCompositeBlock(){ var workingColor = redBlock.backgroundColor let r = workingColor!.components.red as CGFloat workingColor = blueBlock.backgroundColor let b = workingColor!.components.blue workingColor = greenBlock.backgroundColor let g = workingColor!.components.green compositeBlock.backgroundColor=UIColor(red: r, green: g, blue: b , alpha: 1.0) packFromPicker() } func setComponentsFromComposite(){ redBlock.backgroundColor=UIColor(red:compositeBlock.backgroundColor!.components.red, green: 0.0, blue: 0.0, alpha: 1.0) greenBlock.backgroundColor=UIColor(red : 0.0, green:compositeBlock.backgroundColor!.components.green, blue: 0.0, alpha: 1.0) blueBlock.backgroundColor=UIColor(red: 0.0, green : 0.0, blue : compositeBlock.backgroundColor!.components.blue, alpha: 1.0) } @IBAction func rotateRed(sender: UIRotationGestureRecognizer) { redBlock.backgroundColor=UIColor(red: (redRot+((sender.rotation / 4.0 ) % 1.0 ) ) % 1.0, green: 0.0, blue: 0.0, alpha: 1.0) updateCompositeBlock() if sender.state == .Ended{ let savedColor = redBlock.backgroundColor redRot = savedColor!.components.red as CGFloat print("rotation ended") } } @IBAction func rotateGreen(sender: UIRotationGestureRecognizer) { greenBlock.backgroundColor=UIColor(red: 0.0, green: (redRot+((sender.rotation / 4.0 ) % 1.0 ) ) % 1.0, blue: 0.0, alpha: 1.0) updateCompositeBlock() if sender.state == .Ended{ let savedColor = greenBlock.backgroundColor greenRot = savedColor!.components.green as CGFloat print("rotation ended") } } @IBAction func rotateBlue(sender: UIRotationGestureRecognizer) { blueBlock.backgroundColor=UIColor(red: 0.0 , green: 0.0 , blue: (blueRot+((sender.rotation / 4.0 ) % 1.0 ) ) % 1.0,alpha: 1.0) updateCompositeBlock() if sender.state == .Ended{ let savedColor = blueBlock.backgroundColor blueRot = savedColor!.components.blue as CGFloat print("rotation ended") } } }
apache-2.0
04318078dd5d05db4967854437a0a45e
33.632979
134
0.634311
4.559524
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/Observables/Materialize.swift
4
1539
// // Materialize.swift // RxSwift // // Created by sergdort on 08/03/2017. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Convert any Observable into an Observable of its events. - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) - returns: An observable sequence that wraps events in an Event<E>. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. */ public func materialize() -> Observable<Event<E>> { return Materialize(source: self.asObservable()) } } fileprivate final class MaterializeSink<Element, O: ObserverType>: Sink<O>, ObserverType where O.E == Event<Element> { func on(_ event: Event<Element>) { self.forwardOn(.next(event)) if event.isStopEvent { self.forwardOn(.completed) self.dispose() } } } final private class Materialize<Element>: Producer<Event<Element>> { private let _source: Observable<Element> init(source: Observable<Element>) { self._source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = MaterializeSink(observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
4ba9115355c765a559dec1ab102d9324
33.954545
195
0.676203
4.432277
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Model/Notification.swift
1
5376
// // Notification.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @objc open class Notification: NSObject, Identifiable { open let identifier: String open let type: NotificationType open let createdAt: Date open let text: String open let shortText: String open let isNew: Bool open let isUnread: Bool open let creation: Creation? open let user: User? open let gallery: Gallery? open let comment: Comment? open let gallerySubmission: GallerySubmission? open let userEntities: Array<NotificationTextEntity>? open let creationEntities: Array<NotificationTextEntity>? open let galleryEntities: Array<NotificationTextEntity>? open let creationRelationship: Relationship? open let userRelationship: Relationship? open let galleryRelationship: Relationship? open let commentRelationship: Relationship? open let gallerySubmissionRelationship: Relationship? open let userEntitiesRelationships: Array<Relationship>? open let creationEntitiesRelationships: Array<Relationship>? open let galleryEntitiesRelationships: Array<Relationship>? open let bubbleRelationship: Relationship? open let bubble: Bubble? init(mapper: NotificationMapper, dataMapper: DataIncludeMapper? = nil) { identifier = mapper.identifier! text = mapper.text! shortText = mapper.shortText! isNew = mapper.isNew! isUnread = mapper.isUnread! createdAt = mapper.createdAt! as Date type = mapper.parseType() creationRelationship = MappingUtils.relationshipFromMapper(mapper.creationRelationship) userRelationship = MappingUtils.relationshipFromMapper(mapper.userRelationship) galleryRelationship = MappingUtils.relationshipFromMapper(mapper.galleryRelationship) commentRelationship = MappingUtils.relationshipFromMapper(mapper.commentRelationship) gallerySubmissionRelationship = MappingUtils.relationshipFromMapper(mapper.gallerySubmissionRelationship) userEntitiesRelationships = mapper.userEntitiesRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) }) creationEntitiesRelationships = mapper.creationEntitiesRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) }) galleryEntitiesRelationships = mapper.galleryEntitiesRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) }) creation = MappingUtils.objectFromMapper(dataMapper, relationship: creationRelationship, type: Creation.self) user = MappingUtils.objectFromMapper(dataMapper, relationship: userRelationship, type: User.self) gallery = MappingUtils.objectFromMapper(dataMapper, relationship: galleryRelationship, type: Gallery.self) comment = MappingUtils.objectFromMapper(dataMapper, relationship: commentRelationship, type: Comment.self) gallerySubmission = MappingUtils.objectFromMapper(dataMapper, relationship: gallerySubmissionRelationship, type: GallerySubmission.self) userEntities = userEntitiesRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: NotificationTextEntity.self) }).filter({ $0.type != .unknown }) creationEntities = creationEntitiesRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: NotificationTextEntity.self) }).filter({ $0.type != .unknown }) galleryEntities = galleryEntitiesRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: NotificationTextEntity.self) }).filter({ $0.type != .unknown }) //Not sure if we still need this? bubbleRelationship = MappingUtils.relationshipFromMapper(mapper.bubbleRelationship) bubble = MappingUtils.objectFromMapper(dataMapper, relationship: bubbleRelationship, type: Bubble.self) } var isValid: Bool { //Valid creation should have at least one of [creation, user, gallery, creationEntities, userEntities, galleryEntities] set and not-empty return creation != nil || user != nil || gallery != nil || creationEntities?.isEmpty == false || galleryEntities?.isEmpty == false || userEntities?.isEmpty == false } }
mit
b338772a96ab650db303358006c853a9
52.227723
197
0.751302
5.043152
false
false
false
false
lotz84/TwitterMediaTimeline
twitter-media-timeline/TwitterMediaTimeline.swift
1
4222
import UIKit import Social import Accounts typealias TMTRequest = (maxId: String?, account: ACAccount) typealias TMTResultHandler = (idArray: [String]) -> () protocol TwitterMediaTimelineDataSource : class { func getNextStatusIds(request: TMTRequest, callback: TMTResultHandler) -> () } class TwitterMediaTimeline : UIViewController { weak var dataSource: TwitterMediaTimelineDataSource? var account : ACAccount? var nextMaxId : String? var statusIdArray : [String] = [] var statusMap : [String:TweetStatus] = [:] var collectionView : UICollectionView? let ReuseIdentifier = "cell" override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.itemSize = self.view.bounds.size layout.minimumLineSpacing = 0.0; layout.minimumInteritemSpacing = 0.0; layout.sectionInset = UIEdgeInsetsZero; layout.scrollDirection = .Horizontal collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView!.dataSource = self collectionView!.pagingEnabled = true collectionView!.registerClass(TweetStatusCell.classForCoder(), forCellWithReuseIdentifier:ReuseIdentifier) view.addSubview(collectionView!) self.dataSource?.getNextStatusIds((maxId: nextMaxId, account: account!), callback: self.resultHandler) } func resultHandler(idList: [String]) { if idList.isEmpty { nextMaxId = nil } else { nextMaxId = String(minElement(idList.map({(x:String) in x.toInt()!})) - 1) } statusIdArray += idList dispatch_async(dispatch_get_main_queue()) { self.collectionView?.reloadData() } } } extension TwitterMediaTimeline : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return statusIdArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if indexPath.row + 1 == statusIdArray.count { if let maxId = nextMaxId { self.dataSource?.getNextStatusIds((maxId: maxId, account: account!), callback: self.resultHandler) } } let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! TweetStatusCell self.loadStatus(statusIdArray[indexPath.row]) { status in cell.setStatus(status) } return cell; } } //MARK: Network extension TwitterMediaTimeline { func defaultRequestHandler(handler: JSON -> Void) -> SLRequestHandler { return { body, response, error in if (body == nil) { println("HTTPRequest Error: \(error.localizedDescription)") return } if (response.statusCode < 200 && 300 <= response.statusCode) { println("The response status code is \(response.statusCode)") return } handler(JSON(data: body!)) } } func loadStatus(statusId : String, completion : TweetStatus -> Void) { if let json = statusMap[statusId] { completion(json) } else { let url = "https://api.twitter.com/1.1/statuses/show/\(statusId).json" let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: url), parameters: nil) request.account = self.account request.performRequestWithHandler { body, response, error in let json = JSON(data: body!) if let status = TweetStatus.fromJSON(json) { self.statusMap[statusId] = status dispatch_async(dispatch_get_main_queue()) { completion(status) } } else { println("TweetStatus JSON parse fail") } } } } }
mit
8db628afcebbc107b09c08a067e4e5fb
34.788136
136
0.614164
5.167687
false
false
false
false
digoreis/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0064.xcplaygroundpage/Contents.swift
1
2817
/*: # Referencing the Objective-C selector of property getters and setters * Proposal: [SE-0064](0064-property-selectors.md) * Author: [David Hart](https://github.com/hartbit) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-April/000102.html) * Bug: [SR-1239](https://bugs.swift.org/browse/SR-1239) ## Introduction Proposal [SE-0022](0022-objc-selectors.md) was accepted and implemented to provide a `#selector` expression to reference Objective-C method selectors. Unfortunately, it does not allow referencing the getter and setter methods of properties. This proposal seeks to provide a design to reference those methods for the Swift 3.0 timeframe. * [Original swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160215/010791.html) * [Follow-up swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160222/010960.html) ## Motivation The `#selector` expression is very useful but does not yet cover all cases. Accessing property getter and setters requires to drop down to the string syntax and forgo type-safety. This proposal supports this special case without introducing new syntax, but by introducing new overloads to the `#selector` compiler expression. ## Proposed solution Introduce two new overrides to the `#selector` expression that allows building a selector which points to the getter or the setter of a property. ```swift class Person: NSObject { dynamic var firstName: String dynamic let lastName: String dynamic var fullName: String { return "\(firstName) \(lastName)" } init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } } let firstNameGetter = #selector(getter: Person.firstName) let firstNameSetter = #selector(setter: Person.firstName) ``` Both overrides expect a property and the setter requires a variable property. For example, the following line of code would produce an error because the lastName property is defined with let. ``` let lastNameSetter = #selector(setter: Person.lastName) // Argument of #selector(setter:) must refer to a variable property ``` ## Impact on existing code The introduction of the new `#selector` overrides has no impact on existing code and could improve the string-literal-as-selector to `#selector` migrator. ## Alternatives considered A long term alternive could arrise from the design of lenses in Swift. But as this is purely hypothetical and out of scope for Swift 3, this proposal fixes the need for referencing property selectors in a type-safe way straight-away. ---------- [Previous](@previous) | [Next](@next) */
mit
c9464839cf53ebbc7def4140090bc050
43.015625
336
0.760383
4.130499
false
false
false
false
abelsanchezali/ViewBuilder
ViewBuilderDemo/ViewBuilderDemo/Integration/Models/Layout+Definitions.swift
1
2622
// // Layout+Definitions.swift // ViewBuilderDemo // // Created by Abel Sanchez on 7/2/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import ViewBuilder import UIKit public struct LayoutAnchor : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let none = LayoutAnchor([]) public static let top = LayoutAnchor(rawValue: 1 << 0) public static let left = LayoutAnchor(rawValue: 1 << 1) public static let bottom = LayoutAnchor(rawValue: 1 << 2) public static let right = LayoutAnchor(rawValue: 1 << 3) public static let fill = LayoutAnchor([.top, .left, .bottom, .right]) public static let centerX = LayoutAnchor(rawValue: 1 << 4) public static let centerY = LayoutAnchor(rawValue: 1 << 5) public static let center = LayoutAnchor([.centerX, .centerY]) } extension LayoutAnchor: NSValueConvertible { public func convertToNSValue() -> NSValue? { return NSNumber(value: self.rawValue as Int) } } public class Anchor: Object, TextDeserializer { private static let AnchorByText: [String: LayoutAnchor] = ["Fill": LayoutAnchor.fill, "None": LayoutAnchor.none, "Left": LayoutAnchor.left, "Top": LayoutAnchor.top, "Right": LayoutAnchor.right, "Bottom": LayoutAnchor.bottom, "CenterX": LayoutAnchor.centerX, "CenterY": LayoutAnchor.centerY, "Center": LayoutAnchor.center] public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { guard let text = text else { return nil } guard let words = service.parseValidWordsArray(from: text) else { return nil } var value = LayoutAnchor.none for word in words { guard let anchor = Anchor.AnchorByText[word] else { Log.shared.write("Warning: Ingnoring \"\(word)\" when processing LayoutAnchor deserialization.") continue } value.insert(anchor) } return value } }
mit
b8e04b4822c2447d2639c689e0731dfd
38.119403
112
0.517741
5.541226
false
false
false
false
ConradoMateu/Swift-Basics
Basic/Enumerations&Structures.playground/Contents.swift
1
2180
//: Playground - noun: a place where people can play import UIKit // Enumerations define a common type for a group of related values. Enumerations can have methods associated with them. // Use enum to create an enumeration. enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.rawValue) } } } let ace = Rank.Ace //Use the rawValue property to access the raw value of an enumeration member. let aceRawValue = ace.rawValue // Use the `init?(rawValue:)` initializer to make an instance of an enumeration from a raw value. if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() } // In cases where there isn’t a meaningful raw value, you don’t have to provide one. enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription() // One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference. Structures are great for defining lightweight data types that don’t need to have capabilities like inheritance and type casting. // Use struct to create a structure. struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription()
apache-2.0
c4f2f6d42220c44e39db340713fd3ac0
26.175
316
0.656854
4.510373
false
false
false
false
karivalkama/Agricola-Scripture-Editor
TranslationEditor/ConnectionUIView.swift
1
14825
// // ConnectionUIView.swift // TranslationEditor // // Created by Mikko Hilpinen on 17.5.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation import AVFoundation import QRCodeReader import MessageUI fileprivate enum ConnectionState { case disconnected, joined, hosting var actionText: String { var text = "" switch self { case .disconnected: text = "Disconnect" case .joined: text = "Join" case .hosting: text = "Host" } return NSLocalizedString(text, comment: "A label for an action that changes an online state") } var processingText: String { var text = "" switch self { case .disconnected: text = "Disconnecting" case .joined: text = "Joining" case .hosting: text = "Hosting" } return NSLocalizedString(text, comment: "A label for a processing online state") } var ongoingText: String { var text = "" switch self { case .disconnected: text = "Disconnected" case .joined: text = "Joined" case .hosting: text = "Hosting" } return NSLocalizedString(text, comment: "A label for an ongoing online state") } } @IBDesignable class ConnectionUIView: CustomXibView, QRCodeReaderViewControllerDelegate, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate, ConnectionListener { // OUTLETS -------------- //@IBOutlet weak var hostingSwitch: UISwitch! @IBOutlet weak var qrView: UIView! @IBOutlet weak var qrImageView: UIImageView! //@IBOutlet weak var joinSwitch: UISwitch! @IBOutlet weak var onlineStatusView: OnlineStatusView! @IBOutlet weak var hostInfoView: UIView! @IBOutlet weak var hostImageView: UIImageView! @IBOutlet weak var hostNameLabel: UILabel! @IBOutlet weak var hostProjectLabel: UILabel! @IBOutlet weak var sendEmailButton: BasicButton! @IBOutlet weak var bookSelectionView: UIView! @IBOutlet weak var bookSelectionTableView: UITableView! @IBOutlet weak var connectionSegmentedControl: UISegmentedControl! @IBOutlet weak var sharingView: UIView! // ATTRIBUTES ---------- weak var viewController: UIViewController? // private let canSendMail = MFMailComposeViewController.canSendMail() private var targetTranslations = [Book]() private var joining = false // The reader used for capturing QR codes, initialized only when used private lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: .back) } return QRCodeReaderViewController(builder: builder) }() private var canHost = false private var canJoin = false // COMPUTED PROPERTIES ---- private var availableConnectionStates: [(ConnectionState, Int)] { var states = [(ConnectionState.disconnected, 0)] var nextIndex = 1 if canJoin { states.add((ConnectionState.joined, nextIndex)) nextIndex += 1 } if canHost { states.add((ConnectionState.hosting, nextIndex)) nextIndex += 1 } return states } // INIT -------------------- override init(frame: CGRect) { super.init(frame: frame) setupXib(nibName: "Connect2") } required init?(coder: NSCoder) { super.init(coder: coder) setupXib(nibName: "Connect2") } override func awakeFromNib() { bookSelectionView.isHidden = true bookSelectionTableView.register(UINib(nibName: "LabelCell", bundle: nil), forCellReuseIdentifier: LabelCell.identifier) bookSelectionTableView.dataSource = self bookSelectionTableView.delegate = self var projectFound = false do { if let projectId = Session.instance.projectId, let project = try Project.get(projectId) { targetTranslations = try project.targetTranslationQuery().resultObjects() targetTranslations.sort(by: { $0.code < $1.code }) projectFound = true } } catch { print("ERROR: Failed to read target translation data. \(error)") } canHost = projectFound || P2PHostSession.instance != nil canJoin = QRCodeReader.isAvailable() if !canHost { connectionSegmentedControl.removeSegment(at: 2, animated: false) } if !canJoin { connectionSegmentedControl.removeSegment(at: 1, animated: false) } updateStatus() sharingView.isHidden = targetTranslations.isEmpty } // ACTIONS -------------- @IBAction func connectionModeChanged(_ sender: Any) { let newState = stateForIndex(connectionSegmentedControl.selectedSegmentIndex) // Join if newState == .joined { guard let viewController = viewController else { print("ERROR: No view controller to host the QR scanner") return } if QRCodeReader.isAvailable() { joining = true // Presents a join P2P VC readerVC.delegate = self readerVC.modalPresentationStyle = .formSheet viewController.present(readerVC, animated: true, completion: nil) } else { connectionSegmentedControl.selectedSegmentIndex = 0 // TODO: Show some kind of error label } } else { P2PClientSession.stop() } // Hosting if newState == .hosting { if P2PHostSession.instance == nil { do { _ = try P2PHostSession.start(projectId: Session.instance.projectId, hostAvatarId: Session.instance.avatarId) } catch { print("ERROR: Failed to start a P2P hosting session") } } } else { P2PHostSession.stop() } // TODO: Animate updateStatus() } /* @IBAction func hostingSwitchChanged(_ sender: Any) { // TODO: Animate if hostingSwitch.isOn { if P2PHostSession.instance == nil { do { _ = try P2PHostSession.start(projectId: Session.instance.projectId, hostAvatarId: Session.instance.avatarId) } catch { print("ERROR: Failed to start a P2P hosting session") } } } else { P2PHostSession.stop() } updateStatus() } @IBAction func joinSwitchChanged(_ sender: Any) { if joinSwitch.isOn { guard let viewController = viewController else { print("ERROR: No view controller to host the QR scanner") return } // Presents a join P2P VC readerVC.delegate = self readerVC.modalPresentationStyle = .formSheet viewController.present(readerVC, animated: true, completion: nil) } else { P2PClientSession.stop() updateStatus() } } */ @IBAction func sendEmailButtonPressed(_ sender: Any) { // TODO: Animate // When send email button is pressed, book selection is displayed bookSelectionView.isHidden = false sendEmailButton.isEnabled = false } @IBAction func cancelSendButtonPressed(_ sender: Any) { // TODO: Animate // Hides the book selection sendEmailButton.isEnabled = true bookSelectionView.isHidden = true } // IMPLEMENTED METHODS ------ func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { reader.stopScanning() print("STATUS: Scanned QR code result: \(result.value) (of type \(result.metadataType))") viewController.or(reader).dismiss(animated: true, completion: nil) joining = false if let info = P2PConnectionInformation.parse(from: result.value) { print("STATUS: Starting P2P client session") print("STATUS: \(info)") P2PClientSession.start(info) } else { print("ERROR: Failed to parse connection information from \(result.value)") } // TODO: Animate updateStatus() } func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) { print("STATUS: Switched camera") } func readerDidCancel(_ reader: QRCodeReaderViewController) { reader.stopScanning() print("STATUS: QR Capture session cancelled") viewController.or(reader).dismiss(animated: true, completion: nil) joining = false // connectionSegmentedControl.selectedSegmentIndex = 0 // joinSwitch.isOn = false updateStatus() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return targetTranslations.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: LabelCell.identifier, for: indexPath) as! LabelCell cell.configure(text: targetTranslations[indexPath.row].code.description) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let viewController = viewController else { print("ERROR: No view controller to host the share view.") return } do { let book = targetTranslations[indexPath.row] let paragraphs = try ParagraphView.instance.latestParagraphQuery(bookId: book.idString).resultObjects() let usx = USXWriter().writeUSXDocument(book: book, paragraphs: paragraphs) guard let data = usx.data(using: .utf8) else { print("ERROR: Failed to generate USX data") return } sendEmailButton.isEnabled = true bookSelectionView.isHidden = true let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first! let fileurl = dir.appendingPathComponent("\(book.code.code).usx") try data.write(to: fileurl, options: Data.WritingOptions.atomic) let shareVC = UIActivityViewController(activityItems: [fileurl], applicationActivities: nil) shareVC.popoverPresentationController?.sourceView = sendEmailButton /* let mailVC = MFMailComposeViewController() mailVC.mailComposeDelegate = self mailVC.addAttachmentData(data, mimeType: "application/xml", fileName: "\(book.code.code).usx") mailVC.setSubject("\(book.code.name) - \(book.identifier) \(NSLocalizedString("USX Export", comment: "Part of the default export email subject"))") */ viewController.present(shareVC, animated: true, completion: nil) // viewController.present(mailVC, animated: true, completion: nil) } catch { print("ERROR: Failed to read, parse and send translation data. \(error)") } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } func onConnectionStatusChange(newStatus status: ConnectionStatus) { onlineStatusView.status = status // When in idle mode and client session is active, updates host info if (status == .done || status == .upToDate) && P2PClientSession.isConnected { updateHostInfoViewStatus() } } func onConnectionProgressUpdate(transferred: Int, of total: Int, progress: Double) { onlineStatusView.updateProgress(completed: transferred, of: total, progress: progress) } // OTHER METHODS ----- private func stateForIndex(_ index: Int) -> ConnectionState { if index <= 0 { return .disconnected } else if index == 2 { return .hosting } else { if canJoin { return .joined } else { return .hosting } } } private func selectConnectionState(_ selectedState: ConnectionState, isProcessing: Bool = false) { // Updates labels and selection for (state, index) in availableConnectionStates { if state == selectedState { connectionSegmentedControl.setTitle(isProcessing ? state.processingText : state.ongoingText, forSegmentAt: index) connectionSegmentedControl.selectedSegmentIndex = index } else { connectionSegmentedControl.setTitle(state.actionText, forSegmentAt: index) } } } private func updateStatus() { if let hostSession = P2PHostSession.instance { selectConnectionState(.hosting) // QR view and the QR tag are displayed when there's an active host session if qrView.isHidden, let qrImage = hostSession.connectionInformation?.qrCode?.image { qrImageView.image = qrImage qrView.isHidden = false } } else { qrImageView.image = nil qrView.isHidden = true if P2PClientSession.isConnected { selectConnectionState(.joined) onlineStatusView.isHidden = false } else { onlineStatusView.isHidden = true if joining { selectConnectionState(.joined, isProcessing: true) } else { selectConnectionState(.disconnected) } } } updateHostInfoViewStatus() } /* private func updateHostViewStatus() { if let hostSession = P2PHostSession.instance { // QR view and the QR tag are displayed when there's an active host session if qrView.isHidden, let qrImage = hostSession.connectionInformation?.qrCode?.image { qrImageView.image = qrImage qrView.isHidden = false hostingSwitch.isOn = true hostingSwitch.isEnabled = true } } else { qrImageView.image = nil qrView.isHidden = true hostingSwitch.isOn = false // Hosting is disabled while there is an active client session hostingSwitch.isEnabled = !P2PClientSession.isConnected } } private func updateJoinViewStatus() { if P2PClientSession.isConnected { joinSwitch.isOn = true joinSwitch.isEnabled = true onlineStatusView.isHidden = false } else { joinSwitch.isOn = false onlineStatusView.isHidden = true // Join switch is disabled while there's a host session in place. // Camera is required too // TODO: Add camera check joinSwitch.isEnabled = P2PHostSession.instance == nil } }*/ private func updateHostInfoViewStatus() { var infoFound = false if P2PClientSession.isConnected, let clientSession = P2PClientSession.instance { // If correct info is already displayed, doesn't bother reading data again if hostInfoView.isHidden { do { if let projectId = clientSession.projectId, let hostAvatarId = clientSession.hostAvatarId, let project = try Project.get(projectId), let hostAvatar = try Avatar.get(hostAvatarId), let hostInfo = try hostAvatar.info() { infoFound = true hostImageView.image = hostInfo.image ?? #imageLiteral(resourceName: "userIcon") hostNameLabel.text = "\(NSLocalizedString("Joined", comment: "Part of host info desciption. Followed by host user name.")) \(hostAvatar.name)" hostProjectLabel.text = "\(NSLocalizedString("on project:", comment: "Part of host info description. Followed by project name")) \(project.name)" // Makes sure the current user also has access to the project /* if let accountId = Session.instance.accountId { if !project.contributorIds.contains(accountId) { project.contributorIds.append(accountId) try project.push() } } */ } } catch { print("ERROR: Failed to read host data from the database. \(error)") } } else { infoFound = true } } hostInfoView.isHidden = !infoFound } }
mit
fc9d0e2283edb4151c0f6a5c1ef5c9ca
23.543046
221
0.7017
3.793245
false
false
false
false
Roosting/Index
src/Index.swift
1
1875
import Foundation import MessagePack class Index { private let formatter: NSDateFormatter = NSDateFormatter() init() { formatter.dateFormat = "yyyy-MM-dd'T'HH-mm-ss'Z'" } func packPackages(packages: [Package]) { let path = getOutputName() if !fileManager.createFileAtPath(path, contents: nil, attributes: nil) { printAndExit("Failed to create index file '\(path)'") } let file = NSFileHandle(forWritingAtPath: getOutputName())! let header = "Roost Index Version 1\n" file.writeData(header.dataUsingEncoding(NSUTF8StringEncoding)!) var dictionary = [MessagePackValue : MessagePackValue]() for package in packages { let key = MessagePackValue.String(package.name) let value = packedPackage(package) dictionary[key] = value } let packed = MessagePack.pack(.Map(dictionary)) file.writeData(packed) } private func packedPackage(package: Package) -> MessagePackValue { return MessagePackValue.Map([ .String("name") : .String(package.name), .String("version") : .String(package.version.description), .String("versions") : packPackageVersions(package.versions), ]) } /** Convert Array of Version structs into a MessagePackValue.Array of MessagePackValue.Map instances. */ private func packPackageVersions(versions: [Version]) -> MessagePackValue { let versionsValues = versions.map { (v) in return MessagePackValue.Map([ .String("version") : .String(v.version.description), .String("description") : .String(v.description), ]) } return MessagePackValue.Array(versionsValues) } /** Timestamped name of the file to which to write the packed index. */ private func getOutputName() -> String { let date = formatter.stringFromDate(NSDate()) return "Index-\(date).bin" } }
mit
b7e004d2950fff3a74ff97e4804d3eec
25.785714
77
0.674667
4.411765
false
false
false
false
PangeaSocialNetwork/PangeaGallery
PangeaMediaPicker/ImagePicker/AlbumListViewCell.swift
1
2037
// // AlbumListViewCell.swift // PangeaMediaPicker // // Created by Roger Li on 2017/8/28. // Copyright © 2017年 Roger Li. All rights reserved. // import UIKit import Photos class AlbumListViewCell: UITableViewCell { static let cellIdentifier = "AlbumListTableViewCellIdentifier" let bundle = Bundle.init(identifier: "org.cocoapods.PangeaMediaPicker") @IBOutlet var firstImageView: UIImageView! @IBOutlet var albumTitleLabel: UILabel! @IBOutlet var albumCountLabel: UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // Show first image and name var asset: PHAsset? { willSet { if newValue == nil { firstImageView?.image = UIImage.init(named: "l_picNil", in:bundle, compatibleWith: nil) return } let defaultSize = CGSize(width: UIScreen.main.scale + bounds.height, height: UIScreen.main.scale + bounds.height) let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true PHCachingImageManager.default().requestImage(for: newValue!, targetSize: defaultSize, contentMode: .aspectFill, options: options, resultHandler: { (img, _) in self.firstImageView?.image = img }) } } var albumTitleAndCount: (String?, Int)? { willSet { if newValue == nil { return } self.albumTitleLabel?.text = (newValue!.0 ?? "") self.albumCountLabel?.text = String(describing: newValue!.1) self.accessoryView?.isHidden = true self.accessoryView = UIImageView(image: UIImage(named: "checkMark", in: bundle, compatibleWith: nil)) } } }
mit
a23ec1e184076979ab70f426f9143055
35.321429
113
0.544739
5.338583
false
false
false
false
gecko655/Swifter
Sources/SwifterFavorites.swift
2
4520
// // SwifterFavorites.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 Swifter { /** GET favorites/list Returns the 20 most recent Tweets favorited by the authenticating or specified user. If you do not provide either a user_id or screen_name to this method, it will assume you are requesting on behalf of the authenticating user. Specify one or the other for best results. */ public func getRecentlyFavouritedTweets(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/list.json" var parameters = Dictionary<String, Any>() parameters["count"] ??= count parameters["since_id"] ??= sinceID parameters["max_id"] ??= maxID self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } public func getRecentlyFavouritedTweets(for userTag: UserTag, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/list.json" var parameters = Dictionary<String, Any>() parameters[userTag.key] = userTag.value parameters["count"] ??= count parameters["since_id"] ??= sinceID parameters["max_id"] ??= maxID self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST favorites/destroy Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. */ public func unfavouriteTweet(forID id: String, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/destroy.json" var parameters = Dictionary<String, Any>() parameters["id"] = id parameters["include_entities"] ??= includeEntities self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST favorites/create Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. */ public func favouriteTweet(forID id: String, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: HTTPRequest.FailureHandler? = nil) { let path = "favorites/create.json" var parameters = Dictionary<String, Any>() parameters["id"] = id parameters["include_entities"] ??= includeEntities self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } }
mit
e4e6c4141fa6fbcc1e367018cc949e07
47.085106
250
0.702876
4.529058
false
false
false
false
git-hushuai/MOMO
MMHSMeterialProject/FirstViewController.swift
1
17460
// // FirstViewController.swift // MMHSMeterialProject // // Created by hushuaike on 16/3/24. // Copyright © 2016年 hushuaike. All rights reserved. // import UIKit class FirstViewController: TKBaseViewController ,UITableViewDataSource,UITableViewDelegate{ var selectCityArray : NSMutableArray = NSMutableArray(); var selectJobListArray :NSMutableArray = NSMutableArray(); var selectJobNameList :NSMutableArray = NSMutableArray(); var selectEduListArray:NSMutableArray = NSMutableArray(); var TKTableView : UITableView = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height), style: UITableViewStyle.Plain); var dataSourceLists : NSMutableArray = NSMutableArray(); var db = SQLiteDB.sharedInstance(); func setUpUI(){ let notiBtn = UIButton.init(type: UIButtonType.Custom); notiBtn.setTitle("通知", forState: UIControlState.Normal); notiBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal); notiBtn.titleLabel?.font = UIFont.systemFontOfSize(14.0) notiBtn.setTitleColor(UIColor.init(red: 0xff/255.0, green: 0xff/255.0, blue: 0xff/255.0, alpha: 0.6), forState: UIControlState.Highlighted); notiBtn.addTarget(self, action: "onClcikNotificationBtn:", forControlEvents: UIControlEvents.TouchUpInside); notiBtn.sizeToFit(); self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: notiBtn); self.view.addSubview(self.TKTableView); self.TKTableView.sd_layout() .topSpaceToView(self.view,0) .leftSpaceToView(self.view,0) .rightEqualToView(self.view) .bottomSpaceToView(self.view,0); self.TKTableView.backgroundColor = RGBA(0xf3,g:0xf3,b:0xf3,a: 1.0); self.TKTableView.delegate=self; self.TKTableView.dataSource=self; self.TKTableView.tableFooterView = UIView.init(); self.TKTableView.separatorStyle = UITableViewCellSeparatorStyle.None; self.TKTableView.registerClass(ClassFromString("TKFreeRecommandCell"), forCellReuseIdentifier:"TKFreeRecommandCell"); let loadingView = DGElasticPullToRefreshLoadingViewCircle() loadingView.tintColor = UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0) self.TKTableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in self?.loadNewJobItem(); }, loadingView: loadingView) self.TKTableView.dg_setPullToRefreshFillColor(UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0)) self.TKTableView.dg_setPullToRefreshBackgroundColor(self.TKTableView.backgroundColor!); self.TKTableView.contentOffset = CGPointMake(0, 120); // self.TKTableView.dg_headViewStrtLoading(); // self.TKTableView.addBounceHeadRefresh(self,bgColor:UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0),loadingColor:UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0), action: "loadNewJobItem"); self.TKTableView.addFootRefresh(self, action: "loadMoreData") } func loadMoreData(){ print("加载更多历史数据"); self.pullResumeInfo(false); } deinit{ self.TKTableView.dg_removePullToRefresh(); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); print("self navigation bar subinfo :\(self.navigationController?.navigationBar.subviews)"); self.removeNaviSingleView(); } func removeNaviSingleView(){ let subView = self.navigationController?.navigationBar.subviews[0]; print("subView FRAME :\(subView?.subviews)"); for tSubView in subView!.subviews{ if tSubView.bounds.size.height == 0.5{ tSubView.hidden = true; tSubView.removeFromSuperview(); } } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0); self.setConfigInfo(); self.setUpUI(); dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in self.loadLocalResumeDataInfo(); } } func loadLocalResumeDataInfo(){ // 将本地数据取出 let dbCacheModel = TKResumeDataCacheTool(); let nowDate = NSDate.init(); let timeInterval = nowDate.timeIntervalSince1970; let timeIntervalStr = String.init(format: "%i", Int(timeInterval) - 1); let localResumeLists = dbCacheModel.loadLocalAllResumeInfoWithResumeCateInfo("免费推荐", timeStampInfo: timeIntervalStr); print("localResume lists info :\(localResumeLists)"); let itemModelLists : NSArray = TKJobItemModel.parses(arr: localResumeLists) as! [TKJobItemModel]; print("first item Model lists:\(itemModelLists)"); self.dataSourceLists.removeAllObjects(); self.dataSourceLists.addObjectsFromArray(itemModelLists as [AnyObject]); dispatch_sync(dispatch_get_main_queue()) { () -> Void in self.TKTableView.reloadData(); } } func refreshTableViewInMainQueue(){ self.TKTableView.reloadData(); } //MARK:通知 func onClcikNotificationBtn(sender:UIButton){ print("sender btn title :\(sender.titleLabel?.text)"); self.hidesBottomBarWhenPushed = true; let notiVC = HSNotificationController(); notiVC.title = "通知"; self.navigationController?.pushViewController(notiVC, animated: true); self.hidesBottomBarWhenPushed = false; } func loadNewJobItem(){ self.pullResumeInfo(true); } func pullResumeInfo(isFreshCopr:Bool){ print("load thread info:\(NSThread.currentThread())"); let reqDict = self.getLoadNewJobItemReqDict(isFreshCopr); GNNetworkCenter.userLoadResumeItemBaseInfoWithReqObject(reqDict, andFunName: KAppUserLoadResumeFreeRecommandFunc) { (response:YWResponse!) -> Void in print("reqdict :\(reqDict)---responsedata:\(response.data)"); if (Int(response.retCode) == ERROR_NOERROR){ let responseDict:Dictionary<String,AnyObject> = response.data as! Dictionary; let itemArr : NSArray = responseDict["data"]! as! NSArray; print("job item array :\(itemArr)"); if itemArr.count > 0{ let cityInfo = self.getUserSelectCityName(); let deleDBModel = TKResumeDataCacheTool(); deleDBModel.clearTableResumeInfoWithParms("免费推荐", cityCateInfo: cityInfo) //加载数据成功之后将本地数据清空 let itemModel : NSArray = TKJobItemModel.parses(arr: itemArr) as! [TKJobItemModel]; for i in 0...(itemModel.count-1){ let dict = itemModel[i] as! TKJobItemModel; dict.cellItemInfo = "免费推荐"; print("dict cell item info :\(dict)"); let dbItem = TKResumeDataCacheTool(); // 先判断本地是否有该条记录 let job_id = String.init(format: "%@", dict.id); let cellItemCateInfo = dict.cellItemInfo; let queryData = dbItem.checkResumeItemIsAlreadySaveInLocal(job_id, resumeItemInfo: cellItemCateInfo); print("queryData inf0 :\(queryData)"); if(queryData.count > 0){ print("本地已经有该条记录"); }else{ // 本地没有该条数据需要缓存 dbItem.setDBItemInfoWithResumeModel(dict); dbItem.save(); } } // 展示数据 print("item model info:\(itemModel)"); self.showItemInfoWithArray(itemModel,isfresh:isFreshCopr); } }else{ print("数据加载出错"); let errorInfo = response.msg; SVProgressHUD.showErrorWithStatus(String.init(format: "%@", errorInfo)); dispatch_after(UInt64(1.5), dispatch_get_main_queue(), { () -> Void in SVProgressHUD.dismiss(); }); if isFreshCopr == true{ self.TKTableView.head?.stopRefreshing(); }else{ self.TKTableView.foot?.startRefreshing(); } } } } func getUserSelectCityName()->String{ var cityInfo = NSUserDefaults.standardUserDefaults().stringForKey("kUserDidSelectCityInfoKey"); if( cityInfo == nil) { cityInfo = "广州"; } return cityInfo as String!; } func showItemInfoWithArray(itemArr : NSArray,isfresh:Bool){ print("tableview head frame:\(self.TKTableView.head?.frame)"); if isfresh == true{ print("current THREADinfo:\(NSThread.currentThread())"); self.dataSourceLists.removeAllObjects(); self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]); print("self dataSourceList info:\(self.dataSourceLists)"); dispatch_after(1, dispatch_get_main_queue(), { () -> Void in self.TKTableView.reloadData(); self.TKTableView.tableHeadStopRefreshing(); self.TKTableView.dg_stopLoading(); }) }else{ self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]); if itemArr.count >= 20{ dispatch_after(1, dispatch_get_main_queue(), { () -> Void in self.TKTableView.tableFootStopRefreshing(); self.TKTableView.reloadData(); }) }else{ dispatch_async(dispatch_get_main_queue(), { () -> Void in dispatch_after(1, dispatch_get_main_queue(), { () -> Void in self.TKTableView.tableFootShowNomore(); self.TKTableView.reloadData(); }); }) } } } func getLoadNewJobItemReqDict(isFresh : Bool)->NSMutableDictionary{ // let reqDict = NSMutableDictionary(); let keyStr1 : String = NSString.init(format: "menu%@0", GNUserService.sharedUserService().userId) as String!; let keyStr2 : String = NSString.init(format: "menu%@1", GNUserService.sharedUserService().userId) as String!; let keyStr3 : String = NSString.init(format: "menu%@2", GNUserService.sharedUserService().userId) as String!; let userSelectCityInfo = NSUserDefaults.standardUserDefaults().stringForKey(keyStr1); let userSelectJobCateInfo = NSUserDefaults.standardUserDefaults().stringForKey(keyStr2); let userSelectDegreeInfo = NSUserDefaults.standardUserDefaults().stringForKey(keyStr3); var cityStr :String = ""; var jobCateStr :String = ""; var degreeStr : String = ""; if userSelectCityInfo != nil && self.selectCityArray.count>0{ cityStr = self.selectCityArray.objectAtIndex(Int(userSelectCityInfo!)!) as! String; cityStr = (cityStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 && (cityStr=="不限")) ? "":cityStr; } if userSelectJobCateInfo != nil && self.selectJobNameList.count>0 { jobCateStr = self.selectJobNameList.objectAtIndex(Int(userSelectJobCateInfo!)!) as! String; jobCateStr = (jobCateStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 && (jobCateStr=="不限")) ? "":cityStr; for i in 1...self.selectJobListArray.count{ let dict : Dictionary<String,String> = self.selectJobListArray.objectAtIndex(i) as! Dictionary; if dict["name"]==jobCateStr{ jobCateStr = dict["id"]!; } } } if userSelectDegreeInfo != nil && self.selectEduListArray.count>0{ degreeStr = self.selectEduListArray.objectAtIndex(Int(userSelectDegreeInfo!)!) as! String; degreeStr = (degreeStr=="不限") ? "" : degreeStr; } reqDict.setObject(cityStr, forKey: "position"); reqDict.setObject(jobCateStr, forKey: "category"); reqDict.setObject(degreeStr, forKey: "degree"); if isFresh==true{ // 刷新 reqDict.setObject(NSNumber.init(integer: 0),forKey: "lastTime"); }else{ //加载更多 if self.dataSourceLists.count > 0 { let jobItemModel = self.dataSourceLists.lastObject as! TKJobItemModel; reqDict.setObject(jobItemModel.ts,forKey: "lastTime"); }else{ //reqDict.setObject(NSNumber.init(integer: 0),forKey: "lastTime"); } } return reqDict; } func setConfigInfo(){ let positionArray = NSUserDefaults.standardUserDefaults().objectForKey("positions"); self.selectCityArray.addObject("不限"); self.selectCityArray.addObjectsFromArray(positionArray as! Array); let jobListArr = NSUserDefaults .standardUserDefaults() .objectForKey("job_category1"); self.selectJobNameList.addObject("不限"); self.selectJobListArray.addObjectsFromArray(jobListArr as! Array); for i in 0...(self.selectJobListArray.count-1){ let dict = self.selectJobListArray.objectAtIndex(i) ; let jobItemName = dict["name"]; self.selectJobNameList.addObject(jobItemName as! String); } let degreeArr = NSUserDefaults .standardUserDefaults() .objectForKey("degreeArray"); self.selectEduListArray.addObject("不限"); self.selectEduListArray.addObjectsFromArray(degreeArr as! Array); } // MARK: rgb color 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) } // MARK: tableview delegate 和 datasource 方法 func numberOfSectionsInTableView(tableView: UITableView) -> Int { print("dataSourceList count :\(self.dataSourceLists.count)"); self.TKTableView.foot?.hidden = self.dataSourceLists.count > 0 ? false : true; self.TKTableView.foot?.userInteractionEnabled = self.dataSourceLists.count > 0 ? true : false; return self.dataSourceLists.count; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1; } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0{ return 0 ; } return 10.0 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 10.0)); headView.backgroundColor = UIColor.clearColor(); return headView; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TKFreeRecommandCell") as? TKFreeRecommandCell; let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section); cell!.resumeItemModel = resumeModel as? TKJobItemModel; cell!.sd_tableView = tableView; cell!.sd_indexPath = indexPath; return cell!; } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section); return self.TKTableView.cellHeightForIndexPath(indexPath,model: resumeModel, keyPath:"resumeItemModel", cellClass: ClassFromString("TKFreeRecommandCell"), contentViewWidth:UIScreen.mainScreen().bounds.size.width); } // func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // // let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section); // let cell = tableView.cellForRowAtIndexPath(indexPath) as? TKFreeRecommandCell; // cell!.resumeItemModel = resumeModel as? TKJobItemModel; // } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true); print("indexPath info:\(indexPath)"); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
e54aa935b30819992ef47f5f3cfc7e29
41.965087
239
0.61263
4.707377
false
false
false
false
adorabledorks/radio.ios
R-a-dio/MasterViewController.swift
1
3521
import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = NSMutableArray() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insertObject(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] as NSDate let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let object = objects[indexPath.row] as NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeObjectAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
bc43ab8ad0855a84f85bfd3d93d6f8d9
38.561798
157
0.689009
5.967797
false
false
false
false
chatea/BulletinBoard
BulletinBoard/MsgCollection/LabelCollectionViewItemView.swift
1
950
// import Foundation import AppKit class LabelCollectionViewItemView: NSView { // MARK: properties var selected: Bool = false { didSet { if selected != oldValue { needsDisplay = true } } } var highlightState: NSCollectionViewItemHighlightState = .None { didSet { if highlightState != oldValue { needsDisplay = true } } } // MARK: NSView override var wantsUpdateLayer: Bool { return true } override func updateLayer() { if selected { self.layer?.cornerRadius = 10 layer!.backgroundColor = NSColor.darkGrayColor().CGColor } else { self.layer?.cornerRadius = 0 layer!.backgroundColor = NSColor.lightGrayColor().CGColor } } // MARK: init override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true layer?.masksToBounds = true } required init?(coder: NSCoder) { super.init(coder: coder) wantsLayer = true layer?.masksToBounds = true } }
apache-2.0
f89dbb139fcd9eb57c5637fd78a69d38
16.290909
65
0.681053
3.639847
false
false
false
false
mozilla-mobile/firefox-ios
Tests/XCUITests/PrivateBrowsingTest.swift
2
13307
// 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 url1 = "example.com" let url2 = path(forTestPage: "test-mozilla-org.html") let url3 = path(forTestPage: "test-example.html") let urlIndexedDB = path(forTestPage: "test-indexeddb-private.html") let url1And3Label = "Example Domain" let url2Label = "Internet for people, not profit — Mozilla" class PrivateBrowsingTest: BaseTestCase { typealias HistoryPanelA11y = AccessibilityIdentifiers.LibraryPanels.HistoryPanel func testPrivateTabDoesNotTrackHistory() { navigator.openURL(url1) waitForTabsButton() navigator.goto(BrowserTabMenu) // Go to History screen navigator.goto(LibraryPanel_History) waitForExistence(app.tables[HistoryPanelA11y.tableView]) XCTAssertTrue(app.tables[HistoryPanelA11y.tableView].staticTexts[url1And3Label].exists) // History without counting Clear Recent History and Recently Closed let history = app.tables[HistoryPanelA11y.tableView].cells.count - 1 XCTAssertEqual(history, 1, "History entries in regular browsing do not match") // Go to Private browsing to open a website and check if it appears on History navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url2) waitForValueContains(app.textFields["url"], value: "mozilla") navigator.goto(LibraryPanel_History) waitForExistence(app.tables[HistoryPanelA11y.tableView]) XCTAssertTrue(app.tables[HistoryPanelA11y.tableView].staticTexts[url1And3Label].exists) XCTAssertFalse(app.tables[HistoryPanelA11y.tableView].staticTexts[url2Label].exists) // Open one tab in private browsing and check the total number of tabs let privateHistory = app.tables[HistoryPanelA11y.tableView].cells.count - 1 XCTAssertEqual(privateHistory, 1, "History entries in private browsing do not match") } func testTabCountShowsOnlyNormalOrPrivateTabCount() { // Open two tabs in normal browsing and check the number of tabs open navigator.performAction(Action.CloseURLBarOpen) navigator.nowAt(NewTabScreen) navigator.openNewURL(urlString: url2) waitUntilPageLoad() waitForTabsButton() navigator.goto(TabTray) waitForExistence(app.cells.staticTexts[url2Label]) let numTabs = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numTabs, 2, "The number of regular tabs is not correct") // Open one tab in private browsing and check the total number of tabs navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.goto(URLBarOpen) waitUntilPageLoad() navigator.openURL(url3) waitForValueContains(app.textFields["url"], value: "test-example") navigator.nowAt(NewTabScreen) waitForTabsButton() navigator.goto(TabTray) waitForExistence(app.cells.staticTexts[url1And3Label]) let numPrivTabs = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numPrivTabs, 1, "The number of private tabs is not correct") // Go back to regular mode and check the total number of tabs navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode) waitForExistence(app.cells.staticTexts[url2Label]) waitForNoExistence(app.cells.staticTexts[url1And3Label]) let numRegularTabs = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numRegularTabs, 2, "The number of regular tabs is not correct") } func testClosePrivateTabsOptionClosesPrivateTabs() { // Check that Close Private Tabs when closing the Private Browsing Button is off by default navigator.performAction(Action.CloseURLBarOpen) navigator.nowAt(NewTabScreen) waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 5) navigator.goto(SettingsScreen) let settingsTableView = app.tables[AccessibilityIdentifiers.Settings.tableViewController] while settingsTableView.staticTexts["Close Private Tabs"].exists == false { settingsTableView.swipeUp() } let closePrivateTabsSwitch = settingsTableView.switches["settings.closePrivateTabs"] XCTAssertFalse(closePrivateTabsSwitch.isSelected) // Open a Private tab navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url2) waitForTabsButton() // Go back to regular browser navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode) // Go back to private browsing and check that the tab has not been closed navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) waitForExistence(app.cells.staticTexts[url2Label], timeout: 5) checkOpenTabsBeforeClosingPrivateMode() // Now the enable the Close Private Tabs when closing the Private Browsing Button if !iPad() { app.cells.staticTexts[url2Label].tap() } else { app.otherElements["Tabs Tray"].collectionViews.cells.staticTexts[url2Label].tap() } waitForTabsButton() waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 10) navigator.nowAt(BrowserTab) navigator.goto(SettingsScreen) closePrivateTabsSwitch.tap() navigator.goto(BrowserTab) waitForTabsButton() // Go back to regular browsing and check that the private tab has been closed and that the initial Private Browsing message appears when going back to Private Browsing navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode) navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) waitForNoExistence(app.cells.staticTexts["Internet for people, not profit — Mozilla. Currently selected tab."]) checkOpenTabsAfterClosingPrivateMode() } /* Loads a page that checks if an db file exists already. It uses indexedDB on both the main document, and in a web worker. The loaded page has two staticTexts that get set when the db is correctly created (because the db didn't exist in the cache) https://bugzilla.mozilla.org/show_bug.cgi?id=1646756 */ func testClearIndexedDB() { navigator.performAction(Action.CloseURLBarOpen) navigator.nowAt(NewTabScreen) enableClosePrivateBrowsingOptionWhenLeaving() func checkIndexedDBIsCreated() { navigator.openURL(urlIndexedDB) waitUntilPageLoad() XCTAssertTrue(app.webViews.staticTexts["DB_CREATED_PAGE"].exists) XCTAssertTrue(app.webViews.staticTexts["DB_CREATED_WORKER"].exists) } navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) checkIndexedDBIsCreated() navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode) checkIndexedDBIsCreated() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) checkIndexedDBIsCreated() } func testPrivateBrowserPanelView() { navigator.performAction(Action.CloseURLBarOpen) navigator.nowAt(NewTabScreen) // If no private tabs are open, there should be a initial screen with label Private Browsing navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) let numPrivTabsFirstTime = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numPrivTabsFirstTime, 0, "The number of tabs is not correct, there should not be any private tab yet") // If a private tab is open Private Browsing screen is not shown anymore navigator.openURL(path(forTestPage: "test-mozilla-org.html")) // Wait until the page loads and go to regular browser waitUntilPageLoad() waitForTabsButton() navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode) // Go back to private browsing navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.nowAt(TabTray) let numPrivTabsOpen = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numPrivTabsOpen, 1, "The number of private tabs is not correct") } } fileprivate extension BaseTestCase { func checkOpenTabsBeforeClosingPrivateMode() { if !iPad() { let numPrivTabs = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed") } else { let numPrivTabs = app.collectionViews["Top Tabs View"].cells.count XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed") } } func checkOpenTabsAfterClosingPrivateMode() { let numPrivTabsAfterClosing = app.otherElements["Tabs Tray"].cells.count XCTAssertEqual(numPrivTabsAfterClosing, 0, "The number of tabs is not correct, the private tab should have been closed") } func enableClosePrivateBrowsingOptionWhenLeaving() { navigator.goto(SettingsScreen) let settingsTableView = app.tables["AppSettingsTableViewController.tableView"] while settingsTableView.staticTexts["Close Private Tabs"].exists == false { settingsTableView.swipeUp() } let closePrivateTabsSwitch = settingsTableView.switches["settings.closePrivateTabs"] closePrivateTabsSwitch.tap() } } class PrivateBrowsingTestIpad: IpadOnlyTestCase { typealias HistoryPanelA11y = AccessibilityIdentifiers.LibraryPanels.HistoryPanel // This test is only enabled for iPad. Shortcut does not exists on iPhone func testClosePrivateTabsOptionClosesPrivateTabsShortCutiPad() { if skipPlatform { return } waitForTabsButton() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url2) waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 5) enableClosePrivateBrowsingOptionWhenLeaving() // Leave PM by tapping on PM shourt cut navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel) waitForTabsButton() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) checkOpenTabsAfterClosingPrivateMode() } func testiPadDirectAccessPrivateMode() { if skipPlatform { return } waitForTabsButton() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel) // A Tab opens directly in HomePanels view XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") // Open website and check it does not appear under history once going back to regular mode navigator.openURL("http://example.com") waitUntilPageLoad() // This action to enable private mode is defined on HomePanel Screen that is why we need to open a new tab and be sure we are on that screen to use the correct action navigator.goto(NewTabScreen) navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel) navigator.nowAt(NewTabScreen) navigator.goto(LibraryPanel_History) waitForExistence(app.tables[HistoryPanelA11y.tableView]) // History without counting Clear Recent History, Recently Closed let history = app.tables[HistoryPanelA11y.tableView].cells.count - 2 XCTAssertEqual(history, 0, "History list should be empty") } func testiPadDirectAccessPrivateModeBrowserTab() { if skipPlatform { return } navigator.openURL("www.mozilla.org") waitForTabsButton() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarBrowserTab) // A Tab opens directly in HomePanels view XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") // Open website and check it does not appear under history once going back to regular mode navigator.openURL("http://example.com") navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarBrowserTab) navigator.goto(LibraryPanel_History) waitForExistence(app.tables[HistoryPanelA11y.tableView]) // History without counting Clear Recent History, Recently Closed let history = app.tables[HistoryPanelA11y.tableView].cells.count - 2 XCTAssertEqual(history, 1, "There should be one entry in History") let savedToHistory = app.tables[HistoryPanelA11y.tableView].cells.staticTexts[url2Label] waitForExistence(savedToHistory) XCTAssertTrue(savedToHistory.exists) } }
mpl-2.0
ba6f531e61fbd9407ab972515d1585d4
47.199275
175
0.723371
5.06588
false
true
false
false
google/iosched-ios
Source/IOsched/Screens/Schedule/Details/Speaker/SpeakerDetailsCollectionViewMainInfoCell.swift
1
4749
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MaterialComponents import SafariServices class SpeakerDetailsCollectionViewMainInfoCell: MDCCollectionViewCell { private lazy var detailsLabel: UILabel = self.setupDetailsLabel() private lazy var twitterButton: MDCButton = self.setupTwitterButton() private lazy var stackContainer: UIStackView = self.setupStackContainer() private lazy var spacerView: UIView = self.setupSpacerView() var viewModel: SpeakerDetailsMainInfoViewModel? { didSet { updateFromViewModel() } } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) setupViews() } // MARK: - View setup private func setupViews() { contentView.addSubview(detailsLabel) contentView.addSubview(stackContainer) let views = [ "detailsLabel": detailsLabel, "stackContainer": stackContainer ] as [String: Any] let metrics = [ "topMargin": 20, "bottomMargin": 20, "leftMargin": 16, "rightMargin": 16 ] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftMargin)-[detailsLabel]-(rightMargin)-|", options: [], metrics: metrics, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftMargin)-[stackContainer]-(rightMargin)-|", options: [], metrics: metrics, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[detailsLabel]-[stackContainer]-(bottomMargin)-|", options: [], metrics: metrics, views: views) NSLayoutConstraint.activate(constraints) } private func setupStackContainer() -> UIStackView { let stackContainer = UIStackView() stackContainer.addArrangedSubview(spacerView) stackContainer.translatesAutoresizingMaskIntoConstraints = false stackContainer.distribution = .fill stackContainer.axis = .horizontal stackContainer.spacing = 24 stackContainer.isUserInteractionEnabled = true return stackContainer } private func setupSpacerView() -> UIView { let spacerView = UIView() spacerView.translatesAutoresizingMaskIntoConstraints = false spacerView.backgroundColor = UIColor.clear return spacerView } private func setupTwitterButton() -> MDCButton { let twitterButton = MDCFlatButton() twitterButton.isUppercaseTitle = false twitterButton.translatesAutoresizingMaskIntoConstraints = false twitterButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) twitterButton.addTarget(self, action: #selector(twitterTapped), for: .touchUpInside) twitterButton.setImage(UIImage(named: "ic_twitter"), for: .normal) twitterButton.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal) return twitterButton } @objc func twitterTapped() { viewModel?.twitterTapped() } private func setupDetailsLabel() -> UILabel { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .body1) label.enableAdjustFontForContentSizeCategory() label.textColor = MDCPalette.grey.tint800 label.numberOfLines = 0 return label } // MARK: - Model handling private func updateFromViewModel() { if let viewModel = viewModel { detailsLabel.text = viewModel.bio detailsLabel.setLineHeightMultiple(1.4) if viewModel.twitterURL != nil { stackContainer.insertArrangedSubview(twitterButton, at: 0) } // make cell tappable for the twitter and plus url buttons isUserInteractionEnabled = true setNeedsLayout() layoutIfNeeded() invalidateIntrinsicContentSize() } } }
apache-2.0
9a6bc211ccce6ab0f8ea4707d61d8e54
31.979167
122
0.674037
5.27081
false
false
false
false
srxboys/RXSwiftExtention
Pods/SwifterSwift/Source/Extensions/DateExtensions.swift
1
16168
// // DateExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import Foundation public extension Date { /// SwifterSwift: Day name format. /// /// - threeLetters: 3 letter day abbreviation of day name. /// - oneLetter: 1 letter day abbreviation of day name. /// - full: Full day name. public enum DayNameStyle { case threeLetters case oneLetter case full } /// SwifterSwift: Month name format. /// /// - threeLetters: 3 letter month abbreviation of month name. /// - oneLetter: 1 letter month abbreviation of month name. /// - full: Full month name. public enum MonthNameStyle { case threeLetters case oneLetter case full } } // MARK: - Properties public extension Date { /// SwifterSwift: User’s current calendar. public var calendar: Calendar { return Calendar.current } /// SwifterSwift: Era. public var era: Int { return Calendar.current.component(.era, from: self) } /// SwifterSwift: Year. public var year: Int { get { return Calendar.current.component(.year, from: self) } set { if let date = Calendar.current.date(bySetting: .year, value: newValue, of: self) { self = date } } } /// SwifterSwift: Quarter. public var quarter: Int { return Calendar.current.component(.quarter, from: self) } /// SwifterSwift: Month. public var month: Int { get { return Calendar.current.component(.month, from: self) } set { if let date = Calendar.current.date(bySetting: .month, value: newValue, of: self) { self = date } } } /// SwifterSwift: Week of year. public var weekOfYear: Int { return Calendar.current.component(.weekOfYear, from: self) } /// SwifterSwift: Week of month. public var weekOfMonth: Int { return Calendar.current.component(.weekOfMonth, from: self) } /// SwifterSwift: Weekday. public var weekday: Int { get { return Calendar.current.component(.weekday, from: self) } set { if let date = Calendar.current.date(bySetting: .weekday, value: newValue, of: self) { self = date } } } /// SwifterSwift: Day. public var day: Int { get { return Calendar.current.component(.day, from: self) } set { if let date = Calendar.current.date(bySetting: .day, value: newValue, of: self) { self = date } } } /// SwifterSwift: Hour. public var hour: Int { get { return Calendar.current.component(.hour, from: self) } set { if let date = Calendar.current.date(bySetting: .hour, value: newValue, of: self) { self = date } } } /// SwifterSwift: Minutes. public var minute: Int { get { return Calendar.current.component(.minute, from: self) } set { if let date = Calendar.current.date(bySetting: .minute, value: newValue, of: self) { self = date } } } /// SwifterSwift: Seconds. public var second: Int { get { return Calendar.current.component(.second, from: self) } set { if let date = Calendar.current.date(bySetting: .second, value: newValue, of: self) { self = date } } } /// SwifterSwift: Nanoseconds. public var nanosecond: Int { get { return Calendar.current.component(.nanosecond, from: self) } set { if let date = Calendar.current.date(bySetting: .nanosecond, value: newValue, of: self) { self = date } } } /// SwifterSwift: Milliseconds. public var millisecond: Int { get { return Calendar.current.component(.nanosecond, from: self) / 1000000 } set { let ns = newValue * 1000000 if let date = Calendar.current.date(bySetting: .nanosecond, value: ns, of: self) { self = date } } } /// SwifterSwift: Check if date is in future. public var isInFuture: Bool { return self > Date() } /// SwifterSwift: Check if date is in past. public var isInPast: Bool { return self < Date() } /// SwifterSwift: Check if date is in today. public var isInToday: Bool { return Calendar.current.isDateInToday(self) } /// SwifterSwift: Check if date is within yesterday. public var isInYesterday: Bool { return Calendar.current.isDateInYesterday(self) } /// SwifterSwift: Check if date is within tomorrow. public var isInTomorrow: Bool { return Calendar.current.isDateInTomorrow(self) } /// SwifterSwift: Check if date is within a weekend period. public var isInWeekend: Bool { return Calendar.current.isDateInWeekend(self) } /// SwifterSwift: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSS) from date. public var iso8601String: String { // https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" return dateFormatter.string(from: self).appending("Z") } /// SwifterSwift: Nearest five minutes to date. public var nearestFiveMinutes: Date { var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self) let min = components.minute! components.minute! = min % 5 < 3 ? min - min % 5 : min + 5 - (min % 5) components.second = 0 return Calendar.current.date(from: components)! } /// SwifterSwift: Nearest ten minutes to date. public var nearestTenMinutes: Date { var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self) let min = components.minute! components.minute? = min % 10 < 6 ? min - min % 10 : min + 10 - (min % 10) components.second = 0 return Calendar.current.date(from: components)! } /// SwifterSwift: Nearest quarter hour to date. public var nearestQuarterHour: Date { var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self) let min = components.minute! components.minute! = min % 15 < 8 ? min - min % 15 : min + 15 - (min % 15) components.second = 0 return Calendar.current.date(from: components)! } /// SwifterSwift: Nearest half hour to date. public var nearestHalfHour: Date { var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self) let min = components.minute! components.minute! = min % 30 < 15 ? min - min % 30 : min + 30 - (min % 30) components.second = 0 return Calendar.current.date(from: components)! } /// SwifterSwift: Nearest hour to date. public var nearestHour: Date { if minute >= 30 { return beginning(of: .hour)!.adding(.hour, value: 1) } return beginning(of: .hour)! } /// SwifterSwift: Time zone used by system. public var timeZone: TimeZone { return Calendar.current.timeZone } /// SwifterSwift: UNIX timestamp from date. public var unixTimestamp: Double { return timeIntervalSince1970 } } // MARK: - Methods public extension Date { /// SwifterSwift: Date by adding multiples of calendar component. /// /// - Parameters: /// - component: component type. /// - value: multiples of components to add. /// - Returns: original date + multiples of component added. public func adding(_ component: Calendar.Component, value: Int) -> Date { return Calendar.current.date(byAdding: component, value: value, to: self)! } /// SwifterSwift: Add calendar component to date. /// /// - Parameters: /// - component: component type. /// - value: multiples of compnenet to add. public mutating func add(_ component: Calendar.Component, value: Int) { self = adding(component, value: value) } /// SwifterSwift: Date by changing value of calendar component. /// /// - Parameters: /// - component: component type. /// - value: new value of compnenet to change. /// - Returns: original date after changing given component to given value. public func changing(_ component: Calendar.Component, value: Int) -> Date? { return Calendar.current.date(bySetting: component, value: value, of: self) } /// SwifterSwift: Data at the beginning of calendar component. /// /// - Parameter component: calendar component to get date at the beginning of. /// - Returns: date at the beginning of calendar component (if applicable). public func beginning(of component: Calendar.Component) -> Date? { switch component { case .second: return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)) case .minute: return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)) case .hour: return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day, .hour], from: self)) case .day: return Calendar.current.startOfDay(for: self) case .weekOfYear, .weekOfMonth: return Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) case .month: return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self)) case .year: return Calendar.current.date(from: Calendar.current.dateComponents([.year], from: self)) default: return nil } } /// SwifterSwift: Date at the end of calendar component. /// /// - Parameter component: calendar component to get date at the end of. /// - Returns: date at the end of calendar component (if applicable). public func end(of component: Calendar.Component) -> Date? { switch component { case .second: var date = adding(.second, value: 1) date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date))! date.add(.second, value: -1) return date case .minute: var date = adding(.minute, value: 1) let after = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date))! date = after.adding(.second, value: -1) return date case .hour: var date = adding(.hour, value: 1) let after = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day, .hour], from: date))! date = after.adding(.second, value: -1) return date case .day: var date = adding(.day, value: 1) date = Calendar.current.startOfDay(for: date) date.add(.second, value: -1) return date case .weekOfYear, .weekOfMonth: var date = self let beginningOfWeek = Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date))! date = beginningOfWeek.adding(.day, value: 7).adding(.second, value: -1) return date case .month: var date = adding(.month, value: 1) let after = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: date))! date = after.adding(.second, value: -1) return date case .year: var date = adding(.year, value: 1) let after = Calendar.current.date(from: Calendar.current.dateComponents([.year], from: date))! date = after.adding(.second, value: -1) return date default: return nil } } /// SwifterSwift: Date string from date. /// /// - Parameter style: DateFormatter style (default is .medium). /// - Returns: date string. public func dateString(ofStyle style: DateFormatter.Style = .medium) -> String { let dateFormatter = DateFormatter() dateFormatter.timeStyle = .none dateFormatter.dateStyle = style return dateFormatter.string(from: self) } /// SwifterSwift: Date and time string from date. /// /// - Parameter style: DateFormatter style (default is .medium). /// - Returns: date and time string. public func dateTimeString(ofStyle style: DateFormatter.Style = .medium) -> String { let dateFormatter = DateFormatter() dateFormatter.timeStyle = style dateFormatter.dateStyle = style return dateFormatter.string(from: self) } /// SwifterSwift: Check if date is in current given calendar component. /// /// - Parameter component: calendar component to check. /// - Returns: true if date is in current given calendar component. public func isInCurrent(_ component: Calendar.Component) -> Bool { return calendar.isDate(self, equalTo: Date(), toGranularity: component) } /// SwifterSwift: Time string from date /// /// - Parameter style: DateFormatter style (default is .medium). /// - Returns: time string. public func timeString(ofStyle style: DateFormatter.Style = .medium) -> String { let dateFormatter = DateFormatter() dateFormatter.timeStyle = style dateFormatter.dateStyle = .none return dateFormatter.string(from: self) } /// SwifterSwift: Day name from date. /// /// - Parameter Style: style of day name (default is DayNameStyle.full). /// - Returns: day name string (example: W, Wed, Wednesday). public func dayName(ofStyle style: DayNameStyle = .full) -> String { // http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/ let dateFormatter = DateFormatter() var format: String { switch style { case .oneLetter: return "EEEEE" case .threeLetters: return "EEE" case .full: return "EEEE" } } dateFormatter.setLocalizedDateFormatFromTemplate(format) return dateFormatter.string(from: self) } /// SwifterSwift: Month name from date. /// /// - Parameter Style: style of month name (default is MonthNameStyle.full). /// - Returns: month name string (example: D, Dec, December). public func monthName(ofStyle style: MonthNameStyle = .full) -> String { // http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/ let dateFormatter = DateFormatter() var format: String { switch style { case .oneLetter: return "MMMMM" case .threeLetters: return "MMM" case .full: return "MMMM" } } dateFormatter.setLocalizedDateFormatFromTemplate(format) return dateFormatter.string(from: self) } } // MARK: - Initializers public extension Date { /// SwifterSwift: Create a new date form calendar components. /// /// - Parameters: /// - calendar: Calendar (default is current). /// - timeZone: TimeZone (default is current). /// - era: Era (default is current era). /// - year: Year (default is current year). /// - month: Month (default is current month). /// - day: Day (default is today). /// - hour: Hour (default is current hour). /// - minute: Minute (default is current minute). /// - second: Second (default is current second). /// - nanosecond: Nanosecond (default is current nanosecond). public init?( calendar: Calendar? = Calendar.current, timeZone: TimeZone? = TimeZone.current, era: Int? = Date().era, year: Int? = Date().year, month: Int? = Date().month, day: Int? = Date().day, hour: Int? = Date().hour, minute: Int? = Date().minute, second: Int? = Date().second, nanosecond: Int? = Date().nanosecond) { var components = DateComponents() components.calendar = calendar components.timeZone = timeZone components.era = era components.year = year components.month = month components.day = day components.hour = hour components.minute = minute components.second = second components.nanosecond = nanosecond if let date = calendar?.date(from: components) { self = date } else { return nil } } /// SwifterSwift: Create date object from ISO8601 string. /// /// - Parameter iso8601String: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). public init?(iso8601String: String) { // https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone.current dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" if let date = dateFormatter.date(from: iso8601String) { self = date } else { return nil } } /// SwifterSwift: Create new date object from UNIX timestamp. /// /// - Parameter unixTimestamp: UNIX timestamp. public init(unixTimestamp: Double) { self.init(timeIntervalSince1970: unixTimestamp) } }
mit
7a4a72a8e513cc93df35c4c6e476fb9a
27.91771
104
0.680916
3.504987
false
false
false
false
diejmon/KanbanizeAPI
Sources/LogTime.swift
1
2245
import Foundation public extension Client.RequestBuilder { public func logTime(_ loggedTime: LoggedTime, taskID: TaskID, description: Description? = nil) throws -> URLRequest { guard let credentials = self.credentials else { throw Client.Error.notLoggedIn } let request = URLRequest.create(subdomain: subdomain, credentials: credentials, function: .logTime, params: [loggedTime, taskID]) return request } } public extension Client { public func logTime(_ loggedTime: LoggedTime, taskID: TaskID, description: Description? = nil, completion: @escaping (Result<LogTimeResult, ClientError>) -> Void) throws { let request = try requestBuilder().logTime(loggedTime, taskID: taskID, description: description) execute(request, completion: completion) } public struct LogTimeResult { public let id: String public let taskID: TaskID public let author: String public let details: String public let loggedTime: LoggedTime public let isSubTask: Bool public let title: String public let comment: String public let originData: Date } } extension Client.LogTimeResult: APIResult { public init?(jsonObject: AnyObject) { guard let json = jsonObject as? Dictionary<String, AnyObject> else { return nil } guard let id = json["id"] as? String, let taskID = json["taskid"] as? String, let author = json["author"] as? String, let details = json["details"] as? String, let loggedTime = json["loggedtime"] as? Double, let isSubTask = json["issubtask"] as? Bool, let title = json["title"] as? String, let comment = json["comment"] as? String//, // originData = json["origindate"] as? String else { return nil } self.id = id self.taskID = TaskID(taskID) self.author = author self.details = details self.loggedTime = LoggedTime(hours: loggedTime) self.isSubTask = isSubTask self.title = title self.comment = comment self.originData = Date()//TODO: parse date } }
mit
6f8e8f71611a7f371bef4903b2bf3a7b
32.014706
100
0.622272
4.517103
false
false
false
false
andela-jejezie/FlutterwavePaymentManager
Rave/Rave/FWHelperAndConstant/FWConstant.swift
1
9163
// // Constant.swift // flutterwave // // Created by Johnson Ejezie on 09/12/2016. // Copyright © 2016 johnsonejezie. All rights reserved. // import Foundation import UIKit internal struct FWConstants { internal struct Text { static let AccountNumberTextFieldPlaceholder = "Account Number" static let CardNumberTextFieldPlaceholder = "Card Number" static let ExpiryDateTextFieldPlaceholder = "MM/YY" static let CVVTextFieldPlaceholder = "CVV" static let SegmentControlFirstIndexText = "CARD" static let SegmentControlSecondIndexText = "ACCOUNT" static let UserTokenTextFieldPlaceholder = "TOKEN" } internal struct ImageNamed { static let CardBlack = "generic-card" static let Cancel = "cancel" static let BankWhite = "bankWhite" static let BankBlack = "bankBlack" static let DropDown = "dropdown" static let Visa = "visa-card" static let MasterCard = "mastercard" } internal struct Color { static let BorderColor = UIColor.lightGray static let SegmentControlTintColor = UIColor(red: 55/255.0, green: 46/255.0, blue: 76/255.0, alpha: 1) static let flutterGreenColor = UIColor(red: 22/255.0, green: 156/255.0, blue: 129/255.0, alpha: 1) static let ErrorColor = UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 1) } static let CountryCode = Locale.current.regionCode static let Ipify = "https://api.ipify.org?format=json" static let PayEndPoint = "http://flw-pms-dev.eu-west-1.elasticbeanstalk.com/flwv3-pug/getpaidx/api/charge" static let BaseURL = "http://flw-pms-dev.eu-west-1.elasticbeanstalk.com/" static let ValidateAccountCharge = "http://flw-pms-dev.eu-west-1.elasticbeanstalk.com/flwv3-pug/getpaidx/api/validate" internal static let otpOptions:[String] = ["Select OTP option","Hardware Token", "USSD"] internal static var banks = [Bank]() internal static var listOfBankNames = [String]() static let countries = [ "NG": "Nigeria", "AF": "Afghanistan", "AX": "Åland Islands", "AL": "Albania", "DZ": "Algeria", "AS": "American Samoa", "AD": "Andorra", "AO": "Angola", "AI": "Anguilla", "AQ": "Antarctica", "AG": "Antigua and Barbuda", "AR": "Argentina", "AM": "Armenia", "AW": "Aruba", "AU": "Australia", "AT": "Austria", "AZ": "Azerbaijan", "BS": "Bahamas", "BH": "Bahrain", "BD": "Bangladesh", "BB": "Barbados", "BY": "Belarus", "BE": "Belgium", "BZ": "Belize", "BJ": "Benin", "BM": "Bermuda", "BT": "Bhutan", "BO": "Bolivia", "BA": "Bosnia and Herzegovina", "BW": "Botswana", "BV": "Bouvet Island", "BR": "Brazil", "IO": "British Indian Ocean Territory", "BN": "Brunei Darussalam", "BG": "Bulgaria", "BF": "Burkina Faso", "BI": "Burundi", "KH": "Cambodia", "CM": "Cameroon", "CA": "Canada", "CV": "Cape Verde", "KY": "Cayman Islands", "CF": "Central African Republic", "TD": "Chad", "CL": "Chile", "CN": "China", "CX": "Christmas Island", "CC": "Cocos (Keeling) Islands", "CO": "Colombia", "KM": "Comoros", "CG": "Congo", "CD": "Congo, The Democratic Republic of the", "CK": "Cook Islands", "CR": "Costa Rica", "CI": "Cote D'Ivoire", "HR": "Croatia", "CU": "Cuba", "CY": "Cyprus", "CZ": "Czech Republic", "DK": "Denmark", "DJ": "Djibouti", "DM": "Dominica", "DO": "Dominican Republic", "EC": "Ecuador", "EG": "Egypt", "SV": "El Salvador", "GQ": "Equatorial Guinea", "ER": "Eritrea", "EE": "Estonia", "ET": "Ethiopia", "FK": "Falkland Islands (Malvinas)", "FO": "Faroe Islands", "FJ": "Fiji", "FI": "Finland", "FR": "France", "GF": "French Guiana", "PF": "French Polynesia", "TF": "French Southern Territories", "GA": "Gabon", "GM": "Gambia", "GE": "Georgia", "DE": "Germany", "GH": "Ghana", "GI": "Gibraltar", "GR": "Greece", "GL": "Greenland", "GD": "Grenada", "GP": "Guadeloupe", "GU": "Guam", "GT": "Guatemala", "GG": "Guernsey", "GN": "Guinea", "GW": "Guinea-Bissau", "GY": "Guyana", "HT": "Haiti", "HM": "Heard Island and Mcdonald Islands", "VA": "Holy See (Vatican City State)", "HN": "Honduras", "HK": "Hong Kong", "HU": "Hungary", "IS": "Iceland", "IN": "India", "ID": "Indonesia", "IR": "Iran, Islamic Republic Of", "IQ": "Iraq", "IE": "Ireland", "IM": "Isle of Man", "IL": "Israel", "IT": "Italy", "JM": "Jamaica", "JP": "Japan", "JE": "Jersey", "JO": "Jordan", "KZ": "Kazakhstan", "KE": "Kenya", "KI": "Kiribati", "KP": "Democratic People's Republic of Korea", "KR": "Korea, Republic of", "XK": "Kosovo", "KW": "Kuwait", "KG": "Kyrgyzstan", "LA": "Lao People's Democratic Republic", "LV": "Latvia", "LB": "Lebanon", "LS": "Lesotho", "LR": "Liberia", "LY": "Libyan Arab Jamahiriya", "LI": "Liechtenstein", "LT": "Lithuania", "LU": "Luxembourg", "MO": "Macao", "MK": "Macedonia, The Former Yugoslav Republic of", "MG": "Madagascar", "MW": "Malawi", "MY": "Malaysia", "MV": "Maldives", "ML": "Mali", "MT": "Malta", "MH": "Marshall Islands", "MQ": "Martinique", "MR": "Mauritania", "MU": "Mauritius", "YT": "Mayotte", "MX": "Mexico", "FM": "Micronesia, Federated States of", "MD": "Moldova, Republic of", "MC": "Monaco", "MN": "Mongolia", "ME": "Montenegro", "MS": "Montserrat", "MA": "Morocco", "MZ": "Mozambique", "MM": "Myanmar", "NA": "Namibia", "NR": "Nauru", "NP": "Nepal", "NL": "Netherlands", "AN": "Netherlands Antilles", "NC": "New Caledonia", "NZ": "New Zealand", "NI": "Nicaragua", "NE": "Niger", "NU": "Niue", "NF": "Norfolk Island", "MP": "Northern Mariana Islands", "NO": "Norway", "OM": "Oman", "PK": "Pakistan", "PW": "Palau", "PS": "Palestinian Territory, Occupied", "PA": "Panama", "PG": "Papua New Guinea", "PY": "Paraguay", "PE": "Peru", "PH": "Philippines", "PN": "Pitcairn", "PL": "Poland", "PT": "Portugal", "PR": "Puerto Rico", "QA": "Qatar", "RE": "Reunion", "RO": "Romania", "RU": "Russian Federation", "RW": "Rwanda", "SH": "Saint Helena", "KN": "Saint Kitts and Nevis", "LC": "Saint Lucia", "PM": "Saint Pierre and Miquelon", "VC": "Saint Vincent and the Grenadines", "WS": "Samoa", "SM": "San Marino", "ST": "Sao Tome and Principe", "SA": "Saudi Arabia", "SN": "Senegal", "RS": "Serbia", "SC": "Seychelles", "SL": "Sierra Leone", "SG": "Singapore", "SK": "Slovakia", "SI": "Slovenia", "SB": "Solomon Islands", "SO": "Somalia", "ZA": "South Africa", "GS": "South Georgia and the South Sandwich Islands", "ES": "Spain", "LK": "Sri Lanka", "SD": "Sudan", "SR": "Suriname", "SJ": "Svalbard and Jan Mayen", "SZ": "Swaziland", "SE": "Sweden", "CH": "Switzerland", "SY": "Syrian Arab Republic", "TW": "Taiwan", "TJ": "Tajikistan", "TZ": "Tanzania, United Republic of", "TH": "Thailand", "TL": "Timor-Leste", "TG": "Togo", "TK": "Tokelau", "TO": "Tonga", "TT": "Trinidad and Tobago", "TN": "Tunisia", "TR": "Turkey", "TM": "Turkmenistan", "TC": "Turks and Caicos Islands", "TV": "Tuvalu", "UG": "Uganda", "UA": "Ukraine", "AE": "United Arab Emirates", "GB": "United Kingdom", "US": "United States", "UM": "United States Minor Outlying Islands", "UY": "Uruguay", "UZ": "Uzbekistan", "VU": "Vanuatu", "VE": "Venezuela", "VN": "Viet Nam", "VG": "Virgin Islands, British", "VI": "Virgin Islands, U.S.", "WF": "Wallis and Futuna", "EH": "Western Sahara", "YE": "Yemen", "ZM": "Zambia", "ZW": "Zimbabwe" ] }
mit
9c2a580b721cbcb492721c18b18f3054
29.638796
122
0.480515
3.257824
false
false
false
false
joerocca/GitHawk
Classes/Issues/Labeled/IssueLabeledSectionController.swift
1
1176
// // IssueLabeledSectionController.swift // Freetime // // Created by Ryan Nystrom on 6/6/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueLabeledSectionController: ListGenericSectionController<IssueLabeledModel> { private let issueModel: IssueDetailsModel init(issueModel: IssueDetailsModel) { self.issueModel = issueModel super.init() } override func sizeForItem(at index: Int) -> CGSize { guard let width = collectionContext?.containerSize.width else { fatalError("Collection context must be set") } return CGSize(width: width, height: object?.attributedString.textViewSize(width).height ?? 0) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: IssueLabeledCell.self, for: self, at: index) as? IssueLabeledCell, let object = self.object else { fatalError("Missing collection context, cell incorrect type, or object missing") } cell.configure(object) cell.delegate = viewController return cell } }
mit
0c5a97e97e1f1ded7c88af0041690b98
32.571429
134
0.702128
4.718876
false
false
false
false
icharny/CommonUtils
CommonUtils/DictionaryExtensions.swift
1
1418
public extension Dictionary { func deepMap<nK: Hashable, nV>(keyMap: ((Key) -> nK)? = nil, valueMap: ((Value) -> nV)? = nil) -> [nK: nV] { var newDict = [nK: nV]() forEach { k, v in let newKey: nK = keyMap?(k) ?? (k as! nK) let newValue: nV = valueMap?(v) ?? (v as! nV) newDict[newKey] = newValue } return newDict } func appending(newDict: [Key: Value]) -> [Key: Value] { var combinedDict = self newDict.forEach { k, v in combinedDict[k] = v } return combinedDict } func filterToDictionary(includeElement: (Dictionary.Iterator.Element) throws -> Bool) rethrows -> [Key: Value] { var ret = [Key: Value]() if let tuples = try? filter(includeElement) { tuples.forEach { k, v in ret[k] = v } } return ret } // NOTE: NOT COMMUTATIVE // i.e. dict1 + dict2 != dict2 + dict1 // specifically, for common keys, rhs will overwrite lhs static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] { var newDict: [Key: Value] = [:] lhs.forEach { newDict[$0.key] = $0.value } rhs.forEach { newDict[$0.key] = $0.value } return newDict } static func += (lhs: inout [Key: Value], rhs: [Key: Value]) { rhs.forEach { lhs[$0.key] = $0.value } } }
mit
a70456ce2d18e99620ae4eb271a14dac
29.826087
116
0.516925
3.545
false
false
false
false
4jchc/4jchc-BaiSiBuDeJie
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Tool/UIImage+Extension.swift
1
1860
// // UIImage+Extension.swift // 4jchc-BaiSiBuDeJie // // Created by 蒋进 on 16/3/3. // Copyright © 2016年 蒋进. All rights reserved. // import Foundation import UIKit extension UIImage { //MARK: 根据网络图片的地址下载图片并且返回圆形的剪裁图片 /// 根据网络图片的地址下载图片并且返回圆形的剪裁图片 class func circleImageWithImageURL(image_url:String)->UIImage?{ //下载网络图片 let data = NSData(contentsOfURL: NSURL(string: image_url)!) let olderImage = UIImage(data: data!) //开启图片上下文 let contextW = olderImage?.size.width let contextH = olderImage?.size.height UIGraphicsBeginImageContextWithOptions(CGSizeMake(contextW!,contextH! ), false, 0.0); //画小圆 let ctx=UIGraphicsGetCurrentContext() CGContextAddEllipseInRect(ctx, CGRect(x: 0, y: 0, width: contextW!, height: contextH!)) CGContextClip(ctx) olderImage?.drawInRect(CGRect(x: 0, y: 0, width: contextW!, height: contextH!)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func circleImage()->UIImage{ // NO代表透明 UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0); // 获得上下文 let ctx = UIGraphicsGetCurrentContext() // 添加一个圆 let rect:CGRect = CGRectMake(0, 0, self.size.width, self.size.height); CGContextAddEllipseInRect(ctx, rect); // 裁剪 CGContextClip(ctx); // 将图片画上去 self.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage; } }
apache-2.0
f14a8b8addbae0178859d64e99d31d8f
27.913793
95
0.632081
4.367188
false
false
false
false
yoonapps/QPXExpressWrapper
QPXExpressWrapper/Classes/TripsDataTax.swift
1
734
// // TripsDataTax.swift // Flights // // Created by Kyle Yoon on 3/5/16. // Copyright © 2016 Kyle Yoon. All rights reserved. // import Foundation import Gloss public struct TripsDataTax: Decodable { public let kind: String? public let code: String? public let name: String? public init?(json: JSON) { guard let kind: String = "kind" <~~ json else { return nil } self.kind = kind self.code = "code" <~~ json self.name = "name" <~~ json } } extension TripsDataTax: Equatable {} public func ==(lhs: TripsDataTax, rhs: TripsDataTax) -> Bool { return lhs.kind == rhs.kind && lhs.code == rhs.code && lhs.name == rhs.name }
mit
89df23f2201b7bf6db290eccf3b7e753
19.942857
62
0.579809
3.610837
false
false
false
false
ViewModelKit/ViewModelKit
Example/Example/SimpleViewController.swift
1
1097
// // SimpleViewController.swift // ViewModelKit // // Created by Tongtong Xu on 16/2/21. // Copyright © 2016年 Tongtong Xu. All rights reserved. // import Foundation import UIKit import ViewModelKit class SimpleViewController: BaseViewController, BaseControllerTypeAddition { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var errorMessageLabel: UILabel! typealias T = SimpleViewModel override func viewDidLoad() { super.viewDidLoad() titleLabel.text = viewModel.nameTitle NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { [weak self] in guard let textField = $0.object as? UITextField where textField == self?.nameTextField else { return } self?.viewModel.name = textField.text ?? "" }) viewModel.validClosure = { [weak self] in self?.errorMessageLabel.text = $0 } } }
mit
ad6fbb553ad16b8de32e340d54169fce
30.257143
181
0.671846
5.064815
false
false
false
false
steelwheels/KiwiScript
KiwiShell/Test/Shell/UTScript.swift
1
1496
/** * @file UTScript.swift * @brief Test function for KHScriptThread class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiShell import KiwiLibrary import KiwiEngine import CoconutData import CoconutShell import JavaScriptCore import Foundation public func UTScript(input inhdl: FileHandle, output outhdl: FileHandle, error errhdl: FileHandle, console cons: CNConsole) -> Bool { var result = true let instrm : CNFileStream = .fileHandle(inhdl) let outstrm : CNFileStream = .fileHandle(outhdl) let errstrm : CNFileStream = .fileHandle(errhdl) let script: String = "for(let i=0; i<1000000 ; i ++) { sleep(0.1) ; } " let procmgr = CNProcessManager() let env = CNEnvironment() let config = KHConfig(applicationType: .terminal, hasMainFunction: false, doStrict: true, logLevel: .warning) let thread = KHScriptThreadObject(sourceFile: .script(script), processManager: procmgr, input: instrm, output: outstrm, error: errstrm, externalCompiler: nil, environment: env, config: config) /* Execute the thread */ thread.start(argument: .nullValue) /* Check status */ Thread.sleep(forTimeInterval: 1.0) if !thread.isRunning { cons.print(string: "Thread is NOT running\n") result = false } /* Terminate */ thread.terminate() /* Check status */ Thread.sleep(forTimeInterval: 0.5) if thread.isRunning { cons.print(string: "Thread is still running\n") result = false } cons.print(string: "UTScript ... done\n") return result }
lgpl-2.1
4372406cedbcabda224a5647213ac3aa
26.703704
196
0.725267
3.4
false
true
false
false
laszlokorte/reform-swift
ReformStage/ReformStage/RuntimeStageCollector.swift
1
4564
// // RuntimeStageCollector.swift // ReformStage // // Created by Laszlo Korte on 17.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath import ReformCore final public class StageCollector<A:Analyzer> : RuntimeListener { private let stage : Stage private let analyzer : A private let focusFilter : (Evaluatable) -> Bool private var collected : Bool = false private let buffer = StageBuffer() public init(stage: Stage, analyzer: A, focusFilter: @escaping (Evaluatable) -> Bool) { self.stage = stage self.analyzer = analyzer self.focusFilter = focusFilter } public func runtimeBeginEvaluation<R:Runtime>(_ runtime: R, withSize size: (Double, Double)) { collected = false buffer.clear() buffer.size = Vec2d(x: Double(size.0), y: Double(size.1)) } public func runtimeFinishEvaluation<R:Runtime>(_ runtime: R) { buffer.flush(stage) } public func runtime<R:Runtime>(_ runtime: R, didEval instruction: Evaluatable) { guard !collected else { return } guard focusFilter(instruction) else { return } defer { collected = true } for id in runtime.getForms() { guard let entity = entityForRuntimeForm(analyzer, runtime: runtime, formId: id) else { continue } buffer.entities.append(entity) guard let drawable = runtime.get(id) as? Drawable, drawable.drawingMode == .draw else { continue } guard let shape = drawable.getShapeFor(runtime) else { continue } let idShape = IdentifiedShape(id: id, shape: shape) buffer.currentShapes.append(idShape) } } public func runtime<R:Runtime>(_ runtime: R, exitScopeWithForms forms: [FormIdentifier]) { for id in forms { guard let form = runtime.get(id) as? Drawable, form.drawingMode == .draw else { continue } guard let shape = form.getShapeFor(runtime) else { continue } let idShape = IdentifiedShape(id: id, shape: shape) if !collected { buffer.currentShapes.append(idShape) } buffer.finalShapes.append(idShape) } } public func runtime<R:Runtime>(_ runtime: R, triggeredError: RuntimeError, on instruction: Evaluatable) { guard !collected else { return } guard focusFilter(instruction) else { return } buffer.error = triggeredError } public var recalcIntersections : Bool { set(b) { buffer.recalcIntersections = b } get { return buffer.recalcIntersections } } } private class StageBuffer { var recalcIntersections = true var size : Vec2d = Vec2d() var entities : [Entity] = [] var error : RuntimeError? var currentShapes : [IdentifiedShape] = [] var finalShapes : [IdentifiedShape] = [] func clear() { entities.removeAll(keepingCapacity: true) currentShapes.removeAll(keepingCapacity: true) finalShapes.removeAll(keepingCapacity: true) size = Vec2d() error = nil } func flush(_ stage: Stage) { let recalcIntersections = self.recalcIntersections DispatchQueue.main.sync { [unowned self, stage] in stage.size = self.size stage.entities = self.entities.lazy.reversed() stage.currentShapes = self.currentShapes stage.finalShapes = self.finalShapes stage.error = self.error if recalcIntersections { stage.intersections = intersectionsOf(self.entities) self.recalcIntersections = false } } } } func intersectionsOf(_ entities: [Entity]) -> [IntersectionSnapPoint] { var result = [IntersectionSnapPoint]() for (ai, a) in entities.enumerated() { for (bi, b) in entities.enumerated() where bi>ai && a.id != b.id { for (index, pos) in intersect(segmentPath: a.outline, and: b.outline).enumerated() { result.append(IntersectionSnapPoint(position: pos, label: "Intersection", point: RuntimeIntersectionPoint(formA: a.id.runtimeId, formB: b.id.runtimeId, index: index))) } } } return result }
mit
c614e18179e1a6626697b5fb165f585a
29.624161
183
0.586675
4.553892
false
false
false
false
yshrkt/TinyCalendar
Sources/CalendarDate.swift
1
1515
// // CalendarDate.swift // TinyCalendar // // Created by Yoshihiro Kato on 2017/08/26. // // import Foundation public struct CalendarDate { public let year: Int public let month: Int public let day: Int public let weekday: Weekday public static func today() -> CalendarDate? { return CalendarDate(with: Date()) } public init(year: Int, month: Int, day: Int, weekday: Weekday) { self.year = year self.month = month self.day = day self.weekday = weekday } public init?(with date: Date) { let calendar = Calendar(identifier: .gregorian) let dateComponents = calendar.dateComponents([.year, .month, .day, .weekday], from: date) guard let year = dateComponents.year, let month = dateComponents.month, let day = dateComponents.day, let wd = dateComponents.weekday, let weekday = Weekday(rawValue: wd)else { return nil } self.year = year self.month = month self.day = day self.weekday = weekday } } extension CalendarDate: Equatable, Hashable { public static func == (lhs: CalendarDate, rhs: CalendarDate) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day && lhs.weekday == rhs.weekday } public var hashValue: Int { return "\(year)/\(month)/\(day) \(weekday.rawValue)".hashValue } }
mit
d3556db589b8954fe5d281059ba00785
26.053571
97
0.577558
4.267606
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Models/MenuItem.swift
1
1658
// // MenuItem.swift // breadwallet // // Created by Adrian Corscadden on 2017-04-01. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit struct MenuItem { enum Icon { static let scan = UIImage(named: "scan") static let wallet = UIImage(named: "wallet") static let preferences = UIImage(named: "prefs") static let security = UIImage(named: "security") static let support = UIImage(named: "support") static let rewards = UIImage(named: "Star") static let about = UIImage(named: "about") static let atmMap = UIImage(named: "placemark") static let export = UIImage(named: "Export") } var title: String var subTitle: String? let icon: UIImage? let accessoryText: (() -> String)? let callback: () -> Void let faqButton: UIButton? = nil var shouldShow: () -> Bool = { return true } init(title: String, subTitle: String? = nil, icon: UIImage? = nil, accessoryText: (() -> String)? = nil, callback: @escaping () -> Void) { self.title = title self.subTitle = subTitle self.icon = icon?.withRenderingMode(.alwaysTemplate) self.accessoryText = accessoryText self.callback = callback } init(title: String, icon: UIImage? = nil, subMenu: [MenuItem], rootNav: UINavigationController, faqButton: UIButton? = nil) { let subMenuVC = MenuViewController(items: subMenu, title: title, faqButton: faqButton) self.init(title: title, icon: icon, accessoryText: nil) { rootNav.pushViewController(subMenuVC, animated: true) } } }
mit
28b273dcc0d5f4281026b64ec46d4ee7
34.255319
142
0.62764
4.270619
false
false
false
false
dankogai/swift-genericmath
OSX.playground/Contents.swift
1
612
//: Playground - noun: a place where people can play (Int128(1)...Int128(32)).reduce(1,combine:*) Float128(1.0/3.0) Float128(0.0).isPowerOf2 Float128(0.5).isPowerOf2 Float128(1.0).isPowerOf2 Float128(1.5).isPowerOf2 Float128.infinity.isPowerOf2 Float128.NaN.isPowerOf2 UInt128.max.msbAt UInt64.max.msbAt (UInt64.max >> 1).msbAt UInt64(1).msbAt UInt64(0).msbAt UInt32.max.msbAt UInt16.max.msbAt UInt8.max.msbAt UInt.max.msbAt var m = Float128(2.0/3.0) * Float128(1.0/3.0) m.asDouble m._toBitPattern().toString(16) m = Float128(0.1)*Float128(0.1)*Float128(0.1) m = Float128(UInt64.max) m.asUInt64 == UInt64.max
mit
b1d679fe600d1f39eda3f37affe1e555
21.666667
52
0.74183
2.266667
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/other/custom/DZMHaloButton.swift
1
2740
// // DZMHaloButton.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/3/24. // Copyright © 2017年 DZM. All rights reserved. // import UIKit /* imageView 四周默认间距为 HJSpace_3 算宽高的时候记得加上 用于光晕范围*/ class DZMHaloButton: UIControl { /// imageView private(set) var imageView:UIImageView! /// 光晕颜色 private(set) var haloColor:UIColor! /// 默认图片 var nomalImage:UIImage? /// 选中图片 var selectImage:UIImage? /// 选中 override var isSelected: Bool { didSet{ if isSelected { if selectImage != nil { imageView.image = selectImage } }else{ if nomalImage != nil { imageView.image = nomalImage } } } } /// 初始化方法 init(_ frame: CGRect, haloColor:UIColor) { super.init(frame: frame) // 记录 self.haloColor = haloColor // 添加 addSubviews() // 开启光晕 openHalo(haloColor) } /// 通过正常的Size返回对应的按钮大小 class func HaloButtonSize(_ size:CGSize) ->CGSize { return CGSize(width: size.width + DZMSpace_5, height: size.height + DZMSpace_5) } /// 开启光晕 func openHalo(_ haloColor:UIColor?) { if haloColor != nil { self.haloColor = haloColor; // 开启按钮闪动 imageView.startPulse(with: haloColor, scaleFrom: 1.0, to: 1.2, frequency: 1.0, opacity: 0.5, animation: .regularPulsing) } } // 关闭光晕 func closeHalo() { imageView.stopPulse() } private func addSubviews() { // imageView imageView = UIImageView() imageView.backgroundColor = haloColor imageView.contentMode = .center addSubview(imageView) // 布局 setFrame() } private func setFrame() { // 布局 imageView.frame = CGRect(x: DZMSpace_4, y: DZMSpace_4, width: width - DZMSpace_5, height: height - DZMSpace_5) // 圆角 imageView.layer.cornerRadius = (width - DZMSpace_5) / 2 } override func layoutSubviews() { super.layoutSubviews() setFrame() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
d8c6d50aa1c38cbf1c13eff67c12bcbb
20.720339
132
0.48888
4.307563
false
false
false
false
swiftix/swift.old
test/SILPasses/let_propagation.swift
1
7551
// RUN: %target-swift-frontend -primary-file %s -disable-func-sig-opts -emit-sil -O | FileCheck %s // Check that LoadStoreOpts can handle "let" variables properly. // Such variables should be loaded only once and their loaded values can be reused. // This is safe, because once assigned, these variables cannot change their value. // Helper function, which models an external functions with unknown side-effects. // It is calle just to trigger flushing of all known stored in LoadStore optimizations. @inline(never) func action() { print("") } final public class A0 { let x: Int32 let y: Int32 init(_ x: Int32, _ y: Int32) { self.x = x self.y = y } @inline(never) func sum1() -> Int32 { // x and y should be loaded only once. let n = x + y action() let m = x - y action() let p = x - y + 1 return n + m + p } func sum2() -> Int32 { // x and y should be loaded only once. let n = x + y action() let m = x - y action() let p = x - y + 1 return n + m + p } } /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that counter computation is completely evaluated // at compile-time, because the value of a.x and a.y are known // from the initializer and propagated into their uses, because // we know that action() invocations do not affect their values. // // DISABLECHECK-LABEL: sil {{.*}}testAllocAndUseLet // DISABLECHECK: bb0 // DISABLECHECK-NOT: ref_element_addr // DISABLECHECK-NOT: struct_element_addr // DISABLECHECK-NOT: bb1 // DISABLECHECK: function_ref @_TF15let_propagation6actionFT_T_ // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: integer_literal $Builtin.Int32, 36 // DISABLECHECK-NEXT: struct $Int32 ({{.*}} : $Builtin.Int32) // DISABLECHECK-NEXT: return @inline(never) public func testAllocAndUseLet() -> Int32 { let a = A0(3, 1) var counter: Int32 // a.x and a.y should be loaded only once. counter = a.sum2() + a.sum2() counter += a.sum2() + a.sum2() return counter } */ /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that a.x and a.y are loaded only once and then reused. // DISABLECHECK-LABEL: sil {{.*}}testUseLet // DISABLECHECK: bb0 // DISABLECHECK: ref_element_addr // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK: ref_element_addr // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK-NOT: bb1 // DISABLECHECK-NOT: ref_element_addr // DISABLECHECK-NOT: struct_element_addr // DISABLECHECK-NOT: load // DISABLECHECK: return @inline(never) public func testUseLet(a:A0) -> Int32 { var counter: Int32 // a.x and a.y should be loaded only once. counter = a.sum2() + a.sum2() counter += a.sum2() + a.sum2() return counter } */ struct Goo { var x: Int32 var y: Int32 } struct Foo { var g: Goo } struct Bar { let f: Foo var h: Foo @inline(never) mutating func action() { } } @inline(never) func getVal() -> Int32 { return 9 } // Global let let gx: Int32 = getVal() let gy: Int32 = getVal() func sum3() -> Int32 { // gx and gy should be loaded only once. let n = gx + gy action() let m = gx - gy action() let p = gx - gy + 1 return n + m + p } /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that gx and gy are loaded only once and then reused. // DISABLECHECK-LABEL: sil {{.*}}testUseGlobalLet // DISABLECHECK: bb0 // DISABLECHECK: global_addr @_Tv15let_propagation2gyVs5Int32 // DISABLECHECK: global_addr @_Tv15let_propagation2gxVs5Int32 // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK-NOT: bb1 // DISABLECHECK-NOT: global_addr // DISABLECHECK-NOT: ref_element_addr // DISABLECHECK-NOT: struct_element_addr // DISABLECHECK-NOT: load // DISABLECHECK: return @inline(never) public func testUseGlobalLet() -> Int32 { var counter: Int32 = 0 // gx and gy should be loaded only once. counter = sum3() + sum3() + sum3() + sum3() return counter } */ struct A1 { let x: Int32 // Propagate the value of the initializer into all instructions // that use it, which in turn would allow for better constant // propagation. let y: Int32 = 100 init(v: Int32) { if v > 0 { x = 1 } else { x = -1 } } // CHECK-LABEL: sil hidden @_TFV15let_propagation2A12f1 // CHECK: bb0 // CHECK: struct_extract {{.*}}#A1.x // CHECK: struct_extract {{.*}}#Int32._value // CHECK-NOT: load // CHECK-NOT: struct_extract // CHECK-NOT: struct_element_addr // CHECK-NOT: ref_element_addr // CHECK-NOT: bb1 // CHECK: return func f1() -> Int32 { // x should be loaded only once. return x + x } // CHECK-LABEL: sil hidden @_TFV15let_propagation2A12f2 // CHECK: bb0 // CHECK: integer_literal $Builtin.Int32, 200 // CHECK-NEXT: struct $Int32 // CHECK-NEXT: return func f2() -> Int32 { // load y only once. return y + y } } class A2 { let x: B2 = B2() // CHECK-LABEL: sil hidden @_TFC15let_propagation2A22af // bb0 // CHECK: %[[X:[0-9]+]] = ref_element_addr {{.*}}A2.x // CHECK-NEXT: load %[[X]] // CHECK: ref_element_addr {{.*}}B2.i // CHECK: %[[XI:[0-9]+]] = struct_element_addr {{.*}}#Int32._value // CHECK-NEXT: load %[[XI]] // return func af() -> Int32 { // x and x.i should be loaded only once. return x.f() + x.f() } } final class B2 { var i: Int32 = 10 func f() -> Int32 { return i } } @inline(never) func oops() { } struct S { let elt : Int32 } // Check that we can handle reassignments to a variable // of struct type properly. // CHECK-LABEL: sil {{.*}}testStructWithLetElement // CHECK-NOT: function_ref @{{.*}}oops // CHECK: return public func testStructWithLetElement() -> Int32 { var someVar = S(elt: 12) let tmp1 = someVar.elt someVar = S(elt: 15) let tmp2 = someVar.elt // This check should get eliminated if (tmp2 == tmp1) { // If we get here, the compiler has propagated // the old value someVar.elt into tmp2, which // is wrong. oops() } return tmp1+tmp2 } public typealias Tuple3 = (Int32, Int32, Int32) final public class S3 { let x: Tuple3 var y: Tuple3 init(x: Tuple3, y:Tuple3) { self.x = x self.y = y } } /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that s.x.0 is loaded only once and then reused. // DISABLECHECK-LABEL: sil {{.*}}testLetTuple // DISABLECHECK: tuple_element_addr // DISABLECHECK: %[[X:[0-9]+]] = struct_element_addr // DISABLECHECK: load %[[X]] // DISABLECHECK-NOT: load %[[X]] // DISABLECHECK: return public func testLetTuple(s: S3) ->Int32 { var counter: Int32 = 0 counter += s.x.0 action() counter += s.x.0 action() counter += s.x.0 action() counter += s.x.0 action() return counter } */ // Check that s.x.0 is reloaded every time. // CHECK-LABEL: sil {{.*}}testVarTuple // CHECK: tuple_element_addr // CHECK: %[[X:[0-9]+]] = struct_element_addr // CHECK: load %[[X]] // CHECK: load %[[X]] // CHECK: load %[[X]] // CHECK: load %[[X]] // CHECK: return public func testVarTuple(s: S3) ->Int32 { var counter: Int32 = 0 counter += s.y.0 action() counter += s.y.0 action() counter += s.y.0 action() counter += s.y.0 action() return counter }
apache-2.0
55da1ef01a883d4696107be6b3b25941
21.607784
98
0.639253
3.085819
false
false
false
false
swiftgurmeet/LocuEx
LocuEx/LocuData.swift
1
3754
// // LocuData.swift // LocuEx // //The MIT License (MIT) // //Copyright (c) 2015 swiftgurmeet // //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 MapKit class LocuData { struct Settings { static let apiUrl = "https://api.locu.com/v2/venue/search/" } func request(location: CLLocationCoordinate2D, callback:(NSDictionary)->()) { var nsURL = NSURL(string: Settings.apiUrl) var request = NSMutableURLRequest(URL: nsURL!) var response: NSURLResponse? var session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") var locationRequest = [String:AnyObject]() locationRequest["$in_lat_lng_radius"] = [location.latitude,location.longitude,1000] var params = [ "fields":["name", "location", "contact"], "venue_queries": [ [ "location" : [ "geo": locationRequest ] , "categories" : [ "name":"Restaurants", // "str_id" : "chinese" ] ] ], "api_key":"" ] var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) let requestText = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding) let task = session.dataTaskWithRequest(request) { (data,response,error) in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode != 200 { println("response was not 200: \(response)") return } } if (error != nil) { println("error submitting request: \(error.localizedDescription)") return } dispatch_async(dispatch_get_main_queue()) { var error: NSError? if let jsonData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary { callback(jsonData) } else { println("No dictionary received") } } } task.resume() } }
mit
82c5588a9156d086668c7b571bc9eaec
38.515789
162
0.557272
5.370529
false
false
false
false
stefan-vainberg/SlidingImagePuzzle
SlidingImagePuzzle/SlidingImagePuzzle/PuzzleBoardView.swift
1
5014
// // PuzzleBoardView.swift // SlidingImagePuzzle // // Created by Stefan Vainberg on 11/8/14. // Copyright (c) 2014 Stefan. All rights reserved. // import Foundation import UIKit class PuzzleBoardView : UIView { // PUBLICS var boardGameSize:CGSize? var board:([[UIImageView]])? //PRIVATES private var internalImageView:UIImageView? private var puzzleGestureRecognizer:PuzzleGestureHandler? // INITS convenience init(initialImage:UIImage) { self.init(frame:CGRectZero) self.initializeView(initialImage) } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // GENERIC INITIALIZER func initializeView(image:UIImage) -> Void { // add the reference holder of pieces board = [] self.clipsToBounds = true self.layer.borderColor = UIColor.blackColor().CGColor self.layer.borderWidth = 1.0 internalImageView = UIImageView(image: image) self.setTranslatesAutoresizingMaskIntoConstraints(false) internalImageView!.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(internalImageView!) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0)) } func UpdateWithPuzzlePieces(pieces:[[UIImage]]) -> Void { let sampleImage = pieces[0][0] let totalHeight = CGFloat(pieces.count) * sampleImage.size.height let totalWidth = CGFloat(pieces[0].count) * sampleImage.size.width boardGameSize = CGSizeMake(totalWidth, totalHeight) self.removeConstraints(self.constraints()) self.backgroundColor = UIColor.blackColor() internalImageView!.removeFromSuperview() var currentRow = 0 var currentColumn = 0 var fullColumn:[UIImageView] = [] var imageTag = 0 for row in pieces { for image in row { let correspondingImageView = UIImageView(image: image) correspondingImageView.tag = imageTag correspondingImageView.frame = CGRectMake(CGFloat(currentColumn)*(image.size.width+1), CGFloat(currentRow)*(image.size.height+1), image.size.width, image.size.height) self.addSubview(correspondingImageView) fullColumn.append(correspondingImageView) currentColumn++ imageTag++ } board!.append(fullColumn) fullColumn = [] currentRow++ currentColumn = 0 } } func UpdateWithImage(image:UIImage) -> Void { internalImageView!.image = image } func BlackOutPiece(pieceLocation:(row:Int, column:Int)) { let pieceToBlackOut = board![pieceLocation.row][pieceLocation.column] let blackView = UIView(frame: CGRectMake(0, 0, pieceToBlackOut.bounds.size.width, pieceToBlackOut.bounds.size.height)) blackView.backgroundColor = UIColor.blackColor() blackView.alpha = 1.0 pieceToBlackOut.addSubview(blackView) } func PieceAtPoint(point:CGPoint) -> UIImageView { let locationOfPiece = self.arrayLocationOfPiece(point) return board![locationOfPiece.row][locationOfPiece.column] } func arrayLocationOfPiece(point:CGPoint) -> (row:Int, column:Int) { let samplePiece = board![0][0] let samplePieceSize = samplePiece.bounds.size // figure out which row and column the piece is in var pieceAtPointRow:Int = Int( floor(point.y / samplePieceSize.height) ) var pieceAtPointColumn:Int = Int( floor(point.x / samplePieceSize.width) ) if (pieceAtPointColumn >= board![0].count) { pieceAtPointColumn = board![0].count - 1 } if (pieceAtPointRow >= board!.count) { pieceAtPointRow = board!.count - 1 } return (pieceAtPointRow, pieceAtPointColumn) } }
cc0-1.0
3af173cc4cbcae536429e4d920a1541e
34.316901
227
0.648385
4.770695
false
false
false
false
DesWurstes/CleanMyCraft
CleanMyCraft/ViewController.swift
1
8371
// MIT License // Copyright (c) 2017 DesWurstes // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Cocoa class ViewController: NSViewController { var path: String = "/Users/" + NSUserName() + "/Library/Application Support/minecraft" @IBOutlet weak var quit: NSButton! @IBOutlet weak var crashReports: NSView! @IBOutlet weak var misc: NSButton! @IBOutlet weak var screenshots: NSButton! @IBOutlet weak var serverResourcePacks: NSButton! @IBOutlet weak var crashReportsSize: NSTextField! @IBOutlet weak var miscSize: NSTextField! @IBOutlet weak var screenshotsSize: NSTextField! @IBOutlet weak var serverResourceSize: NSTextField! @IBOutlet weak var assetsSize: NSTextField! @IBOutlet weak var librariesSize: NSTextField! @IBAction func quit(_ sender: NSButton) { let alert = NSAlert() alert.messageText = "Are you sure you want to quit?" alert.informativeText = "You may quit now." alert.alertStyle = .informational alert.addButton(withTitle: "Quit") alert.addButton(withTitle: "Cancel") if alert.runModal() == 1000 { NSApplication.shared().terminate(self) } } func fileOrFolderSize(_ fileOrFolderPath: String) -> UInt64 { if !FileManager().fileExists(atPath: fileOrFolderPath) { return 0 } var bool: ObjCBool = false if FileManager().fileExists(atPath: fileOrFolderPath, isDirectory: &bool), bool.boolValue { // url is a folder url do { // Source: https://stackoverflow.com/a/32814710/ // print(fileOrFolderPath) let z: URL = URL(string: fileOrFolderPath.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!.replacingOccurrences(of: "%2F", with: "/"))! as URL //let z: URL = URL(string: fileOrFolderPath.replacingOccurrences(of: " ", with: "%20"))! as URL let files = try FileManager().contentsOfDirectory(at: z, includingPropertiesForKeys: nil, options: []) //let files = try FileManager().contentsOfDirectory(at: NSURL(string: fileOrFolderPath)! as URL, includingPropertiesForKeys: nil, options: []) var folderFileSizeInBytes: UInt64 = 0 for file in files { var boolo: ObjCBool = false if FileManager().fileExists(atPath: file.path, isDirectory: &boolo), boolo.boolValue { folderFileSizeInBytes += fileOrFolderSize(file.path) } else { folderFileSizeInBytes += (try? FileManager.default.attributesOfItem(atPath: file.path)[.size] as? NSNumber)??.uint64Value ?? 0 } } // format it using NSByteCountFormatter to display it properly /*let byteCountFormatter = ByteCountFormatter() byteCountFormatter.allowedUnits = .useBytes byteCountFormatter.countStyle = .file let folderSizeToDisplay = byteCountFormatter.string(fromByteCount: Int64(folderFileSizeInBytes)) print(folderSizeToDisplay)*/ // "X,XXX,XXX bytes" return folderFileSizeInBytes } catch { print(error) } } else { do { return (try FileManager.default.attributesOfItem(atPath: fileOrFolderPath)[.size] as? NSNumber)?.uint64Value ?? 0 } catch { print(error) } } print("Error! Please report it to https://github.com/DesWurstes/CleanMyCraft") return 0 } override func viewDidAppear() { view.wantsLayer = true guard let window = NSApplication.shared().windows.first else { return } // pinky window.backgroundColor = NSColor.init(red: 1, green: 249.0/255.0, blue: 249.0/255.0, alpha: 0.7) // yellow window.backgroundColor = NSColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 102.0/255.0, alpha: 0.6) window.backgroundColor = NSColor.init(red: 100.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 0.675) window.titlebarAppearsTransparent = true window.titleVisibility = .hidden window.isOpaque = false /*if !(Bundle.main.resourcePath! as String).contains("Applications") { let alert = NSAlert() // alert.window.back alert.messageText = "Do you want to move this app to Applications folder?" alert.informativeText = "It may be moved automatically if you want, and it takes less than a second." alert.alertStyle = .warning alert.addButton(withTitle: "Move it!") alert.addButton(withTitle: "I'll move it manually.") if alert.runModal() == 1000 { if FileManager().fileExists(atPath: "/Applications/CleanMyCraft.app") { do { try FileManager().removeItem(atPath: "/Applications/CleanMyCraft.app") } catch let e { print(e) } print("Found /Applications/CleanMyCraft.app") } let t = Process(), p = Pipe(), t1 = Process(), p1 = Pipe() t.standardOutput = p t1.standardOutput = p1 t.launchPath = "/usr/bin/env" t1.launchPath = "/usr/bin/env" t.arguments = ["mv", (Bundle.main.resourcePath! as String).replacingOccurrences(of: "/Contents/Resources", with: ""), "/Applications/CleanMyCraft.app"] t.launch() print(NSString(data: p.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue)!) t1.arguments = ["open", "-n", "-a", "/Applications/CleanMyCraft.app"] t1.launch() print(NSString(data: p1.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue)!) } NSApplication.shared().terminate(self) }*/ assert(FileManager().fileExists(atPath: path)) path += "/" DispatchQueue.main.async { var size = self.fileOrFolderSize(self.path + "crash-reports") + self.fileOrFolderSize(self.path + "logs") for e in self.findFiles(self.path, "hs_err_pid") { size += self.fileOrFolderSize(e) } self.crashReportsSize.stringValue = self.sizeCalculator(size) size = self.fileOrFolderSize(self.path + "level.dat") + self.fileOrFolderSize(self.path + "launcher.pack.lzma") + self.fileOrFolderSize(self.path + "usercache.json") + self.fileOrFolderSize(self.path + "bin") + self.fileOrFolderSize(self.path + "resources") for e in self.findFiles(self.path, "textures_") { size += self.fileOrFolderSize(e) } self.miscSize.stringValue = self.sizeCalculator(size) self.screenshotsSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "screenshots")) self.serverResourceSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "server-resource-packs")) self.assetsSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "assets")) self.librariesSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "libraries")) } } func findFiles(_ path: String, _ containing: String) -> [String] { // Inspired from https://stackoverflow.com/a/35612760/6557621 //let pathURL = NSURL(fileURLWithPath: path, isDirectory: true) var allFiles: [String] = [] if let enumerator = FileManager().enumerator(atPath: path) { for filet in enumerator { if (filet as! String).contains(containing) { allFiles.append(filet as! String) } } } print(allFiles) return allFiles } func sizeCalculator(_ a: UInt64) -> String { if a < 1024 { return "\(a) bytes" } if a < 1024*1024 { return "\(Float(UInt(Float(a)*10/1024))/10) KB" } if a < 1024*1024*1024 { return "\(Float(UInt(Float(a)*10/(1024*1024)))/10) MB" } return "\(Float(UInt(Float(a)*10/(1024*1024*1024)))/10) GB" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
mit
6c208fbd46d7d79f399f2b08e514b75d
42.149485
260
0.71461
3.615983
false
false
false
false
victorchee/NavigationController
NavigationAppearance/NavigationAppearance/AppearanceNavigationController.swift
1
4863
// // AppearanceNavigationController.swift // NavigationAppearance // // Created by qihaijun on 12/2/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit public class AppearanceNavigationController: UINavigationController, UINavigationControllerDelegate { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) delegate = self } override public init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) delegate = self } public convenience init() { self.init(nibName: nil, bundle: nil) } // MARK: - UINavigationControllerDelegate public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { guard let appearanceContext = viewController as? NavigationControllerAppearanceContext else { return } setNavigationBarHidden(appearanceContext.prefersNavigationControllerBarHidden(navigationController: self), animated: animated) setToolbarHidden(appearanceContext.prefersNavigationControllerToolbarHidden(navigationController: self), animated: animated) applyAppearance(appearance: appearanceContext.preferredNavigationControllerAppearance(navigationController: self), animated: animated) // interactive gesture requires more complex login. guard let coordinator = viewController.transitionCoordinator, coordinator.isInteractive else { return } coordinator.animate(alongsideTransition: { (_) -> Void in }) { (context) -> Void in if context.isCancelled, let appearanceContext = self.topViewController as? NavigationControllerAppearanceContext { // hiding navigation bar & toolbar within interaction completion will result into inconsistent UI state self.setNavigationBarHidden(appearanceContext.prefersNavigationControllerBarHidden(navigationController: self), animated: animated) self.setToolbarHidden(appearanceContext.prefersNavigationControllerToolbarHidden(navigationController: self), animated: animated) } } coordinator.notifyWhenInteractionEnds { (context) -> Void in if context.isCancelled, let from = context.viewController(forKey: UITransitionContextViewControllerKey.from) as? NavigationControllerAppearanceContext { // changing navigation bar & toolbar appearance within animate completion will result into UI glitch self.applyAppearance(appearance: from.preferredNavigationControllerAppearance(navigationController: self), animated: true) } } } // MARK: - Appearance Applying private var appliedAppearance: Appearance? public var appearanceApplyingStrategy = AppearanceApplyingStrategy() { didSet { applyAppearance(appearance: appliedAppearance, animated: false) } } private func applyAppearance(appearance: Appearance?, animated: Bool) { if appearance != nil && appliedAppearance != appearance { appliedAppearance = appearance appearanceApplyingStrategy.apply(appearance: appearance, toNavigationController: self, animated: animated) setNeedsStatusBarAppearanceUpdate() } } // MARK: - Appearance Update func updateAppearanceForViewController(viewController: UIViewController) { guard let context = viewController as? NavigationControllerAppearanceContext, viewController == topViewController && transitionCoordinator == nil else { return } setNavigationBarHidden(context.prefersNavigationControllerBarHidden(navigationController: self), animated: true) setToolbarHidden(context.prefersNavigationControllerToolbarHidden(navigationController: self), animated: true) applyAppearance(appearance: context.preferredNavigationControllerAppearance(navigationController: self), animated: true) } public func updateAppearance() { guard let top = topViewController else { return } updateAppearanceForViewController(viewController: top) } override public var preferredStatusBarStyle: UIStatusBarStyle { return appliedAppearance?.statusBarStyle ?? super.preferredStatusBarStyle } override public var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return appliedAppearance != nil ? .fade : super.preferredStatusBarUpdateAnimation } }
mit
9b577cf04f6201e64a2ddb685c58848a
47.138614
164
0.717606
6.414248
false
false
false
false
jcsla/MusicoAudioPlayer
MusicoAudioPlayer/Classes/player/extensions/AudioPlayer+CurrentItem.swift
2
1665
// // AudioPlayer+CurrentItem.swift // AudioPlayer // // Created by Kevin DELANNOY on 29/03/16. // Copyright © 2016 Kevin Delannoy. All rights reserved. // import Foundation public typealias TimeRange = (earliest: TimeInterval, latest: TimeInterval) extension AudioPlayer { /// The current item progression or nil if no item. public var currentItemProgression: TimeInterval? { return player?.currentItem?.currentTime().ap_timeIntervalValue } /// The current item duration or nil if no item or unknown duration. public var currentItemDuration: TimeInterval? { return player?.currentItem?.duration.ap_timeIntervalValue } /// The current seekable range. public var currentItemSeekableRange: TimeRange? { let range = player?.currentItem?.seekableTimeRanges.last?.timeRangeValue if let start = range?.start.ap_timeIntervalValue, let end = range?.end.ap_timeIntervalValue { return (start, end) } if let currentItemProgression = currentItemProgression { // if there is no start and end point of seekable range // return the current time, so no seeking possible return (currentItemProgression, currentItemProgression) } // cannot seek at all, so return nil return nil } /// The current loaded range. public var currentItemLoadedRange: TimeRange? { let range = player?.currentItem?.loadedTimeRanges.last?.timeRangeValue if let start = range?.start.ap_timeIntervalValue, let end = range?.end.ap_timeIntervalValue { return (start, end) } return nil } }
mit
fbb8ea4bf9a2602b9c8b26c82f38fec4
34.404255
101
0.677284
4.837209
false
false
false
false
nakiostudio/EasyPeasy
Example/EasyPeasy/FeedController.swift
1
4091
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import EasyPeasy // NOTE: // I know this controller could be easily achievable with a regular // UITableViewController but this way is much easier to show the // potential of EasyPeasy class FeedController: UIViewController { fileprivate var tweets: [TweetModel] = [] fileprivate var tweetViews: [TweetView] = [] fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: CGRect.zero) return scrollView }() fileprivate lazy var newTweetsView: UIImageView = { let imageView = UIImageView(image: UIImage.easy_newTweets()) return imageView }() override func viewDidLoad() { super.viewDidLoad() self.setup() self.populateFeed() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // An example of UIView animation self.showNewTweetsIndicator(true) } // MARK: Private fileprivate func setup() { // Set stub data self.tweets = TweetModel.stubData() // Background color self.view.backgroundColor = UIColor(red: 0.937, green: 0.937, blue: 0.937, alpha: 1.0) // Set title view let logoImageView = UIImageView(image: UIImage.easy_twitterLogo()) self.navigationItem.titleView = logoImageView // Scrollview self.view.addSubview(self.scrollView) self.scrollView.easy.layout( Edges() ) // New tweets indicator self.view.addSubview(self.newTweetsView) self.newTweetsView.easy.layout( Size(CGSize(width: 118.0, height: 30.0)), Top(-100), CenterX() ) } fileprivate func populateFeed() { // It creates the constraints for each entry for (index, tweet) in self.tweets.enumerated() { let view = TweetView(frame: CGRect.zero) view.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .vertical) view.setContentHuggingPriority(UILayoutPriority(rawValue: 600), for: .vertical) self.scrollView.addSubview(view) view.easy.layout( Width(<=420), Height(>=78), CenterX(), Left().with(.medium), Right().with(.medium), // Pins to top only when we place the first row Top().when { index == 0 }, // Pins to bottom of the preivous item for the other cases Top(1).to(self.tweetViews.last ?? self.scrollView).when { index > 0 } ) view.configureWithModel(tweet) self.tweetViews.append(view) } // Establishes constraint with the bottom of the scroll view to adjust // the content size self.tweetViews.last!.easy.layout( Bottom().to(self.scrollView, .bottom) ) } fileprivate func showNewTweetsIndicator(_ show: Bool) { UIView.animate(withDuration: 0.3, delay: 2.0, options: UIView.AnimationOptions(), animations: { self.newTweetsView.easy.layout(Top(10).when { show }) self.newTweetsView.easy.layout(Top(-100).when { !show }) self.view.layoutIfNeeded() }, completion: { complete in if show { self.showNewTweetsIndicator(false) } }) } }
mit
c640f0e7319b4459232f02e473c56041
33.669492
106
0.602053
4.790398
false
false
false
false
braintree/braintree_ios
Sources/BraintreeSEPADirectDebit/BTSEPADirectDebitClient.swift
1
10432
import Foundation import AuthenticationServices #if canImport(BraintreeCore) import BraintreeCore #endif /// Used to integrate with SEPA Direct Debit. @objcMembers public class BTSEPADirectDebitClient: NSObject { let apiClient: BTAPIClient var webAuthenticationSession: WebAuthenticationSession var sepaDirectDebitAPI: SEPADirectDebitAPI /// Creates a SEPA Direct Debit client. /// - Parameter apiClient: An instance of `BTAPIClient` @objc(initWithAPIClient:) public init(apiClient: BTAPIClient) { self.apiClient = apiClient self.sepaDirectDebitAPI = SEPADirectDebitAPI(apiClient: apiClient) self.webAuthenticationSession = WebAuthenticationSession() } /// Internal for testing. init(apiClient: BTAPIClient, webAuthenticationSession: WebAuthenticationSession, sepaDirectDebitAPI: SEPADirectDebitAPI) { self.apiClient = apiClient self.webAuthenticationSession = webAuthenticationSession self.sepaDirectDebitAPI = sepaDirectDebitAPI } /// Initiates an `ASWebAuthenticationSession` to display a mandate to the user. Upon successful mandate creation, tokenizes the payment method and returns a result /// - Parameters: /// - request: a BTSEPADebitRequest /// - context: the ASWebAuthenticationPresentationContextProviding protocol conforming ViewController @available(iOS 13.0, *) public func tokenize( request: BTSEPADirectDebitRequest, context: ASWebAuthenticationPresentationContextProviding, completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void ) { apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.selected.started") createMandate(request: request) { createMandateResult, error in guard error == nil else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure") completion(nil, error) return } guard let createMandateResult = createMandateResult else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure") completion(nil, SEPADirectDebitError.resultReturnedNil) return } // if the SEPADirectDebitAPI.tokenize API calls returns a "null" URL, the URL has already been approved. if createMandateResult.approvalURL == CreateMandateResult.mandateAlreadyApprovedURLString { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success") self.tokenize(createMandateResult: createMandateResult, completion: completion) return } else if let url = URL(string: createMandateResult.approvalURL) { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success") self.startAuthenticationSession(url: url, context: context) { success, error in switch success { case true: self.tokenize(createMandateResult: createMandateResult, completion: completion) return case false: completion(nil, error) return } } } else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure") completion(nil, SEPADirectDebitError.approvalURLInvalid) } } } /// Initiates an `ASWebAuthenticationSession` to display a mandate to the user. Upon successful mandate creation, tokenizes the payment method and returns a result /// - Parameters: /// - request: a BTSEPADebitRequest /// - Note: This function should only be used for iOS 12 support. This function cannot be invoked on a device running iOS 13 or higher. // NEXT_MAJOR_VERSION remove this function public func tokenize( request: BTSEPADirectDebitRequest, completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void ) { apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.selected.started") createMandate(request: request) { createMandateResult, error in guard error == nil else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure") completion(nil, error) return } guard let createMandateResult = createMandateResult else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure") completion(nil, SEPADirectDebitError.resultReturnedNil) return } // if the SEPADirectDebitAPI.tokenize API calls returns a "null" URL, the URL has already been approved. if createMandateResult.approvalURL == CreateMandateResult.mandateAlreadyApprovedURLString { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success") self.tokenize(createMandateResult: createMandateResult, completion: completion) return } else if let url = URL(string: createMandateResult.approvalURL) { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success") self.startAuthenticationSessionWithoutContext(url: url) { success, error in switch success { case true: self.tokenize(createMandateResult: createMandateResult, completion: completion) return case false: completion(nil, error) return } } } else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure") completion(nil, SEPADirectDebitError.approvalURLInvalid) } } } /// Calls `SEPADirectDebitAPI.createMandate` to create the mandate and returns the `approvalURL` in the `CreateMandateResult` /// that is used to display the mandate to the user during the web flow. func createMandate( request: BTSEPADirectDebitRequest, completion: @escaping (CreateMandateResult?, Error?) -> Void ) { apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.requested") sepaDirectDebitAPI.createMandate(sepaDirectDebitRequest: request) { result, error in completion(result, error) } } func tokenize( createMandateResult: CreateMandateResult, completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void ) { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.tokenize.requested") self.sepaDirectDebitAPI.tokenize(createMandateResult: createMandateResult) { sepaDirectDebitNonce, error in guard let sepaDirectDebitNonce = sepaDirectDebitNonce else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.tokenize.failure") completion(nil, error) return } self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.tokenize.success") completion(sepaDirectDebitNonce, nil) } } /// Starts the web authentication session with the `approvalURL` from the `CreateMandateResult` on iOS 12 func startAuthenticationSessionWithoutContext( url: URL, completion: @escaping (Bool, Error?) -> Void ) { apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.started") self.webAuthenticationSession.start(url: url) { url, error in self.handleWebAuthenticationSessionResult(url: url, error: error, completion: completion) } } /// Starts the web authentication session with the context with the `approvalURL` from the `CreateMandateResult` on iOS 13+ @available(iOS 13.0, *) func startAuthenticationSession( url: URL, context: ASWebAuthenticationPresentationContextProviding, completion: @escaping (Bool, Error?) -> Void ) { apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.started") self.webAuthenticationSession.start(url: url, context: context) { url, error in self.handleWebAuthenticationSessionResult(url: url, error: error, completion: completion) } } /// Handles the result from the web authentication flow when returning to the app. Returns a success result or an error. func handleWebAuthenticationSessionResult( url: URL?, error: Error?, completion: @escaping (Bool, Error?) -> Void ) { if let error = error { switch error { case ASWebAuthenticationSessionError.canceledLogin: self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.canceled") completion(false, SEPADirectDebitError.webFlowCanceled) return default: self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.presentation-context-invalid") completion(false, SEPADirectDebitError.presentationContextInvalid) return } } else if let url = url { guard url.absoluteString.contains("sepa/success"), let queryParameter = self.getQueryStringParameter(url: url.absoluteString, param: "success"), queryParameter.contains("true") else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.failure") completion(false, SEPADirectDebitError.resultURLInvalid) return } self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.success") completion(true, nil) } else { self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.failure") completion(false, SEPADirectDebitError.authenticationResultNil) } } private func getQueryStringParameter(url: String, param: String) -> String? { guard let url = URLComponents(string: url) else { return nil } return url.queryItems?.first { $0.name == param }?.value } }
mit
ecba1eb7e55c6cdb83541f73a3cb6996
47.52093
167
0.64791
5.081344
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CodePipeline/CodePipeline_Shapes.swift
1
149436
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension CodePipeline { // MARK: Enums public enum ActionCategory: String, CustomStringConvertible, Codable { case approval = "Approval" case build = "Build" case deploy = "Deploy" case invoke = "Invoke" case source = "Source" case test = "Test" public var description: String { return self.rawValue } } public enum ActionConfigurationPropertyType: String, CustomStringConvertible, Codable { case boolean = "Boolean" case number = "Number" case string = "String" public var description: String { return self.rawValue } } public enum ActionExecutionStatus: String, CustomStringConvertible, Codable { case abandoned = "Abandoned" case failed = "Failed" case inprogress = "InProgress" case succeeded = "Succeeded" public var description: String { return self.rawValue } } public enum ActionOwner: String, CustomStringConvertible, Codable { case aws = "AWS" case custom = "Custom" case thirdparty = "ThirdParty" public var description: String { return self.rawValue } } public enum ApprovalStatus: String, CustomStringConvertible, Codable { case approved = "Approved" case rejected = "Rejected" public var description: String { return self.rawValue } } public enum ArtifactLocationType: String, CustomStringConvertible, Codable { case s3 = "S3" public var description: String { return self.rawValue } } public enum ArtifactStoreType: String, CustomStringConvertible, Codable { case s3 = "S3" public var description: String { return self.rawValue } } public enum BlockerType: String, CustomStringConvertible, Codable { case schedule = "Schedule" public var description: String { return self.rawValue } } public enum EncryptionKeyType: String, CustomStringConvertible, Codable { case kms = "KMS" public var description: String { return self.rawValue } } public enum FailureType: String, CustomStringConvertible, Codable { case configurationerror = "ConfigurationError" case jobfailed = "JobFailed" case permissionerror = "PermissionError" case revisionoutofsync = "RevisionOutOfSync" case revisionunavailable = "RevisionUnavailable" case systemunavailable = "SystemUnavailable" public var description: String { return self.rawValue } } public enum JobStatus: String, CustomStringConvertible, Codable { case created = "Created" case dispatched = "Dispatched" case failed = "Failed" case inprogress = "InProgress" case queued = "Queued" case succeeded = "Succeeded" case timedout = "TimedOut" public var description: String { return self.rawValue } } public enum PipelineExecutionStatus: String, CustomStringConvertible, Codable { case failed = "Failed" case inprogress = "InProgress" case stopped = "Stopped" case stopping = "Stopping" case succeeded = "Succeeded" case superseded = "Superseded" public var description: String { return self.rawValue } } public enum StageExecutionStatus: String, CustomStringConvertible, Codable { case failed = "Failed" case inprogress = "InProgress" case stopped = "Stopped" case stopping = "Stopping" case succeeded = "Succeeded" public var description: String { return self.rawValue } } public enum StageRetryMode: String, CustomStringConvertible, Codable { case failedActions = "FAILED_ACTIONS" public var description: String { return self.rawValue } } public enum StageTransitionType: String, CustomStringConvertible, Codable { case inbound = "Inbound" case outbound = "Outbound" public var description: String { return self.rawValue } } public enum TriggerType: String, CustomStringConvertible, Codable { case cloudwatchevent = "CloudWatchEvent" case createpipeline = "CreatePipeline" case pollforsourcechanges = "PollForSourceChanges" case putactionrevision = "PutActionRevision" case startpipelineexecution = "StartPipelineExecution" case webhook = "Webhook" public var description: String { return self.rawValue } } public enum WebhookAuthenticationType: String, CustomStringConvertible, Codable { case githubHmac = "GITHUB_HMAC" case ip = "IP" case unauthenticated = "UNAUTHENTICATED" public var description: String { return self.rawValue } } // MARK: Shapes public struct AWSSessionCredentials: AWSDecodableShape { /// The access key for the session. public let accessKeyId: String /// The secret access key for the session. public let secretAccessKey: String /// The token for the session. public let sessionToken: String public init(accessKeyId: String, secretAccessKey: String, sessionToken: String) { self.accessKeyId = accessKeyId self.secretAccessKey = secretAccessKey self.sessionToken = sessionToken } private enum CodingKeys: String, CodingKey { case accessKeyId case secretAccessKey case sessionToken } } public struct AcknowledgeJobInput: AWSEncodableShape { /// The unique system-generated ID of the job for which you want to confirm receipt. public let jobId: String /// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response of the PollForJobs request that returned this job. public let nonce: String public init(jobId: String, nonce: String) { self.jobId = jobId self.nonce = nonce } public func validate(name: String) throws { try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.validate(self.nonce, name: "nonce", parent: name, max: 50) try self.validate(self.nonce, name: "nonce", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case jobId case nonce } } public struct AcknowledgeJobOutput: AWSDecodableShape { /// Whether the job worker has received the specified job. public let status: JobStatus? public init(status: JobStatus? = nil) { self.status = status } private enum CodingKeys: String, CodingKey { case status } } public struct AcknowledgeThirdPartyJobInput: AWSEncodableShape { /// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details. public let clientToken: String /// The unique system-generated ID of the job. public let jobId: String /// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response to a GetThirdPartyJobDetails request. public let nonce: String public init(clientToken: String, jobId: String, nonce: String) { self.clientToken = clientToken self.jobId = jobId self.nonce = nonce } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.jobId, name: "jobId", parent: name, max: 512) try self.validate(self.jobId, name: "jobId", parent: name, min: 1) try self.validate(self.nonce, name: "nonce", parent: name, max: 50) try self.validate(self.nonce, name: "nonce", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken case jobId case nonce } } public struct AcknowledgeThirdPartyJobOutput: AWSDecodableShape { /// The status information for the third party job, if any. public let status: JobStatus? public init(status: JobStatus? = nil) { self.status = status } private enum CodingKeys: String, CodingKey { case status } } public struct ActionConfiguration: AWSDecodableShape { /// The configuration data for the action. public let configuration: [String: String]? public init(configuration: [String: String]? = nil) { self.configuration = configuration } private enum CodingKeys: String, CodingKey { case configuration } } public struct ActionConfigurationProperty: AWSEncodableShape & AWSDecodableShape { /// The description of the action configuration property that is displayed to users. public let description: String? /// Whether the configuration property is a key. public let key: Bool /// The name of the action configuration property. public let name: String /// Indicates that the property is used with PollForJobs. When creating a custom action, an action can have up to one queryable property. If it has one, that property must be both required and not secret. If you create a pipeline with a custom action type, and that custom action contains a queryable property, the value for that configuration property is subject to other restrictions. The value must be less than or equal to twenty (20) characters. The value can contain only alphanumeric characters, underscores, and hyphens. public let queryable: Bool? /// Whether the configuration property is a required value. public let required: Bool /// Whether the configuration property is secret. Secrets are hidden from all calls except for GetJobDetails, GetThirdPartyJobDetails, PollForJobs, and PollForThirdPartyJobs. When updating a pipeline, passing * * * * * without changing any other values of the action preserves the previous value of the secret. public let secret: Bool /// The type of the configuration property. public let type: ActionConfigurationPropertyType? public init(description: String? = nil, key: Bool, name: String, queryable: Bool? = nil, required: Bool, secret: Bool, type: ActionConfigurationPropertyType? = nil) { self.description = description self.key = key self.name = name self.queryable = queryable self.required = required self.secret = secret self.type = type } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 160) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, max: 50) try self.validate(self.name, name: "name", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case description case key case name case queryable case required case secret case type } } public struct ActionContext: AWSDecodableShape { /// The system-generated unique ID that corresponds to an action's execution. public let actionExecutionId: String? /// The name of the action in the context of a job. public let name: String? public init(actionExecutionId: String? = nil, name: String? = nil) { self.actionExecutionId = actionExecutionId self.name = name } private enum CodingKeys: String, CodingKey { case actionExecutionId case name } } public struct ActionDeclaration: AWSEncodableShape & AWSDecodableShape { /// Specifies the action type and the provider of the action. public let actionTypeId: ActionTypeId /// The action's configuration. These are key-value pairs that specify input values for an action. For more information, see Action Structure Requirements in CodePipeline. For the list of configuration properties for the AWS CloudFormation action type in CodePipeline, see Configuration Properties Reference in the AWS CloudFormation User Guide. For template snippets with examples, see Using Parameter Override Functions with CodePipeline Pipelines in the AWS CloudFormation User Guide. The values can be represented in either JSON or YAML format. For example, the JSON configuration item format is as follows: JSON: "Configuration" : { Key : Value }, public let configuration: [String: String]? /// The name or ID of the artifact consumed by the action, such as a test or build artifact. public let inputArtifacts: [InputArtifact]? /// The action declaration's name. public let name: String /// The variable namespace associated with the action. All variables produced as output by this action fall under this namespace. public let namespace: String? /// The name or ID of the result of the action declaration, such as a test or build artifact. public let outputArtifacts: [OutputArtifact]? /// The action declaration's AWS Region, such as us-east-1. public let region: String? /// The ARN of the IAM service role that performs the declared action. This is assumed through the roleArn for the pipeline. public let roleArn: String? /// The order in which actions are run. public let runOrder: Int? public init(actionTypeId: ActionTypeId, configuration: [String: String]? = nil, inputArtifacts: [InputArtifact]? = nil, name: String, namespace: String? = nil, outputArtifacts: [OutputArtifact]? = nil, region: String? = nil, roleArn: String? = nil, runOrder: Int? = nil) { self.actionTypeId = actionTypeId self.configuration = configuration self.inputArtifacts = inputArtifacts self.name = name self.namespace = namespace self.outputArtifacts = outputArtifacts self.region = region self.roleArn = roleArn self.runOrder = runOrder } public func validate(name: String) throws { try self.actionTypeId.validate(name: "\(name).actionTypeId") try self.configuration?.forEach { try validate($0.key, name: "configuration.key", parent: name, max: 50) try validate($0.key, name: "configuration.key", parent: name, min: 1) try validate($0.value, name: "configuration[\"\($0.key)\"]", parent: name, max: 1000) try validate($0.value, name: "configuration[\"\($0.key)\"]", parent: name, min: 1) } try self.inputArtifacts?.forEach { try $0.validate(name: "\(name).inputArtifacts[]") } try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.namespace, name: "namespace", parent: name, max: 100) try self.validate(self.namespace, name: "namespace", parent: name, min: 1) try self.validate(self.namespace, name: "namespace", parent: name, pattern: "[A-Za-z0-9@\\-_]+") try self.outputArtifacts?.forEach { try $0.validate(name: "\(name).outputArtifacts[]") } try self.validate(self.region, name: "region", parent: name, max: 30) try self.validate(self.region, name: "region", parent: name, min: 4) try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1024) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:aws(-[\\w]+)*:iam::[0-9]{12}:role/.*") try self.validate(self.runOrder, name: "runOrder", parent: name, max: 999) try self.validate(self.runOrder, name: "runOrder", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case actionTypeId case configuration case inputArtifacts case name case namespace case outputArtifacts case region case roleArn case runOrder } } public struct ActionExecution: AWSDecodableShape { /// The details of an error returned by a URL external to AWS. public let errorDetails: ErrorDetails? /// The external ID of the run of the action. public let externalExecutionId: String? /// The URL of a resource external to AWS that is used when running the action (for example, an external repository URL). public let externalExecutionUrl: String? /// The last status change of the action. public let lastStatusChange: Date? /// The ARN of the user who last changed the pipeline. public let lastUpdatedBy: String? /// A percentage of completeness of the action as it runs. public let percentComplete: Int? /// The status of the action, or for a completed action, the last status of the action. public let status: ActionExecutionStatus? /// A summary of the run of the action. public let summary: String? /// The system-generated token used to identify a unique approval request. The token for each open approval request can be obtained using the GetPipelineState command. It is used to validate that the approval request corresponding to this token is still valid. public let token: String? public init(errorDetails: ErrorDetails? = nil, externalExecutionId: String? = nil, externalExecutionUrl: String? = nil, lastStatusChange: Date? = nil, lastUpdatedBy: String? = nil, percentComplete: Int? = nil, status: ActionExecutionStatus? = nil, summary: String? = nil, token: String? = nil) { self.errorDetails = errorDetails self.externalExecutionId = externalExecutionId self.externalExecutionUrl = externalExecutionUrl self.lastStatusChange = lastStatusChange self.lastUpdatedBy = lastUpdatedBy self.percentComplete = percentComplete self.status = status self.summary = summary self.token = token } private enum CodingKeys: String, CodingKey { case errorDetails case externalExecutionId case externalExecutionUrl case lastStatusChange case lastUpdatedBy case percentComplete case status case summary case token } } public struct ActionExecutionDetail: AWSDecodableShape { /// The action execution ID. public let actionExecutionId: String? /// The name of the action. public let actionName: String? /// Input details for the action execution, such as role ARN, Region, and input artifacts. public let input: ActionExecutionInput? /// The last update time of the action execution. public let lastUpdateTime: Date? /// Output details for the action execution, such as the action execution result. public let output: ActionExecutionOutput? /// The pipeline execution ID for the action execution. public let pipelineExecutionId: String? /// The version of the pipeline where the action was run. public let pipelineVersion: Int? /// The name of the stage that contains the action. public let stageName: String? /// The start time of the action execution. public let startTime: Date? /// The status of the action execution. Status categories are InProgress, Succeeded, and Failed. public let status: ActionExecutionStatus? public init(actionExecutionId: String? = nil, actionName: String? = nil, input: ActionExecutionInput? = nil, lastUpdateTime: Date? = nil, output: ActionExecutionOutput? = nil, pipelineExecutionId: String? = nil, pipelineVersion: Int? = nil, stageName: String? = nil, startTime: Date? = nil, status: ActionExecutionStatus? = nil) { self.actionExecutionId = actionExecutionId self.actionName = actionName self.input = input self.lastUpdateTime = lastUpdateTime self.output = output self.pipelineExecutionId = pipelineExecutionId self.pipelineVersion = pipelineVersion self.stageName = stageName self.startTime = startTime self.status = status } private enum CodingKeys: String, CodingKey { case actionExecutionId case actionName case input case lastUpdateTime case output case pipelineExecutionId case pipelineVersion case stageName case startTime case status } } public struct ActionExecutionFilter: AWSEncodableShape { /// The pipeline execution ID used to filter action execution history. public let pipelineExecutionId: String? public init(pipelineExecutionId: String? = nil) { self.pipelineExecutionId = pipelineExecutionId } public func validate(name: String) throws { try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case pipelineExecutionId } } public struct ActionExecutionInput: AWSDecodableShape { public let actionTypeId: ActionTypeId? /// Configuration data for an action execution. public let configuration: [String: String]? /// Details of input artifacts of the action that correspond to the action execution. public let inputArtifacts: [ArtifactDetail]? /// The variable namespace associated with the action. All variables produced as output by this action fall under this namespace. public let namespace: String? /// The AWS Region for the action, such as us-east-1. public let region: String? /// Configuration data for an action execution with all variable references replaced with their real values for the execution. public let resolvedConfiguration: [String: String]? /// The ARN of the IAM service role that performs the declared action. This is assumed through the roleArn for the pipeline. public let roleArn: String? public init(actionTypeId: ActionTypeId? = nil, configuration: [String: String]? = nil, inputArtifacts: [ArtifactDetail]? = nil, namespace: String? = nil, region: String? = nil, resolvedConfiguration: [String: String]? = nil, roleArn: String? = nil) { self.actionTypeId = actionTypeId self.configuration = configuration self.inputArtifacts = inputArtifacts self.namespace = namespace self.region = region self.resolvedConfiguration = resolvedConfiguration self.roleArn = roleArn } private enum CodingKeys: String, CodingKey { case actionTypeId case configuration case inputArtifacts case namespace case region case resolvedConfiguration case roleArn } } public struct ActionExecutionOutput: AWSDecodableShape { /// Execution result information listed in the output details for an action execution. public let executionResult: ActionExecutionResult? /// Details of output artifacts of the action that correspond to the action execution. public let outputArtifacts: [ArtifactDetail]? /// The outputVariables field shows the key-value pairs that were output as part of that execution. public let outputVariables: [String: String]? public init(executionResult: ActionExecutionResult? = nil, outputArtifacts: [ArtifactDetail]? = nil, outputVariables: [String: String]? = nil) { self.executionResult = executionResult self.outputArtifacts = outputArtifacts self.outputVariables = outputVariables } private enum CodingKeys: String, CodingKey { case executionResult case outputArtifacts case outputVariables } } public struct ActionExecutionResult: AWSDecodableShape { /// The action provider's external ID for the action execution. public let externalExecutionId: String? /// The action provider's summary for the action execution. public let externalExecutionSummary: String? /// The deepest external link to the external resource (for example, a repository URL or deployment endpoint) that is used when running the action. public let externalExecutionUrl: String? public init(externalExecutionId: String? = nil, externalExecutionSummary: String? = nil, externalExecutionUrl: String? = nil) { self.externalExecutionId = externalExecutionId self.externalExecutionSummary = externalExecutionSummary self.externalExecutionUrl = externalExecutionUrl } private enum CodingKeys: String, CodingKey { case externalExecutionId case externalExecutionSummary case externalExecutionUrl } } public struct ActionRevision: AWSEncodableShape & AWSDecodableShape { /// The date and time when the most recent version of the action was created, in timestamp format. public let created: Date /// The unique identifier of the change that set the state to this revision (for example, a deployment ID or timestamp). public let revisionChangeId: String /// The system-generated unique ID that identifies the revision number of the action. public let revisionId: String public init(created: Date, revisionChangeId: String, revisionId: String) { self.created = created self.revisionChangeId = revisionChangeId self.revisionId = revisionId } public func validate(name: String) throws { try self.validate(self.revisionChangeId, name: "revisionChangeId", parent: name, max: 100) try self.validate(self.revisionChangeId, name: "revisionChangeId", parent: name, min: 1) try self.validate(self.revisionId, name: "revisionId", parent: name, max: 1500) try self.validate(self.revisionId, name: "revisionId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case created case revisionChangeId case revisionId } } public struct ActionState: AWSDecodableShape { /// The name of the action. public let actionName: String? /// Represents information about the version (or revision) of an action. public let currentRevision: ActionRevision? /// A URL link for more information about the state of the action, such as a deployment group details page. public let entityUrl: String? /// Represents information about the run of an action. public let latestExecution: ActionExecution? /// A URL link for more information about the revision, such as a commit details page. public let revisionUrl: String? public init(actionName: String? = nil, currentRevision: ActionRevision? = nil, entityUrl: String? = nil, latestExecution: ActionExecution? = nil, revisionUrl: String? = nil) { self.actionName = actionName self.currentRevision = currentRevision self.entityUrl = entityUrl self.latestExecution = latestExecution self.revisionUrl = revisionUrl } private enum CodingKeys: String, CodingKey { case actionName case currentRevision case entityUrl case latestExecution case revisionUrl } } public struct ActionType: AWSDecodableShape { /// The configuration properties for the action type. public let actionConfigurationProperties: [ActionConfigurationProperty]? /// Represents information about an action type. public let id: ActionTypeId /// The details of the input artifact for the action, such as its commit ID. public let inputArtifactDetails: ArtifactDetails /// The details of the output artifact of the action, such as its commit ID. public let outputArtifactDetails: ArtifactDetails /// The settings for the action type. public let settings: ActionTypeSettings? public init(actionConfigurationProperties: [ActionConfigurationProperty]? = nil, id: ActionTypeId, inputArtifactDetails: ArtifactDetails, outputArtifactDetails: ArtifactDetails, settings: ActionTypeSettings? = nil) { self.actionConfigurationProperties = actionConfigurationProperties self.id = id self.inputArtifactDetails = inputArtifactDetails self.outputArtifactDetails = outputArtifactDetails self.settings = settings } private enum CodingKeys: String, CodingKey { case actionConfigurationProperties case id case inputArtifactDetails case outputArtifactDetails case settings } } public struct ActionTypeId: AWSEncodableShape & AWSDecodableShape { /// A category defines what kind of action can be taken in the stage, and constrains the provider type for the action. Valid categories are limited to one of the following values. public let category: ActionCategory /// The creator of the action being called. public let owner: ActionOwner /// The provider of the service being called by the action. Valid providers are determined by the action category. For example, an action in the Deploy category type might have a provider of AWS CodeDeploy, which would be specified as CodeDeploy. For more information, see Valid Action Types and Providers in CodePipeline. public let provider: String /// A string that describes the action version. public let version: String public init(category: ActionCategory, owner: ActionOwner, provider: String, version: String) { self.category = category self.owner = owner self.provider = provider self.version = version } public func validate(name: String) throws { try self.validate(self.provider, name: "provider", parent: name, max: 25) try self.validate(self.provider, name: "provider", parent: name, min: 1) try self.validate(self.provider, name: "provider", parent: name, pattern: "[0-9A-Za-z_-]+") try self.validate(self.version, name: "version", parent: name, max: 9) try self.validate(self.version, name: "version", parent: name, min: 1) try self.validate(self.version, name: "version", parent: name, pattern: "[0-9A-Za-z_-]+") } private enum CodingKeys: String, CodingKey { case category case owner case provider case version } } public struct ActionTypeSettings: AWSEncodableShape & AWSDecodableShape { /// The URL returned to the AWS CodePipeline console that provides a deep link to the resources of the external system, such as the configuration page for an AWS CodeDeploy deployment group. This link is provided as part of the action display in the pipeline. public let entityUrlTemplate: String? /// The URL returned to the AWS CodePipeline console that contains a link to the top-level landing page for the external system, such as the console page for AWS CodeDeploy. This link is shown on the pipeline view page in the AWS CodePipeline console and provides a link to the execution entity of the external action. public let executionUrlTemplate: String? /// The URL returned to the AWS CodePipeline console that contains a link to the page where customers can update or change the configuration of the external action. public let revisionUrlTemplate: String? /// The URL of a sign-up page where users can sign up for an external service and perform initial configuration of the action provided by that service. public let thirdPartyConfigurationUrl: String? public init(entityUrlTemplate: String? = nil, executionUrlTemplate: String? = nil, revisionUrlTemplate: String? = nil, thirdPartyConfigurationUrl: String? = nil) { self.entityUrlTemplate = entityUrlTemplate self.executionUrlTemplate = executionUrlTemplate self.revisionUrlTemplate = revisionUrlTemplate self.thirdPartyConfigurationUrl = thirdPartyConfigurationUrl } public func validate(name: String) throws { try self.validate(self.entityUrlTemplate, name: "entityUrlTemplate", parent: name, max: 2048) try self.validate(self.entityUrlTemplate, name: "entityUrlTemplate", parent: name, min: 1) try self.validate(self.executionUrlTemplate, name: "executionUrlTemplate", parent: name, max: 2048) try self.validate(self.executionUrlTemplate, name: "executionUrlTemplate", parent: name, min: 1) try self.validate(self.revisionUrlTemplate, name: "revisionUrlTemplate", parent: name, max: 2048) try self.validate(self.revisionUrlTemplate, name: "revisionUrlTemplate", parent: name, min: 1) try self.validate(self.thirdPartyConfigurationUrl, name: "thirdPartyConfigurationUrl", parent: name, max: 2048) try self.validate(self.thirdPartyConfigurationUrl, name: "thirdPartyConfigurationUrl", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case entityUrlTemplate case executionUrlTemplate case revisionUrlTemplate case thirdPartyConfigurationUrl } } public struct ApprovalResult: AWSEncodableShape { /// The response submitted by a reviewer assigned to an approval action request. public let status: ApprovalStatus /// The summary of the current status of the approval request. public let summary: String public init(status: ApprovalStatus, summary: String) { self.status = status self.summary = summary } public func validate(name: String) throws { try self.validate(self.summary, name: "summary", parent: name, max: 512) try self.validate(self.summary, name: "summary", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case status case summary } } public struct Artifact: AWSDecodableShape { /// The location of an artifact. public let location: ArtifactLocation? /// The artifact's name. public let name: String? /// The artifact's revision ID. Depending on the type of object, this could be a commit ID (GitHub) or a revision ID (Amazon S3). public let revision: String? public init(location: ArtifactLocation? = nil, name: String? = nil, revision: String? = nil) { self.location = location self.name = name self.revision = revision } private enum CodingKeys: String, CodingKey { case location case name case revision } } public struct ArtifactDetail: AWSDecodableShape { /// The artifact object name for the action execution. public let name: String? /// The Amazon S3 artifact location for the action execution. public let s3location: S3Location? public init(name: String? = nil, s3location: S3Location? = nil) { self.name = name self.s3location = s3location } private enum CodingKeys: String, CodingKey { case name case s3location } } public struct ArtifactDetails: AWSEncodableShape & AWSDecodableShape { /// The maximum number of artifacts allowed for the action type. public let maximumCount: Int /// The minimum number of artifacts allowed for the action type. public let minimumCount: Int public init(maximumCount: Int, minimumCount: Int) { self.maximumCount = maximumCount self.minimumCount = minimumCount } public func validate(name: String) throws { try self.validate(self.maximumCount, name: "maximumCount", parent: name, max: 5) try self.validate(self.maximumCount, name: "maximumCount", parent: name, min: 0) try self.validate(self.minimumCount, name: "minimumCount", parent: name, max: 5) try self.validate(self.minimumCount, name: "minimumCount", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case maximumCount case minimumCount } } public struct ArtifactLocation: AWSDecodableShape { /// The S3 bucket that contains the artifact. public let s3Location: S3ArtifactLocation? /// The type of artifact in the location. public let type: ArtifactLocationType? public init(s3Location: S3ArtifactLocation? = nil, type: ArtifactLocationType? = nil) { self.s3Location = s3Location self.type = type } private enum CodingKeys: String, CodingKey { case s3Location case type } } public struct ArtifactRevision: AWSDecodableShape { /// The date and time when the most recent revision of the artifact was created, in timestamp format. public let created: Date? /// The name of an artifact. This name might be system-generated, such as "MyApp", or defined by the user when an action is created. public let name: String? /// An additional identifier for a revision, such as a commit date or, for artifacts stored in Amazon S3 buckets, the ETag value. public let revisionChangeIdentifier: String? /// The revision ID of the artifact. public let revisionId: String? /// Summary information about the most recent revision of the artifact. For GitHub and AWS CodeCommit repositories, the commit message. For Amazon S3 buckets or actions, the user-provided content of a codepipeline-artifact-revision-summary key specified in the object metadata. public let revisionSummary: String? /// The commit ID for the artifact revision. For artifacts stored in GitHub or AWS CodeCommit repositories, the commit ID is linked to a commit details page. public let revisionUrl: String? public init(created: Date? = nil, name: String? = nil, revisionChangeIdentifier: String? = nil, revisionId: String? = nil, revisionSummary: String? = nil, revisionUrl: String? = nil) { self.created = created self.name = name self.revisionChangeIdentifier = revisionChangeIdentifier self.revisionId = revisionId self.revisionSummary = revisionSummary self.revisionUrl = revisionUrl } private enum CodingKeys: String, CodingKey { case created case name case revisionChangeIdentifier case revisionId case revisionSummary case revisionUrl } } public struct ArtifactStore: AWSEncodableShape & AWSDecodableShape { /// The encryption key used to encrypt the data in the artifact store, such as an AWS Key Management Service (AWS KMS) key. If this is undefined, the default key for Amazon S3 is used. public let encryptionKey: EncryptionKey? /// The S3 bucket used for storing the artifacts for a pipeline. You can specify the name of an S3 bucket but not a folder in the bucket. A folder to contain the pipeline artifacts is created for you based on the name of the pipeline. You can use any S3 bucket in the same AWS Region as the pipeline to store your pipeline artifacts. public let location: String /// The type of the artifact store, such as S3. public let type: ArtifactStoreType public init(encryptionKey: EncryptionKey? = nil, location: String, type: ArtifactStoreType) { self.encryptionKey = encryptionKey self.location = location self.type = type } public func validate(name: String) throws { try self.encryptionKey?.validate(name: "\(name).encryptionKey") try self.validate(self.location, name: "location", parent: name, max: 63) try self.validate(self.location, name: "location", parent: name, min: 3) try self.validate(self.location, name: "location", parent: name, pattern: "[a-zA-Z0-9\\-\\.]+") } private enum CodingKeys: String, CodingKey { case encryptionKey case location case type } } public struct BlockerDeclaration: AWSEncodableShape & AWSDecodableShape { /// Reserved for future use. public let name: String /// Reserved for future use. public let type: BlockerType public init(name: String, type: BlockerType) { self.name = name self.type = type } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name case type } } public struct CreateCustomActionTypeInput: AWSEncodableShape { /// The category of the custom action, such as a build action or a test action. Although Source and Approval are listed as valid values, they are not currently functional. These values are reserved for future use. public let category: ActionCategory /// The configuration properties for the custom action. You can refer to a name in the configuration properties of the custom action within the URL templates by following the format of {Config:name}, as long as the configuration property is both required and not secret. For more information, see Create a Custom Action for a Pipeline. public let configurationProperties: [ActionConfigurationProperty]? /// The details of the input artifact for the action, such as its commit ID. public let inputArtifactDetails: ArtifactDetails /// The details of the output artifact of the action, such as its commit ID. public let outputArtifactDetails: ArtifactDetails /// The provider of the service used in the custom action, such as AWS CodeDeploy. public let provider: String /// URLs that provide users information about this custom action. public let settings: ActionTypeSettings? /// The tags for the custom action. public let tags: [Tag]? /// The version identifier of the custom action. public let version: String public init(category: ActionCategory, configurationProperties: [ActionConfigurationProperty]? = nil, inputArtifactDetails: ArtifactDetails, outputArtifactDetails: ArtifactDetails, provider: String, settings: ActionTypeSettings? = nil, tags: [Tag]? = nil, version: String) { self.category = category self.configurationProperties = configurationProperties self.inputArtifactDetails = inputArtifactDetails self.outputArtifactDetails = outputArtifactDetails self.provider = provider self.settings = settings self.tags = tags self.version = version } public func validate(name: String) throws { try self.configurationProperties?.forEach { try $0.validate(name: "\(name).configurationProperties[]") } try self.validate(self.configurationProperties, name: "configurationProperties", parent: name, max: 10) try self.inputArtifactDetails.validate(name: "\(name).inputArtifactDetails") try self.outputArtifactDetails.validate(name: "\(name).outputArtifactDetails") try self.validate(self.provider, name: "provider", parent: name, max: 25) try self.validate(self.provider, name: "provider", parent: name, min: 1) try self.validate(self.provider, name: "provider", parent: name, pattern: "[0-9A-Za-z_-]+") try self.settings?.validate(name: "\(name).settings") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.version, name: "version", parent: name, max: 9) try self.validate(self.version, name: "version", parent: name, min: 1) try self.validate(self.version, name: "version", parent: name, pattern: "[0-9A-Za-z_-]+") } private enum CodingKeys: String, CodingKey { case category case configurationProperties case inputArtifactDetails case outputArtifactDetails case provider case settings case tags case version } } public struct CreateCustomActionTypeOutput: AWSDecodableShape { /// Returns information about the details of an action type. public let actionType: ActionType /// Specifies the tags applied to the custom action. public let tags: [Tag]? public init(actionType: ActionType, tags: [Tag]? = nil) { self.actionType = actionType self.tags = tags } private enum CodingKeys: String, CodingKey { case actionType case tags } } public struct CreatePipelineInput: AWSEncodableShape { /// Represents the structure of actions and stages to be performed in the pipeline. public let pipeline: PipelineDeclaration /// The tags for the pipeline. public let tags: [Tag]? public init(pipeline: PipelineDeclaration, tags: [Tag]? = nil) { self.pipeline = pipeline self.tags = tags } public func validate(name: String) throws { try self.pipeline.validate(name: "\(name).pipeline") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } } private enum CodingKeys: String, CodingKey { case pipeline case tags } } public struct CreatePipelineOutput: AWSDecodableShape { /// Represents the structure of actions and stages to be performed in the pipeline. public let pipeline: PipelineDeclaration? /// Specifies the tags applied to the pipeline. public let tags: [Tag]? public init(pipeline: PipelineDeclaration? = nil, tags: [Tag]? = nil) { self.pipeline = pipeline self.tags = tags } private enum CodingKeys: String, CodingKey { case pipeline case tags } } public struct CurrentRevision: AWSEncodableShape { /// The change identifier for the current revision. public let changeIdentifier: String /// The date and time when the most recent revision of the artifact was created, in timestamp format. public let created: Date? /// The revision ID of the current version of an artifact. public let revision: String /// The summary of the most recent revision of the artifact. public let revisionSummary: String? public init(changeIdentifier: String, created: Date? = nil, revision: String, revisionSummary: String? = nil) { self.changeIdentifier = changeIdentifier self.created = created self.revision = revision self.revisionSummary = revisionSummary } public func validate(name: String) throws { try self.validate(self.changeIdentifier, name: "changeIdentifier", parent: name, max: 100) try self.validate(self.changeIdentifier, name: "changeIdentifier", parent: name, min: 1) try self.validate(self.revision, name: "revision", parent: name, max: 1500) try self.validate(self.revision, name: "revision", parent: name, min: 1) try self.validate(self.revisionSummary, name: "revisionSummary", parent: name, max: 2048) try self.validate(self.revisionSummary, name: "revisionSummary", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case changeIdentifier case created case revision case revisionSummary } } public struct DeleteCustomActionTypeInput: AWSEncodableShape { /// The category of the custom action that you want to delete, such as source or deploy. public let category: ActionCategory /// The provider of the service used in the custom action, such as AWS CodeDeploy. public let provider: String /// The version of the custom action to delete. public let version: String public init(category: ActionCategory, provider: String, version: String) { self.category = category self.provider = provider self.version = version } public func validate(name: String) throws { try self.validate(self.provider, name: "provider", parent: name, max: 25) try self.validate(self.provider, name: "provider", parent: name, min: 1) try self.validate(self.provider, name: "provider", parent: name, pattern: "[0-9A-Za-z_-]+") try self.validate(self.version, name: "version", parent: name, max: 9) try self.validate(self.version, name: "version", parent: name, min: 1) try self.validate(self.version, name: "version", parent: name, pattern: "[0-9A-Za-z_-]+") } private enum CodingKeys: String, CodingKey { case category case provider case version } } public struct DeletePipelineInput: AWSEncodableShape { /// The name of the pipeline to be deleted. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case name } } public struct DeleteWebhookInput: AWSEncodableShape { /// The name of the webhook you want to delete. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case name } } public struct DeleteWebhookOutput: AWSDecodableShape { public init() {} } public struct DeregisterWebhookWithThirdPartyInput: AWSEncodableShape { /// The name of the webhook you want to deregister. public let webhookName: String? public init(webhookName: String? = nil) { self.webhookName = webhookName } public func validate(name: String) throws { try self.validate(self.webhookName, name: "webhookName", parent: name, max: 100) try self.validate(self.webhookName, name: "webhookName", parent: name, min: 1) try self.validate(self.webhookName, name: "webhookName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case webhookName } } public struct DeregisterWebhookWithThirdPartyOutput: AWSDecodableShape { public init() {} } public struct DisableStageTransitionInput: AWSEncodableShape { /// The name of the pipeline in which you want to disable the flow of artifacts from one stage to another. public let pipelineName: String /// The reason given to the user that a stage is disabled, such as waiting for manual approval or manual tests. This message is displayed in the pipeline console UI. public let reason: String /// The name of the stage where you want to disable the inbound or outbound transition of artifacts. public let stageName: String /// Specifies whether artifacts are prevented from transitioning into the stage and being processed by the actions in that stage (inbound), or prevented from transitioning from the stage after they have been processed by the actions in that stage (outbound). public let transitionType: StageTransitionType public init(pipelineName: String, reason: String, stageName: String, transitionType: StageTransitionType) { self.pipelineName = pipelineName self.reason = reason self.stageName = stageName self.transitionType = transitionType } public func validate(name: String) throws { try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.reason, name: "reason", parent: name, max: 300) try self.validate(self.reason, name: "reason", parent: name, min: 1) try self.validate(self.reason, name: "reason", parent: name, pattern: "[a-zA-Z0-9!@ \\(\\)\\.\\*\\?\\-]+") try self.validate(self.stageName, name: "stageName", parent: name, max: 100) try self.validate(self.stageName, name: "stageName", parent: name, min: 1) try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case pipelineName case reason case stageName case transitionType } } public struct EnableStageTransitionInput: AWSEncodableShape { /// The name of the pipeline in which you want to enable the flow of artifacts from one stage to another. public let pipelineName: String /// The name of the stage where you want to enable the transition of artifacts, either into the stage (inbound) or from that stage to the next stage (outbound). public let stageName: String /// Specifies whether artifacts are allowed to enter the stage and be processed by the actions in that stage (inbound) or whether already processed artifacts are allowed to transition to the next stage (outbound). public let transitionType: StageTransitionType public init(pipelineName: String, stageName: String, transitionType: StageTransitionType) { self.pipelineName = pipelineName self.stageName = stageName self.transitionType = transitionType } public func validate(name: String) throws { try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.stageName, name: "stageName", parent: name, max: 100) try self.validate(self.stageName, name: "stageName", parent: name, min: 1) try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case pipelineName case stageName case transitionType } } public struct EncryptionKey: AWSEncodableShape & AWSDecodableShape { /// The ID used to identify the key. For an AWS KMS key, you can use the key ID, the key ARN, or the alias ARN. Aliases are recognized only in the account that created the customer master key (CMK). For cross-account actions, you can only use the key ID or key ARN to identify the key. public let id: String /// The type of encryption key, such as an AWS Key Management Service (AWS KMS) key. When creating or updating a pipeline, the value must be set to 'KMS'. public let type: EncryptionKeyType public init(id: String, type: EncryptionKeyType) { self.id = id self.type = type } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case id case type } } public struct ErrorDetails: AWSDecodableShape { /// The system ID or number code of the error. public let code: String? /// The text of the error message. public let message: String? public init(code: String? = nil, message: String? = nil) { self.code = code self.message = message } private enum CodingKeys: String, CodingKey { case code case message } } public struct ExecutionDetails: AWSEncodableShape { /// The system-generated unique ID of this action used to identify this job worker in any external systems, such as AWS CodeDeploy. public let externalExecutionId: String? /// The percentage of work completed on the action, represented on a scale of 0 to 100 percent. public let percentComplete: Int? /// The summary of the current status of the actions. public let summary: String? public init(externalExecutionId: String? = nil, percentComplete: Int? = nil, summary: String? = nil) { self.externalExecutionId = externalExecutionId self.percentComplete = percentComplete self.summary = summary } public func validate(name: String) throws { try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, max: 1500) try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, min: 1) try self.validate(self.percentComplete, name: "percentComplete", parent: name, max: 100) try self.validate(self.percentComplete, name: "percentComplete", parent: name, min: 0) try self.validate(self.summary, name: "summary", parent: name, max: 2048) try self.validate(self.summary, name: "summary", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case externalExecutionId case percentComplete case summary } } public struct ExecutionTrigger: AWSDecodableShape { /// Detail related to the event that started a pipeline execution, such as the webhook ARN of the webhook that triggered the pipeline execution or the user ARN for a user-initiated start-pipeline-execution CLI command. public let triggerDetail: String? /// The type of change-detection method, command, or user interaction that started a pipeline execution. public let triggerType: TriggerType? public init(triggerDetail: String? = nil, triggerType: TriggerType? = nil) { self.triggerDetail = triggerDetail self.triggerType = triggerType } private enum CodingKeys: String, CodingKey { case triggerDetail case triggerType } } public struct FailureDetails: AWSEncodableShape { /// The external ID of the run of the action that failed. public let externalExecutionId: String? /// The message about the failure. public let message: String /// The type of the failure. public let type: FailureType public init(externalExecutionId: String? = nil, message: String, type: FailureType) { self.externalExecutionId = externalExecutionId self.message = message self.type = type } public func validate(name: String) throws { try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, max: 1500) try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, min: 1) try self.validate(self.message, name: "message", parent: name, max: 5000) try self.validate(self.message, name: "message", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case externalExecutionId case message case type } } public struct GetJobDetailsInput: AWSEncodableShape { /// The unique system-generated ID for the job. public let jobId: String public init(jobId: String) { self.jobId = jobId } public func validate(name: String) throws { try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case jobId } } public struct GetJobDetailsOutput: AWSDecodableShape { /// The details of the job. If AWSSessionCredentials is used, a long-running job can call GetJobDetails again to obtain new credentials. public let jobDetails: JobDetails? public init(jobDetails: JobDetails? = nil) { self.jobDetails = jobDetails } private enum CodingKeys: String, CodingKey { case jobDetails } } public struct GetPipelineExecutionInput: AWSEncodableShape { /// The ID of the pipeline execution about which you want to get execution details. public let pipelineExecutionId: String /// The name of the pipeline about which you want to get execution details. public let pipelineName: String public init(pipelineExecutionId: String, pipelineName: String) { self.pipelineExecutionId = pipelineExecutionId self.pipelineName = pipelineName } public func validate(name: String) throws { try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case pipelineExecutionId case pipelineName } } public struct GetPipelineExecutionOutput: AWSDecodableShape { /// Represents information about the execution of a pipeline. public let pipelineExecution: PipelineExecution? public init(pipelineExecution: PipelineExecution? = nil) { self.pipelineExecution = pipelineExecution } private enum CodingKeys: String, CodingKey { case pipelineExecution } } public struct GetPipelineInput: AWSEncodableShape { /// The name of the pipeline for which you want to get information. Pipeline names must be unique under an AWS user account. public let name: String /// The version number of the pipeline. If you do not specify a version, defaults to the current version. public let version: Int? public init(name: String, version: Int? = nil) { self.name = name self.version = version } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.version, name: "version", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name case version } } public struct GetPipelineOutput: AWSDecodableShape { /// Represents the pipeline metadata information returned as part of the output of a GetPipeline action. public let metadata: PipelineMetadata? /// Represents the structure of actions and stages to be performed in the pipeline. public let pipeline: PipelineDeclaration? public init(metadata: PipelineMetadata? = nil, pipeline: PipelineDeclaration? = nil) { self.metadata = metadata self.pipeline = pipeline } private enum CodingKeys: String, CodingKey { case metadata case pipeline } } public struct GetPipelineStateInput: AWSEncodableShape { /// The name of the pipeline about which you want to get information. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case name } } public struct GetPipelineStateOutput: AWSDecodableShape { /// The date and time the pipeline was created, in timestamp format. public let created: Date? /// The name of the pipeline for which you want to get the state. public let pipelineName: String? /// The version number of the pipeline. A newly created pipeline is always assigned a version number of 1. public let pipelineVersion: Int? /// A list of the pipeline stage output information, including stage name, state, most recent run details, whether the stage is disabled, and other data. public let stageStates: [StageState]? /// The date and time the pipeline was last updated, in timestamp format. public let updated: Date? public init(created: Date? = nil, pipelineName: String? = nil, pipelineVersion: Int? = nil, stageStates: [StageState]? = nil, updated: Date? = nil) { self.created = created self.pipelineName = pipelineName self.pipelineVersion = pipelineVersion self.stageStates = stageStates self.updated = updated } private enum CodingKeys: String, CodingKey { case created case pipelineName case pipelineVersion case stageStates case updated } } public struct GetThirdPartyJobDetailsInput: AWSEncodableShape { /// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details. public let clientToken: String /// The unique system-generated ID used for identifying the job. public let jobId: String public init(clientToken: String, jobId: String) { self.clientToken = clientToken self.jobId = jobId } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.jobId, name: "jobId", parent: name, max: 512) try self.validate(self.jobId, name: "jobId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken case jobId } } public struct GetThirdPartyJobDetailsOutput: AWSDecodableShape { /// The details of the job, including any protected values defined for the job. public let jobDetails: ThirdPartyJobDetails? public init(jobDetails: ThirdPartyJobDetails? = nil) { self.jobDetails = jobDetails } private enum CodingKeys: String, CodingKey { case jobDetails } } public struct InputArtifact: AWSEncodableShape & AWSDecodableShape { /// The name of the artifact to be worked on (for example, "My App"). The input artifact of an action must exactly match the output artifact declared in a preceding action, but the input artifact does not have to be the next action in strict sequence from the action that provided the output artifact. Actions in parallel can declare different output artifacts, which are in turn consumed by different following actions. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_\\-]+") } private enum CodingKeys: String, CodingKey { case name } } public struct Job: AWSDecodableShape { /// The ID of the AWS account to use when performing the job. public let accountId: String? /// Other data about a job. public let data: JobData? /// The unique system-generated ID of the job. public let id: String? /// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Use this number in an AcknowledgeJob request. public let nonce: String? public init(accountId: String? = nil, data: JobData? = nil, id: String? = nil, nonce: String? = nil) { self.accountId = accountId self.data = data self.id = id self.nonce = nonce } private enum CodingKeys: String, CodingKey { case accountId case data case id case nonce } } public struct JobData: AWSDecodableShape { /// Represents information about an action configuration. public let actionConfiguration: ActionConfiguration? /// Represents information about an action type. public let actionTypeId: ActionTypeId? /// Represents an AWS session credentials object. These credentials are temporary credentials that are issued by AWS Secure Token Service (STS). They can be used to access input and output artifacts in the S3 bucket used to store artifacts for the pipeline in AWS CodePipeline. public let artifactCredentials: AWSSessionCredentials? /// A system-generated token, such as a AWS CodeDeploy deployment ID, required by a job to continue the job asynchronously. public let continuationToken: String? /// Represents information about the key used to encrypt data in the artifact store, such as an AWS Key Management Service (AWS KMS) key. public let encryptionKey: EncryptionKey? /// The artifact supplied to the job. public let inputArtifacts: [Artifact]? /// The output of the job. public let outputArtifacts: [Artifact]? /// Represents information about a pipeline to a job worker. Includes pipelineArn and pipelineExecutionId for custom jobs. public let pipelineContext: PipelineContext? public init(actionConfiguration: ActionConfiguration? = nil, actionTypeId: ActionTypeId? = nil, artifactCredentials: AWSSessionCredentials? = nil, continuationToken: String? = nil, encryptionKey: EncryptionKey? = nil, inputArtifacts: [Artifact]? = nil, outputArtifacts: [Artifact]? = nil, pipelineContext: PipelineContext? = nil) { self.actionConfiguration = actionConfiguration self.actionTypeId = actionTypeId self.artifactCredentials = artifactCredentials self.continuationToken = continuationToken self.encryptionKey = encryptionKey self.inputArtifacts = inputArtifacts self.outputArtifacts = outputArtifacts self.pipelineContext = pipelineContext } private enum CodingKeys: String, CodingKey { case actionConfiguration case actionTypeId case artifactCredentials case continuationToken case encryptionKey case inputArtifacts case outputArtifacts case pipelineContext } } public struct JobDetails: AWSDecodableShape { /// The AWS account ID associated with the job. public let accountId: String? /// Represents other information about a job required for a job worker to complete the job. public let data: JobData? /// The unique system-generated ID of the job. public let id: String? public init(accountId: String? = nil, data: JobData? = nil, id: String? = nil) { self.accountId = accountId self.data = data self.id = id } private enum CodingKeys: String, CodingKey { case accountId case data case id } } public struct ListActionExecutionsInput: AWSEncodableShape { /// Input information used to filter action execution history. public let filter: ActionExecutionFilter? /// The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value. Action execution history is retained for up to 12 months, based on action execution start times. Default value is 100. Detailed execution history is available for executions run on or after February 21, 2019. public let maxResults: Int? /// The token that was returned from the previous ListActionExecutions call, which can be used to return the next set of action executions in the list. public let nextToken: String? /// The name of the pipeline for which you want to list action execution history. public let pipelineName: String public init(filter: ActionExecutionFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil, pipelineName: String) { self.filter = filter self.maxResults = maxResults self.nextToken = nextToken self.pipelineName = pipelineName } public func validate(name: String) throws { try self.filter?.validate(name: "\(name).filter") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case filter case maxResults case nextToken case pipelineName } } public struct ListActionExecutionsOutput: AWSDecodableShape { /// The details for a list of recent executions, such as action execution ID. public let actionExecutionDetails: [ActionExecutionDetail]? /// If the amount of returned information is significantly large, an identifier is also returned and can be used in a subsequent ListActionExecutions call to return the next set of action executions in the list. public let nextToken: String? public init(actionExecutionDetails: [ActionExecutionDetail]? = nil, nextToken: String? = nil) { self.actionExecutionDetails = actionExecutionDetails self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case actionExecutionDetails case nextToken } } public struct ListActionTypesInput: AWSEncodableShape { /// Filters the list of action types to those created by a specified entity. public let actionOwnerFilter: ActionOwner? /// An identifier that was returned from the previous list action types call, which can be used to return the next set of action types in the list. public let nextToken: String? public init(actionOwnerFilter: ActionOwner? = nil, nextToken: String? = nil) { self.actionOwnerFilter = actionOwnerFilter self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case actionOwnerFilter case nextToken } } public struct ListActionTypesOutput: AWSDecodableShape { /// Provides details of the action types. public let actionTypes: [ActionType] /// If the amount of returned information is significantly large, an identifier is also returned. It can be used in a subsequent list action types call to return the next set of action types in the list. public let nextToken: String? public init(actionTypes: [ActionType], nextToken: String? = nil) { self.actionTypes = actionTypes self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case actionTypes case nextToken } } public struct ListPipelineExecutionsInput: AWSEncodableShape { /// The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value. Pipeline history is limited to the most recent 12 months, based on pipeline execution start times. Default value is 100. public let maxResults: Int? /// The token that was returned from the previous ListPipelineExecutions call, which can be used to return the next set of pipeline executions in the list. public let nextToken: String? /// The name of the pipeline for which you want to get execution summary information. public let pipelineName: String public init(maxResults: Int? = nil, nextToken: String? = nil, pipelineName: String) { self.maxResults = maxResults self.nextToken = nextToken self.pipelineName = pipelineName } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken case pipelineName } } public struct ListPipelineExecutionsOutput: AWSDecodableShape { /// A token that can be used in the next ListPipelineExecutions call. To view all items in the list, continue to call this operation with each subsequent token until no more nextToken values are returned. public let nextToken: String? /// A list of executions in the history of a pipeline. public let pipelineExecutionSummaries: [PipelineExecutionSummary]? public init(nextToken: String? = nil, pipelineExecutionSummaries: [PipelineExecutionSummary]? = nil) { self.nextToken = nextToken self.pipelineExecutionSummaries = pipelineExecutionSummaries } private enum CodingKeys: String, CodingKey { case nextToken case pipelineExecutionSummaries } } public struct ListPipelinesInput: AWSEncodableShape { /// An identifier that was returned from the previous list pipelines call. It can be used to return the next set of pipelines in the list. public let nextToken: String? public init(nextToken: String? = nil) { self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case nextToken } } public struct ListPipelinesOutput: AWSDecodableShape { /// If the amount of returned information is significantly large, an identifier is also returned. It can be used in a subsequent list pipelines call to return the next set of pipelines in the list. public let nextToken: String? /// The list of pipelines. public let pipelines: [PipelineSummary]? public init(nextToken: String? = nil, pipelines: [PipelineSummary]? = nil) { self.nextToken = nextToken self.pipelines = pipelines } private enum CodingKeys: String, CodingKey { case nextToken case pipelines } } public struct ListTagsForResourceInput: AWSEncodableShape { /// The maximum number of results to return in a single call. public let maxResults: Int? /// The token that was returned from the previous API call, which would be used to return the next page of the list. The ListTagsforResource call lists all available tags in one call and does not use pagination. public let nextToken: String? /// The Amazon Resource Name (ARN) of the resource to get tags for. public let resourceArn: String public init(maxResults: Int? = nil, nextToken: String? = nil, resourceArn: String) { self.maxResults = maxResults self.nextToken = nextToken self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "arn:aws(-[\\w]+)*:codepipeline:.+:[0-9]{12}:.+") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken case resourceArn } } public struct ListTagsForResourceOutput: AWSDecodableShape { /// If the amount of returned information is significantly large, an identifier is also returned and can be used in a subsequent API call to return the next page of the list. The ListTagsforResource call lists all available tags in one call and does not use pagination. public let nextToken: String? /// The tags for the resource. public let tags: [Tag]? public init(nextToken: String? = nil, tags: [Tag]? = nil) { self.nextToken = nextToken self.tags = tags } private enum CodingKeys: String, CodingKey { case nextToken case tags } } public struct ListWebhookItem: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the webhook. public let arn: String? /// The detail returned for each webhook, such as the webhook authentication type and filter rules. public let definition: WebhookDefinition /// The number code of the error. public let errorCode: String? /// The text of the error message about the webhook. public let errorMessage: String? /// The date and time a webhook was last successfully triggered, in timestamp format. public let lastTriggered: Date? /// Specifies the tags applied to the webhook. public let tags: [Tag]? /// A unique URL generated by CodePipeline. When a POST request is made to this URL, the defined pipeline is started as long as the body of the post request satisfies the defined authentication and filtering conditions. Deleting and re-creating a webhook makes the old URL invalid and generates a new one. public let url: String public init(arn: String? = nil, definition: WebhookDefinition, errorCode: String? = nil, errorMessage: String? = nil, lastTriggered: Date? = nil, tags: [Tag]? = nil, url: String) { self.arn = arn self.definition = definition self.errorCode = errorCode self.errorMessage = errorMessage self.lastTriggered = lastTriggered self.tags = tags self.url = url } private enum CodingKeys: String, CodingKey { case arn case definition case errorCode case errorMessage case lastTriggered case tags case url } } public struct ListWebhooksInput: AWSEncodableShape { /// The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value. public let maxResults: Int? /// The token that was returned from the previous ListWebhooks call, which can be used to return the next set of webhooks in the list. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListWebhooksOutput: AWSDecodableShape { /// If the amount of returned information is significantly large, an identifier is also returned and can be used in a subsequent ListWebhooks call to return the next set of webhooks in the list. public let nextToken: String? /// The JSON detail returned for each webhook in the list output for the ListWebhooks call. public let webhooks: [ListWebhookItem]? public init(nextToken: String? = nil, webhooks: [ListWebhookItem]? = nil) { self.nextToken = nextToken self.webhooks = webhooks } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case webhooks } } public struct OutputArtifact: AWSEncodableShape & AWSDecodableShape { /// The name of the output of an artifact, such as "My App". The input artifact of an action must exactly match the output artifact declared in a preceding action, but the input artifact does not have to be the next action in strict sequence from the action that provided the output artifact. Actions in parallel can declare different output artifacts, which are in turn consumed by different following actions. Output artifact names must be unique within a pipeline. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_\\-]+") } private enum CodingKeys: String, CodingKey { case name } } public struct PipelineContext: AWSDecodableShape { /// The context of an action to a job worker in the stage of a pipeline. public let action: ActionContext? /// The Amazon Resource Name (ARN) of the pipeline. public let pipelineArn: String? /// The execution ID of the pipeline. public let pipelineExecutionId: String? /// The name of the pipeline. This is a user-specified value. Pipeline names must be unique across all pipeline names under an Amazon Web Services account. public let pipelineName: String? /// The stage of the pipeline. public let stage: StageContext? public init(action: ActionContext? = nil, pipelineArn: String? = nil, pipelineExecutionId: String? = nil, pipelineName: String? = nil, stage: StageContext? = nil) { self.action = action self.pipelineArn = pipelineArn self.pipelineExecutionId = pipelineExecutionId self.pipelineName = pipelineName self.stage = stage } private enum CodingKeys: String, CodingKey { case action case pipelineArn case pipelineExecutionId case pipelineName case stage } } public struct PipelineDeclaration: AWSEncodableShape & AWSDecodableShape { /// Represents information about the S3 bucket where artifacts are stored for the pipeline. You must include either artifactStore or artifactStores in your pipeline, but you cannot use both. If you create a cross-region action in your pipeline, you must use artifactStores. public let artifactStore: ArtifactStore? /// A mapping of artifactStore objects and their corresponding AWS Regions. There must be an artifact store for the pipeline Region and for each cross-region action in the pipeline. You must include either artifactStore or artifactStores in your pipeline, but you cannot use both. If you create a cross-region action in your pipeline, you must use artifactStores. public let artifactStores: [String: ArtifactStore]? /// The name of the action to be performed. public let name: String /// The Amazon Resource Name (ARN) for AWS CodePipeline to use to either perform actions with no actionRoleArn, or to use to assume roles for actions with an actionRoleArn. public let roleArn: String /// The stage in which to perform the action. public let stages: [StageDeclaration] /// The version number of the pipeline. A new pipeline always has a version number of 1. This number is incremented when a pipeline is updated. public let version: Int? public init(artifactStore: ArtifactStore? = nil, artifactStores: [String: ArtifactStore]? = nil, name: String, roleArn: String, stages: [StageDeclaration], version: Int? = nil) { self.artifactStore = artifactStore self.artifactStores = artifactStores self.name = name self.roleArn = roleArn self.stages = stages self.version = version } public func validate(name: String) throws { try self.artifactStore?.validate(name: "\(name).artifactStore") try self.artifactStores?.forEach { try validate($0.key, name: "artifactStores.key", parent: name, max: 30) try validate($0.key, name: "artifactStores.key", parent: name, min: 4) try $0.value.validate(name: "\(name).artifactStores[\"\($0.key)\"]") } try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1024) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:aws(-[\\w]+)*:iam::[0-9]{12}:role/.*") try self.stages.forEach { try $0.validate(name: "\(name).stages[]") } try self.validate(self.version, name: "version", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case artifactStore case artifactStores case name case roleArn case stages case version } } public struct PipelineExecution: AWSDecodableShape { /// A list of ArtifactRevision objects included in a pipeline execution. public let artifactRevisions: [ArtifactRevision]? /// The ID of the pipeline execution. public let pipelineExecutionId: String? /// The name of the pipeline with the specified pipeline execution. public let pipelineName: String? /// The version number of the pipeline with the specified pipeline execution. public let pipelineVersion: Int? /// The status of the pipeline execution. InProgress: The pipeline execution is currently running. Stopped: The pipeline execution was manually stopped. For more information, see Stopped Executions. Stopping: The pipeline execution received a request to be manually stopped. Depending on the selected stop mode, the execution is either completing or abandoning in-progress actions. For more information, see Stopped Executions. Succeeded: The pipeline execution was completed successfully. Superseded: While this pipeline execution was waiting for the next stage to be completed, a newer pipeline execution advanced and continued through the pipeline instead. For more information, see Superseded Executions. Failed: The pipeline execution was not completed successfully. public let status: PipelineExecutionStatus? public init(artifactRevisions: [ArtifactRevision]? = nil, pipelineExecutionId: String? = nil, pipelineName: String? = nil, pipelineVersion: Int? = nil, status: PipelineExecutionStatus? = nil) { self.artifactRevisions = artifactRevisions self.pipelineExecutionId = pipelineExecutionId self.pipelineName = pipelineName self.pipelineVersion = pipelineVersion self.status = status } private enum CodingKeys: String, CodingKey { case artifactRevisions case pipelineExecutionId case pipelineName case pipelineVersion case status } } public struct PipelineExecutionSummary: AWSDecodableShape { /// The date and time of the last change to the pipeline execution, in timestamp format. public let lastUpdateTime: Date? /// The ID of the pipeline execution. public let pipelineExecutionId: String? /// A list of the source artifact revisions that initiated a pipeline execution. public let sourceRevisions: [SourceRevision]? /// The date and time when the pipeline execution began, in timestamp format. public let startTime: Date? /// The status of the pipeline execution. InProgress: The pipeline execution is currently running. Stopped: The pipeline execution was manually stopped. For more information, see Stopped Executions. Stopping: The pipeline execution received a request to be manually stopped. Depending on the selected stop mode, the execution is either completing or abandoning in-progress actions. For more information, see Stopped Executions. Succeeded: The pipeline execution was completed successfully. Superseded: While this pipeline execution was waiting for the next stage to be completed, a newer pipeline execution advanced and continued through the pipeline instead. For more information, see Superseded Executions. Failed: The pipeline execution was not completed successfully. public let status: PipelineExecutionStatus? /// The interaction that stopped a pipeline execution. public let stopTrigger: StopExecutionTrigger? /// The interaction or event that started a pipeline execution, such as automated change detection or a StartPipelineExecution API call. public let trigger: ExecutionTrigger? public init(lastUpdateTime: Date? = nil, pipelineExecutionId: String? = nil, sourceRevisions: [SourceRevision]? = nil, startTime: Date? = nil, status: PipelineExecutionStatus? = nil, stopTrigger: StopExecutionTrigger? = nil, trigger: ExecutionTrigger? = nil) { self.lastUpdateTime = lastUpdateTime self.pipelineExecutionId = pipelineExecutionId self.sourceRevisions = sourceRevisions self.startTime = startTime self.status = status self.stopTrigger = stopTrigger self.trigger = trigger } private enum CodingKeys: String, CodingKey { case lastUpdateTime case pipelineExecutionId case sourceRevisions case startTime case status case stopTrigger case trigger } } public struct PipelineMetadata: AWSDecodableShape { /// The date and time the pipeline was created, in timestamp format. public let created: Date? /// The Amazon Resource Name (ARN) of the pipeline. public let pipelineArn: String? /// The date and time the pipeline was last updated, in timestamp format. public let updated: Date? public init(created: Date? = nil, pipelineArn: String? = nil, updated: Date? = nil) { self.created = created self.pipelineArn = pipelineArn self.updated = updated } private enum CodingKeys: String, CodingKey { case created case pipelineArn case updated } } public struct PipelineSummary: AWSDecodableShape { /// The date and time the pipeline was created, in timestamp format. public let created: Date? /// The name of the pipeline. public let name: String? /// The date and time of the last update to the pipeline, in timestamp format. public let updated: Date? /// The version number of the pipeline. public let version: Int? public init(created: Date? = nil, name: String? = nil, updated: Date? = nil, version: Int? = nil) { self.created = created self.name = name self.updated = updated self.version = version } private enum CodingKeys: String, CodingKey { case created case name case updated case version } } public struct PollForJobsInput: AWSEncodableShape { /// Represents information about an action type. public let actionTypeId: ActionTypeId /// The maximum number of jobs to return in a poll for jobs call. public let maxBatchSize: Int? /// A map of property names and values. For an action type with no queryable properties, this value must be null or an empty map. For an action type with a queryable property, you must supply that property as a key in the map. Only jobs whose action configuration matches the mapped value are returned. public let queryParam: [String: String]? public init(actionTypeId: ActionTypeId, maxBatchSize: Int? = nil, queryParam: [String: String]? = nil) { self.actionTypeId = actionTypeId self.maxBatchSize = maxBatchSize self.queryParam = queryParam } public func validate(name: String) throws { try self.actionTypeId.validate(name: "\(name).actionTypeId") try self.validate(self.maxBatchSize, name: "maxBatchSize", parent: name, min: 1) try self.queryParam?.forEach { try validate($0.key, name: "queryParam.key", parent: name, max: 50) try validate($0.key, name: "queryParam.key", parent: name, min: 1) try validate($0.value, name: "queryParam[\"\($0.key)\"]", parent: name, max: 50) try validate($0.value, name: "queryParam[\"\($0.key)\"]", parent: name, min: 1) try validate($0.value, name: "queryParam[\"\($0.key)\"]", parent: name, pattern: "[a-zA-Z0-9_-]+") } } private enum CodingKeys: String, CodingKey { case actionTypeId case maxBatchSize case queryParam } } public struct PollForJobsOutput: AWSDecodableShape { /// Information about the jobs to take action on. public let jobs: [Job]? public init(jobs: [Job]? = nil) { self.jobs = jobs } private enum CodingKeys: String, CodingKey { case jobs } } public struct PollForThirdPartyJobsInput: AWSEncodableShape { /// Represents information about an action type. public let actionTypeId: ActionTypeId /// The maximum number of jobs to return in a poll for jobs call. public let maxBatchSize: Int? public init(actionTypeId: ActionTypeId, maxBatchSize: Int? = nil) { self.actionTypeId = actionTypeId self.maxBatchSize = maxBatchSize } public func validate(name: String) throws { try self.actionTypeId.validate(name: "\(name).actionTypeId") try self.validate(self.maxBatchSize, name: "maxBatchSize", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case actionTypeId case maxBatchSize } } public struct PollForThirdPartyJobsOutput: AWSDecodableShape { /// Information about the jobs to take action on. public let jobs: [ThirdPartyJob]? public init(jobs: [ThirdPartyJob]? = nil) { self.jobs = jobs } private enum CodingKeys: String, CodingKey { case jobs } } public struct PutActionRevisionInput: AWSEncodableShape { /// The name of the action that processes the revision. public let actionName: String /// Represents information about the version (or revision) of an action. public let actionRevision: ActionRevision /// The name of the pipeline that starts processing the revision to the source. public let pipelineName: String /// The name of the stage that contains the action that acts on the revision. public let stageName: String public init(actionName: String, actionRevision: ActionRevision, pipelineName: String, stageName: String) { self.actionName = actionName self.actionRevision = actionRevision self.pipelineName = pipelineName self.stageName = stageName } public func validate(name: String) throws { try self.validate(self.actionName, name: "actionName", parent: name, max: 100) try self.validate(self.actionName, name: "actionName", parent: name, min: 1) try self.validate(self.actionName, name: "actionName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.actionRevision.validate(name: "\(name).actionRevision") try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.stageName, name: "stageName", parent: name, max: 100) try self.validate(self.stageName, name: "stageName", parent: name, min: 1) try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case actionName case actionRevision case pipelineName case stageName } } public struct PutActionRevisionOutput: AWSDecodableShape { /// Indicates whether the artifact revision was previously used in an execution of the specified pipeline. public let newRevision: Bool? /// The ID of the current workflow state of the pipeline. public let pipelineExecutionId: String? public init(newRevision: Bool? = nil, pipelineExecutionId: String? = nil) { self.newRevision = newRevision self.pipelineExecutionId = pipelineExecutionId } private enum CodingKeys: String, CodingKey { case newRevision case pipelineExecutionId } } public struct PutApprovalResultInput: AWSEncodableShape { /// The name of the action for which approval is requested. public let actionName: String /// The name of the pipeline that contains the action. public let pipelineName: String /// Represents information about the result of the approval request. public let result: ApprovalResult /// The name of the stage that contains the action. public let stageName: String /// The system-generated token used to identify a unique approval request. The token for each open approval request can be obtained using the GetPipelineState action. It is used to validate that the approval request corresponding to this token is still valid. public let token: String public init(actionName: String, pipelineName: String, result: ApprovalResult, stageName: String, token: String) { self.actionName = actionName self.pipelineName = pipelineName self.result = result self.stageName = stageName self.token = token } public func validate(name: String) throws { try self.validate(self.actionName, name: "actionName", parent: name, max: 100) try self.validate(self.actionName, name: "actionName", parent: name, min: 1) try self.validate(self.actionName, name: "actionName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.result.validate(name: "\(name).result") try self.validate(self.stageName, name: "stageName", parent: name, max: 100) try self.validate(self.stageName, name: "stageName", parent: name, min: 1) try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.token, name: "token", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case actionName case pipelineName case result case stageName case token } } public struct PutApprovalResultOutput: AWSDecodableShape { /// The timestamp showing when the approval or rejection was submitted. public let approvedAt: Date? public init(approvedAt: Date? = nil) { self.approvedAt = approvedAt } private enum CodingKeys: String, CodingKey { case approvedAt } } public struct PutJobFailureResultInput: AWSEncodableShape { /// The details about the failure of a job. public let failureDetails: FailureDetails /// The unique system-generated ID of the job that failed. This is the same ID returned from PollForJobs. public let jobId: String public init(failureDetails: FailureDetails, jobId: String) { self.failureDetails = failureDetails self.jobId = jobId } public func validate(name: String) throws { try self.failureDetails.validate(name: "\(name).failureDetails") try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case failureDetails case jobId } } public struct PutJobSuccessResultInput: AWSEncodableShape { /// A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to identify a custom action in progress. Future jobs use this token to identify the running instance of the action. It can be reused to return more information about the progress of the custom action. When the action is complete, no continuation token should be supplied. public let continuationToken: String? /// The ID of the current revision of the artifact successfully worked on by the job. public let currentRevision: CurrentRevision? /// The execution details of the successful job, such as the actions taken by the job worker. public let executionDetails: ExecutionDetails? /// The unique system-generated ID of the job that succeeded. This is the same ID returned from PollForJobs. public let jobId: String /// Key-value pairs produced as output by a job worker that can be made available to a downstream action configuration. outputVariables can be included only when there is no continuation token on the request. public let outputVariables: [String: String]? public init(continuationToken: String? = nil, currentRevision: CurrentRevision? = nil, executionDetails: ExecutionDetails? = nil, jobId: String, outputVariables: [String: String]? = nil) { self.continuationToken = continuationToken self.currentRevision = currentRevision self.executionDetails = executionDetails self.jobId = jobId self.outputVariables = outputVariables } public func validate(name: String) throws { try self.validate(self.continuationToken, name: "continuationToken", parent: name, max: 2048) try self.validate(self.continuationToken, name: "continuationToken", parent: name, min: 1) try self.currentRevision?.validate(name: "\(name).currentRevision") try self.executionDetails?.validate(name: "\(name).executionDetails") try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.outputVariables?.forEach { try validate($0.key, name: "outputVariables.key", parent: name, pattern: "[A-Za-z0-9@\\-_]+") } } private enum CodingKeys: String, CodingKey { case continuationToken case currentRevision case executionDetails case jobId case outputVariables } } public struct PutThirdPartyJobFailureResultInput: AWSEncodableShape { /// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details. public let clientToken: String /// Represents information about failure details. public let failureDetails: FailureDetails /// The ID of the job that failed. This is the same ID returned from PollForThirdPartyJobs. public let jobId: String public init(clientToken: String, failureDetails: FailureDetails, jobId: String) { self.clientToken = clientToken self.failureDetails = failureDetails self.jobId = jobId } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.failureDetails.validate(name: "\(name).failureDetails") try self.validate(self.jobId, name: "jobId", parent: name, max: 512) try self.validate(self.jobId, name: "jobId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken case failureDetails case jobId } } public struct PutThirdPartyJobSuccessResultInput: AWSEncodableShape { /// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details. public let clientToken: String /// A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to identify a partner action in progress. Future jobs use this token to identify the running instance of the action. It can be reused to return more information about the progress of the partner action. When the action is complete, no continuation token should be supplied. public let continuationToken: String? /// Represents information about a current revision. public let currentRevision: CurrentRevision? /// The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline. public let executionDetails: ExecutionDetails? /// The ID of the job that successfully completed. This is the same ID returned from PollForThirdPartyJobs. public let jobId: String public init(clientToken: String, continuationToken: String? = nil, currentRevision: CurrentRevision? = nil, executionDetails: ExecutionDetails? = nil, jobId: String) { self.clientToken = clientToken self.continuationToken = continuationToken self.currentRevision = currentRevision self.executionDetails = executionDetails self.jobId = jobId } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.continuationToken, name: "continuationToken", parent: name, max: 2048) try self.validate(self.continuationToken, name: "continuationToken", parent: name, min: 1) try self.currentRevision?.validate(name: "\(name).currentRevision") try self.executionDetails?.validate(name: "\(name).executionDetails") try self.validate(self.jobId, name: "jobId", parent: name, max: 512) try self.validate(self.jobId, name: "jobId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken case continuationToken case currentRevision case executionDetails case jobId } } public struct PutWebhookInput: AWSEncodableShape { /// The tags for the webhook. public let tags: [Tag]? /// The detail provided in an input file to create the webhook, such as the webhook name, the pipeline name, and the action name. Give the webhook a unique name that helps you identify it. You might name the webhook after the pipeline and action it targets so that you can easily recognize what it's used for later. public let webhook: WebhookDefinition public init(tags: [Tag]? = nil, webhook: WebhookDefinition) { self.tags = tags self.webhook = webhook } public func validate(name: String) throws { try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.webhook.validate(name: "\(name).webhook") } private enum CodingKeys: String, CodingKey { case tags case webhook } } public struct PutWebhookOutput: AWSDecodableShape { /// The detail returned from creating the webhook, such as the webhook name, webhook URL, and webhook ARN. public let webhook: ListWebhookItem? public init(webhook: ListWebhookItem? = nil) { self.webhook = webhook } private enum CodingKeys: String, CodingKey { case webhook } } public struct RegisterWebhookWithThirdPartyInput: AWSEncodableShape { /// The name of an existing webhook created with PutWebhook to register with a supported third party. public let webhookName: String? public init(webhookName: String? = nil) { self.webhookName = webhookName } public func validate(name: String) throws { try self.validate(self.webhookName, name: "webhookName", parent: name, max: 100) try self.validate(self.webhookName, name: "webhookName", parent: name, min: 1) try self.validate(self.webhookName, name: "webhookName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case webhookName } } public struct RegisterWebhookWithThirdPartyOutput: AWSDecodableShape { public init() {} } public struct RetryStageExecutionInput: AWSEncodableShape { /// The ID of the pipeline execution in the failed stage to be retried. Use the GetPipelineState action to retrieve the current pipelineExecutionId of the failed stage public let pipelineExecutionId: String /// The name of the pipeline that contains the failed stage. public let pipelineName: String /// The scope of the retry attempt. Currently, the only supported value is FAILED_ACTIONS. public let retryMode: StageRetryMode /// The name of the failed stage to be retried. public let stageName: String public init(pipelineExecutionId: String, pipelineName: String, retryMode: StageRetryMode, stageName: String) { self.pipelineExecutionId = pipelineExecutionId self.pipelineName = pipelineName self.retryMode = retryMode self.stageName = stageName } public func validate(name: String) throws { try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.stageName, name: "stageName", parent: name, max: 100) try self.validate(self.stageName, name: "stageName", parent: name, min: 1) try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case pipelineExecutionId case pipelineName case retryMode case stageName } } public struct RetryStageExecutionOutput: AWSDecodableShape { /// The ID of the current workflow execution in the failed stage. public let pipelineExecutionId: String? public init(pipelineExecutionId: String? = nil) { self.pipelineExecutionId = pipelineExecutionId } private enum CodingKeys: String, CodingKey { case pipelineExecutionId } } public struct S3ArtifactLocation: AWSDecodableShape { /// The name of the S3 bucket. public let bucketName: String /// The key of the object in the S3 bucket, which uniquely identifies the object in the bucket. public let objectKey: String public init(bucketName: String, objectKey: String) { self.bucketName = bucketName self.objectKey = objectKey } private enum CodingKeys: String, CodingKey { case bucketName case objectKey } } public struct S3Location: AWSDecodableShape { /// The Amazon S3 artifact bucket for an action's artifacts. public let bucket: String? /// The artifact name. public let key: String? public init(bucket: String? = nil, key: String? = nil) { self.bucket = bucket self.key = key } private enum CodingKeys: String, CodingKey { case bucket case key } } public struct SourceRevision: AWSDecodableShape { /// The name of the action that processed the revision to the source artifact. public let actionName: String /// The system-generated unique ID that identifies the revision number of the artifact. public let revisionId: String? /// Summary information about the most recent revision of the artifact. For GitHub and AWS CodeCommit repositories, the commit message. For Amazon S3 buckets or actions, the user-provided content of a codepipeline-artifact-revision-summary key specified in the object metadata. public let revisionSummary: String? /// The commit ID for the artifact revision. For artifacts stored in GitHub or AWS CodeCommit repositories, the commit ID is linked to a commit details page. public let revisionUrl: String? public init(actionName: String, revisionId: String? = nil, revisionSummary: String? = nil, revisionUrl: String? = nil) { self.actionName = actionName self.revisionId = revisionId self.revisionSummary = revisionSummary self.revisionUrl = revisionUrl } private enum CodingKeys: String, CodingKey { case actionName case revisionId case revisionSummary case revisionUrl } } public struct StageContext: AWSDecodableShape { /// The name of the stage. public let name: String? public init(name: String? = nil) { self.name = name } private enum CodingKeys: String, CodingKey { case name } } public struct StageDeclaration: AWSEncodableShape & AWSDecodableShape { /// The actions included in a stage. public let actions: [ActionDeclaration] /// Reserved for future use. public let blockers: [BlockerDeclaration]? /// The name of the stage. public let name: String public init(actions: [ActionDeclaration], blockers: [BlockerDeclaration]? = nil, name: String) { self.actions = actions self.blockers = blockers self.name = name } public func validate(name: String) throws { try self.actions.forEach { try $0.validate(name: "\(name).actions[]") } try self.blockers?.forEach { try $0.validate(name: "\(name).blockers[]") } try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case actions case blockers case name } } public struct StageExecution: AWSDecodableShape { /// The ID of the pipeline execution associated with the stage. public let pipelineExecutionId: String /// The status of the stage, or for a completed stage, the last status of the stage. public let status: StageExecutionStatus public init(pipelineExecutionId: String, status: StageExecutionStatus) { self.pipelineExecutionId = pipelineExecutionId self.status = status } private enum CodingKeys: String, CodingKey { case pipelineExecutionId case status } } public struct StageState: AWSDecodableShape { /// The state of the stage. public let actionStates: [ActionState]? /// The state of the inbound transition, which is either enabled or disabled. public let inboundTransitionState: TransitionState? /// Information about the latest execution in the stage, including its ID and status. public let latestExecution: StageExecution? /// The name of the stage. public let stageName: String? public init(actionStates: [ActionState]? = nil, inboundTransitionState: TransitionState? = nil, latestExecution: StageExecution? = nil, stageName: String? = nil) { self.actionStates = actionStates self.inboundTransitionState = inboundTransitionState self.latestExecution = latestExecution self.stageName = stageName } private enum CodingKeys: String, CodingKey { case actionStates case inboundTransitionState case latestExecution case stageName } } public struct StartPipelineExecutionInput: AWSEncodableShape { /// The system-generated unique ID used to identify a unique execution request. public let clientRequestToken: String? /// The name of the pipeline to start. public let name: String public init(clientRequestToken: String? = StartPipelineExecutionInput.idempotencyToken(), name: String) { self.clientRequestToken = clientRequestToken self.name = name } public func validate(name: String) throws { try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 128) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[a-zA-Z0-9-]+$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case clientRequestToken case name } } public struct StartPipelineExecutionOutput: AWSDecodableShape { /// The unique system-generated ID of the pipeline execution that was started. public let pipelineExecutionId: String? public init(pipelineExecutionId: String? = nil) { self.pipelineExecutionId = pipelineExecutionId } private enum CodingKeys: String, CodingKey { case pipelineExecutionId } } public struct StopExecutionTrigger: AWSDecodableShape { /// The user-specified reason the pipeline was stopped. public let reason: String? public init(reason: String? = nil) { self.reason = reason } private enum CodingKeys: String, CodingKey { case reason } } public struct StopPipelineExecutionInput: AWSEncodableShape { /// Use this option to stop the pipeline execution by abandoning, rather than finishing, in-progress actions. This option can lead to failed or out-of-sequence tasks. public let abandon: Bool? /// The ID of the pipeline execution to be stopped in the current stage. Use the GetPipelineState action to retrieve the current pipelineExecutionId. public let pipelineExecutionId: String /// The name of the pipeline to stop. public let pipelineName: String /// Use this option to enter comments, such as the reason the pipeline was stopped. public let reason: String? public init(abandon: Bool? = nil, pipelineExecutionId: String, pipelineName: String, reason: String? = nil) { self.abandon = abandon self.pipelineExecutionId = pipelineExecutionId self.pipelineName = pipelineName self.reason = reason } public func validate(name: String) throws { try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100) try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1) try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.reason, name: "reason", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case abandon case pipelineExecutionId case pipelineName case reason } } public struct StopPipelineExecutionOutput: AWSDecodableShape { /// The unique system-generated ID of the pipeline execution that was stopped. public let pipelineExecutionId: String? public init(pipelineExecutionId: String? = nil) { self.pipelineExecutionId = pipelineExecutionId } private enum CodingKeys: String, CodingKey { case pipelineExecutionId } } public struct Tag: AWSEncodableShape & AWSDecodableShape { /// The tag's key. public let key: String /// The tag's value. public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 128) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.value, name: "value", parent: name, max: 256) try self.validate(self.value, name: "value", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case key case value } } public struct TagResourceInput: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the resource you want to add tags to. public let resourceArn: String /// The tags you want to modify or add to the resource. public let tags: [Tag] public init(resourceArn: String, tags: [Tag]) { self.resourceArn = resourceArn self.tags = tags } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "arn:aws(-[\\w]+)*:codepipeline:.+:[0-9]{12}:.+") try self.tags.forEach { try $0.validate(name: "\(name).tags[]") } } private enum CodingKeys: String, CodingKey { case resourceArn case tags } } public struct TagResourceOutput: AWSDecodableShape { public init() {} } public struct ThirdPartyJob: AWSDecodableShape { /// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details. public let clientId: String? /// The identifier used to identify the job in AWS CodePipeline. public let jobId: String? public init(clientId: String? = nil, jobId: String? = nil) { self.clientId = clientId self.jobId = jobId } private enum CodingKeys: String, CodingKey { case clientId case jobId } } public struct ThirdPartyJobData: AWSDecodableShape { /// Represents information about an action configuration. public let actionConfiguration: ActionConfiguration? /// Represents information about an action type. public let actionTypeId: ActionTypeId? /// Represents an AWS session credentials object. These credentials are temporary credentials that are issued by AWS Secure Token Service (STS). They can be used to access input and output artifacts in the S3 bucket used to store artifact for the pipeline in AWS CodePipeline. public let artifactCredentials: AWSSessionCredentials? /// A system-generated token, such as a AWS CodeDeploy deployment ID, that a job requires to continue the job asynchronously. public let continuationToken: String? /// The encryption key used to encrypt and decrypt data in the artifact store for the pipeline, such as an AWS Key Management Service (AWS KMS) key. This is optional and might not be present. public let encryptionKey: EncryptionKey? /// The name of the artifact that is worked on by the action, if any. This name might be system-generated, such as "MyApp", or it might be defined by the user when the action is created. The input artifact name must match the name of an output artifact generated by an action in an earlier action or stage of the pipeline. public let inputArtifacts: [Artifact]? /// The name of the artifact that is the result of the action, if any. This name might be system-generated, such as "MyBuiltApp", or it might be defined by the user when the action is created. public let outputArtifacts: [Artifact]? /// Represents information about a pipeline to a job worker. Does not include pipelineArn and pipelineExecutionId for ThirdParty jobs. public let pipelineContext: PipelineContext? public init(actionConfiguration: ActionConfiguration? = nil, actionTypeId: ActionTypeId? = nil, artifactCredentials: AWSSessionCredentials? = nil, continuationToken: String? = nil, encryptionKey: EncryptionKey? = nil, inputArtifacts: [Artifact]? = nil, outputArtifacts: [Artifact]? = nil, pipelineContext: PipelineContext? = nil) { self.actionConfiguration = actionConfiguration self.actionTypeId = actionTypeId self.artifactCredentials = artifactCredentials self.continuationToken = continuationToken self.encryptionKey = encryptionKey self.inputArtifacts = inputArtifacts self.outputArtifacts = outputArtifacts self.pipelineContext = pipelineContext } private enum CodingKeys: String, CodingKey { case actionConfiguration case actionTypeId case artifactCredentials case continuationToken case encryptionKey case inputArtifacts case outputArtifacts case pipelineContext } } public struct ThirdPartyJobDetails: AWSDecodableShape { /// The data to be returned by the third party job worker. public let data: ThirdPartyJobData? /// The identifier used to identify the job details in AWS CodePipeline. public let id: String? /// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Use this number in an AcknowledgeThirdPartyJob request. public let nonce: String? public init(data: ThirdPartyJobData? = nil, id: String? = nil, nonce: String? = nil) { self.data = data self.id = id self.nonce = nonce } private enum CodingKeys: String, CodingKey { case data case id case nonce } } public struct TransitionState: AWSDecodableShape { /// The user-specified reason why the transition between two stages of a pipeline was disabled. public let disabledReason: String? /// Whether the transition between stages is enabled (true) or disabled (false). public let enabled: Bool? /// The timestamp when the transition state was last changed. public let lastChangedAt: Date? /// The ID of the user who last changed the transition state. public let lastChangedBy: String? public init(disabledReason: String? = nil, enabled: Bool? = nil, lastChangedAt: Date? = nil, lastChangedBy: String? = nil) { self.disabledReason = disabledReason self.enabled = enabled self.lastChangedAt = lastChangedAt self.lastChangedBy = lastChangedBy } private enum CodingKeys: String, CodingKey { case disabledReason case enabled case lastChangedAt case lastChangedBy } } public struct UntagResourceInput: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the resource to remove tags from. public let resourceArn: String /// The list of keys for the tags to be removed from the resource. public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "arn:aws(-[\\w]+)*:codepipeline:.+:[0-9]{12}:.+") try self.tagKeys.forEach { try validate($0, name: "tagKeys[]", parent: name, max: 128) try validate($0, name: "tagKeys[]", parent: name, min: 1) } } private enum CodingKeys: String, CodingKey { case resourceArn case tagKeys } } public struct UntagResourceOutput: AWSDecodableShape { public init() {} } public struct UpdatePipelineInput: AWSEncodableShape { /// The name of the pipeline to be updated. public let pipeline: PipelineDeclaration public init(pipeline: PipelineDeclaration) { self.pipeline = pipeline } public func validate(name: String) throws { try self.pipeline.validate(name: "\(name).pipeline") } private enum CodingKeys: String, CodingKey { case pipeline } } public struct UpdatePipelineOutput: AWSDecodableShape { /// The structure of the updated pipeline. public let pipeline: PipelineDeclaration? public init(pipeline: PipelineDeclaration? = nil) { self.pipeline = pipeline } private enum CodingKeys: String, CodingKey { case pipeline } } public struct WebhookAuthConfiguration: AWSEncodableShape & AWSDecodableShape { /// The property used to configure acceptance of webhooks in an IP address range. For IP, only the AllowedIPRange property must be set. This property must be set to a valid CIDR range. public let allowedIPRange: String? /// The property used to configure GitHub authentication. For GITHUB_HMAC, only the SecretToken property must be set. public let secretToken: String? public init(allowedIPRange: String? = nil, secretToken: String? = nil) { self.allowedIPRange = allowedIPRange self.secretToken = secretToken } public func validate(name: String) throws { try self.validate(self.allowedIPRange, name: "allowedIPRange", parent: name, max: 100) try self.validate(self.allowedIPRange, name: "allowedIPRange", parent: name, min: 1) try self.validate(self.secretToken, name: "secretToken", parent: name, max: 100) try self.validate(self.secretToken, name: "secretToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case allowedIPRange = "AllowedIPRange" case secretToken = "SecretToken" } } public struct WebhookDefinition: AWSEncodableShape & AWSDecodableShape { /// Supported options are GITHUB_HMAC, IP, and UNAUTHENTICATED. For information about the authentication scheme implemented by GITHUB_HMAC, see Securing your webhooks on the GitHub Developer website. IP rejects webhooks trigger requests unless they originate from an IP address in the IP range whitelisted in the authentication configuration. UNAUTHENTICATED accepts all webhook trigger requests regardless of origin. public let authentication: WebhookAuthenticationType /// Properties that configure the authentication applied to incoming webhook trigger requests. The required properties depend on the authentication type. For GITHUB_HMAC, only the SecretToken property must be set. For IP, only the AllowedIPRange property must be set to a valid CIDR range. For UNAUTHENTICATED, no properties can be set. public let authenticationConfiguration: WebhookAuthConfiguration /// A list of rules applied to the body/payload sent in the POST request to a webhook URL. All defined rules must pass for the request to be accepted and the pipeline started. public let filters: [WebhookFilterRule] /// The name of the webhook. public let name: String /// The name of the action in a pipeline you want to connect to the webhook. The action must be from the source (first) stage of the pipeline. public let targetAction: String /// The name of the pipeline you want to connect to the webhook. public let targetPipeline: String public init(authentication: WebhookAuthenticationType, authenticationConfiguration: WebhookAuthConfiguration, filters: [WebhookFilterRule], name: String, targetAction: String, targetPipeline: String) { self.authentication = authentication self.authenticationConfiguration = authenticationConfiguration self.filters = filters self.name = name self.targetAction = targetAction self.targetPipeline = targetPipeline } public func validate(name: String) throws { try self.authenticationConfiguration.validate(name: "\(name).authenticationConfiguration") try self.filters.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.filters, name: "filters", parent: name, max: 5) try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.targetAction, name: "targetAction", parent: name, max: 100) try self.validate(self.targetAction, name: "targetAction", parent: name, min: 1) try self.validate(self.targetAction, name: "targetAction", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") try self.validate(self.targetPipeline, name: "targetPipeline", parent: name, max: 100) try self.validate(self.targetPipeline, name: "targetPipeline", parent: name, min: 1) try self.validate(self.targetPipeline, name: "targetPipeline", parent: name, pattern: "[A-Za-z0-9.@\\-_]+") } private enum CodingKeys: String, CodingKey { case authentication case authenticationConfiguration case filters case name case targetAction case targetPipeline } } public struct WebhookFilterRule: AWSEncodableShape & AWSDecodableShape { /// A JsonPath expression that is applied to the body/payload of the webhook. The value selected by the JsonPath expression must match the value specified in the MatchEquals field. Otherwise, the request is ignored. For more information, see Java JsonPath implementation in GitHub. public let jsonPath: String /// The value selected by the JsonPath expression must match what is supplied in the MatchEquals field. Otherwise, the request is ignored. Properties from the target action configuration can be included as placeholders in this value by surrounding the action configuration key with curly brackets. For example, if the value supplied here is "refs/heads/{Branch}" and the target action has an action configuration property called "Branch" with a value of "master", the MatchEquals value is evaluated as "refs/heads/master". For a list of action configuration properties for built-in action types, see Pipeline Structure Reference Action Requirements. public let matchEquals: String? public init(jsonPath: String, matchEquals: String? = nil) { self.jsonPath = jsonPath self.matchEquals = matchEquals } public func validate(name: String) throws { try self.validate(self.jsonPath, name: "jsonPath", parent: name, max: 150) try self.validate(self.jsonPath, name: "jsonPath", parent: name, min: 1) try self.validate(self.matchEquals, name: "matchEquals", parent: name, max: 150) try self.validate(self.matchEquals, name: "matchEquals", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case jsonPath case matchEquals } } }
apache-2.0
4b775b58186bfa3e56d9e4e803db8205
46.409898
792
0.647147
4.92327
false
false
false
false
mlibai/XZKit
Projects/Example/CarouselViewExample/CarouselViewExample/CarouselViewExample/Example3/Example3ViewController.swift
1
18827
// // Example3ViewController.swift // XZCarouselViewExample // // Created by 徐臻 on 2019/3/12. // Copyright © 2019 mlibai. All rights reserved. // import UIKit import XZKit class Example3ViewController: UIViewController { deinit { print("Example3ViewController: \(#function)") } fileprivate class Model { let index: Int let title: String let url: URL lazy private(set) var titleWidth: CGFloat = { return (title as NSString).boundingRect(with: CGSize.init(width: 1000, height: 40), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15.0)], context: nil).width + 10 }() init(_ index: Int, _ title: String, _ imageURL: URL) { self.index = index self.title = title self.url = imageURL } } fileprivate let pages: [Model] = [ Model(0, "最新", URL(string: "https://m.ithome.com/")!), Model(1, "排行榜", URL(string: "https://m.ithome.com/rankm/")!), Model(2, "精读", URL(string: "https://m.ithome.com/jingdum/")!), Model(3, "原创", URL(string: "https://m.ithome.com/originalm/")!), Model(4, "上热评", URL(string: "https://m.ithome.com/hotcommentm/")!), Model(5, "评测室", URL(string: "https://m.ithome.com/labsm/")!), Model(6, "发布会", URL(string: "https://m.ithome.com/livem/")!), Model(7, "专题", URL(string: "https://m.ithome.com/specialm/")!), Model(8, "阳台", URL(string: "https://m.ithome.com/balconym/")!), Model(9, "手机", URL(string: "https://m.ithome.com/phonem/")!), Model(10, "数码", URL(string: "https://m.ithome.com/digim/")!), Model(11, "极客学院", URL(string: "https://m.ithome.com/geekm/")!), Model(12, "VR", URL(string: "https://m.ithome.com/vrm/")!), Model(13, "智能汽车", URL(string: "https://m.ithome.com/autom/")!), Model(14, "电脑", URL(string: "https://m.ithome.com/pcm/")!), Model(15, "京东精选", URL(string: "https://m.ithome.com/jdm/")!), Model(16, "安卓", URL(string: "https://m.ithome.com/androidm/")!), Model(17, "苹果", URL(string: "https://m.ithome.com/iosm/")!), Model(18, "网络焦点", URL(string: "https://m.ithome.com/internetm/")!), Model(19, "行业前沿", URL(string: "https://m.ithome.com/itm/")!), Model(20, "游戏电竞", URL(string: "https://m.ithome.com/gamem/")!), Model(21, "Windows", URL(string: "https://m.ithome.com/windowsm/")!), Model(22, "科普", URL(string: "https://m.ithome.com/discoverym/")!) ] @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var containerView: UIView! let indicatorView = UIView.init(frame: .zero) let carouselViewController = CarouselViewController.init() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: nil, action: nil) indicatorView.backgroundColor = UIColor(red: 0xC1 / 255.0, green: 0x06 / 255.0, blue: 0x19 / 255.0, alpha: 1.0) indicatorView.layer.cornerRadius = 1.5 indicatorView.layer.masksToBounds = true collectionView.addSubview(indicatorView) carouselViewController.carouselView.transitionViewHierarchy = .navigation addChild(carouselViewController) carouselViewController.view.backgroundColor = .white carouselViewController.view.frame = containerView.bounds carouselViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] containerView.addSubview(carouselViewController.view) carouselViewController.didMove(toParent: self) carouselViewController.delegate = self carouselViewController.dataSource = self // 因为 UICollectionView 刷新页面是异步的,所以要在菜单显示后才能设置菜单的指示器位置。 collectionView.performBatchUpdates({ self.collectionView.reloadData() }, completion: { (_) in self.carouselViewController.reloadData() }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("Example3ViewController: \(#function)") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("Example3ViewController: \(#function)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("Example3ViewController: \(#function)") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("Example3ViewController: \(#function)") } @IBAction func transitionAnimationSwitchAction(_ sender: UISwitch) { if sender.isOn && carouselViewController.carouselView.transitioningDelegate == nil { carouselViewController.carouselView.transitioningDelegate = self let alertVC = UIAlertController(title: "XZKit", message: "转场 Push/Pop 特效已开启!", preferredStyle: .alert) alertVC.addAction(.init(title: "知道了", style: .cancel, handler: nil)) present(alertVC, animated: true, completion: nil) } else if carouselViewController.carouselView.transitioningDelegate != nil { carouselViewController.carouselView.transitioningDelegate = nil } } private var menuIndex: Int = CarouselView.notFound // 不能重用的控制器 private var indexedViewControllers = [Int: Example3WebViewController]() // 自定义的重用机制:重用池。 private var reusableViewControllers = [Example3WebViewController]() } extension Example3ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Example3MenuCell cell.textLabel.text = pages[indexPath.item].title cell.transition = (menuIndex == indexPath.item ? 1.0 : 0) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: pages[indexPath.item].titleWidth, height: 40) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) carouselViewController.setCurrentIndex(indexPath.item, animated: true) } } extension Example3ViewController: CarouselViewControllerDataSource { func numberOfViewControllers(in carouselViewController: CarouselViewController) -> Int { return pages.count } func carouselViewController(_ carouselViewController: CarouselViewController, viewControllerFor index: Int, reusing reusingViewController: UIViewController?) -> UIViewController { // 自定义重用机制。假定前 5 个栏目是专栏,使用独立的控制器,其它栏目使用相同控制器。 if index < 5 { if let viewController = indexedViewControllers[index] { return viewController } print("创建不可重用控制器:\(index)") let webViewController = Example3WebViewController.init(index: index) webViewController.title = pages[index].title webViewController.load(url: pages[index].url) indexedViewControllers[index] = webViewController return webViewController } if reusableViewControllers.isEmpty { print("创建可重用控制器:\(index)") let webViewController = Example3WebViewController.init(index: index) webViewController.title = pages[index].title webViewController.load(url: pages[index].url) return webViewController } let webViewController = reusableViewControllers.removeLast() print("使用可重用控制器:\(webViewController.index) -> \(index)") webViewController.title = pages[index].title webViewController.load(url: pages[index].url) return webViewController } func carouselViewController(_ carouselViewController: CarouselViewController, shouldEnqueue viewController: UIViewController, at index: Int) -> Bool { guard index >= 5 else { return false } let viewController = viewController as! Example3WebViewController print("回收可重用控制器:\(viewController.index)") viewController.prepareForReusing() reusableViewControllers.append(viewController) return false } } extension Example3ViewController: CarouselViewControllerDelegate { func carouselViewController(_ carouselViewController: CarouselViewController, didShow viewController: UIViewController, at index: Int) { self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true) print("didShowItemAt: \(index)") } func carouselViewController(_ carouselViewController: CarouselViewController, didTransition transition: CGFloat, animated: Bool) { let newIndex = carouselViewController.currentIndex if menuIndex == newIndex { // if transition > 0 { // 滚往下一个。 menuTranstion(to: menuIndex + 1, transition: transition) } else if transition < 0 { menuTranstion(to: menuIndex - 1, transition: -transition) } else { // 滚动取消 menuTranstion(to: menuIndex, transition: 0) collectionView.reloadData() // 重置菜单文字颜色。 } } else { // 页面已跳转到新的 index 。 if (transition == 0) { // 完成跳转 menuIndex = newIndex menuTranstion(to: menuIndex, transition: 0) collectionView.reloadData() } else { // 跳转中。 menuTranstion(to: newIndex, transition: 1.0 - abs(transition)) } } // print("Transition: \(newIndex) \(transition)") } private func menuTranstion(to newIndex: Int, transition: CGFloat) { if menuIndex != newIndex, let targetMenuCell = collectionView.cellForItem(at: IndexPath(item: newIndex, section: 0)) as? Example3MenuCell { // 菜单发生切换,且目标位置可以看到。 targetMenuCell.transition = transition if let currentMenuCell = collectionView.cellForItem(at: IndexPath(item: menuIndex, section: 0)) as? Example3MenuCell { currentMenuCell.transition = 1.0 - transition let p1 = currentMenuCell.center let p2 = targetMenuCell.center if transition < 0.5 { if p1.x < p2.x { let width = (p2.x - p1.x) * transition * 2.0 + 10 indicatorView.frame = CGRect(x: p1.x - 5, y: 37, width: width, height: 3.0) } else { let width = (p1.x - p2.x) * transition * 2.0 + 10.0 indicatorView.frame = CGRect(x: p1.x + 5.0 - width, y: 37, width: width, height: 3.0) } } else { if p1.x < p2.x { let width = (p2.x - p1.x) * (1.0 - transition) * 2.0 + 10.0 indicatorView.frame = CGRect(x: p2.x + 5.0 - width, y: 37, width: width, height: 3.0) } else { let width = (p1.x - p2.x) * (1.0 - transition) * 2.0 + 10.0 indicatorView.frame = CGRect(x: p2.x - 5.0, y: 37, width: width, height: 3.0) } } } else { let p2 = targetMenuCell.center indicatorView.frame = CGRect.init(x: p2.x - 5.0, y: 37, width: 10, height: 3.0) } } else if let currentMenuCell = collectionView.cellForItem(at: IndexPath(item: menuIndex, section: 0)) as? Example3MenuCell { // 只能看到当前菜单。 currentMenuCell.transition = 1.0 - transition let p1 = currentMenuCell.center indicatorView.frame = CGRect.init(x: p1.x - 5.0, y: 37, width: 10, height: 3.0) } else { // 看不到当前菜单。 collectionView.performBatchUpdates({ self.collectionView.reloadData() }, completion: { (_) in self.menuTranstion(to: newIndex, transition: 0) }) } } } extension Example3ViewController: CarouselViewTransitioningDelegate { func carouselView(_ carouselView: CarouselView, animateTransition isInteractive: Bool) { let width: CGFloat = floor(UIScreen.main.bounds.width / 3.0) let timingFunction = isInteractive ? nil : CAMediaTimingFunction(name: .easeInEaseOut) let navigationAnimation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.transform)); navigationAnimation.timingFunction = timingFunction let shadowRadiusAnimation = CAKeyframeAnimation.init(keyPath: #keyPath(CALayer.shadowRadius)) shadowRadiusAnimation.timingFunction = timingFunction let shadowOpacityAnimation = CAKeyframeAnimation.init(keyPath: #keyPath(CALayer.shadowOpacity)) shadowOpacityAnimation.timingFunction = timingFunction let shadowColorAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.shadowColor)) shadowColorAnimation.timingFunction = timingFunction shadowColorAnimation.fromValue = UIColor.black.cgColor shadowColorAnimation.toValue = UIColor.black.cgColor let shadowOffsetAnimation = CABasicAnimation.init(keyPath: #keyPath(CALayer.shadowOffset)) shadowOffsetAnimation.timingFunction = timingFunction shadowOffsetAnimation.fromValue = NSValue(cgSize: .zero); shadowOffsetAnimation.toValue = NSValue(cgSize: .zero); // backwardTransitioningView navigationAnimation.values = [ CATransform3DMakeTranslation(+width, 0, 0), CATransform3DIdentity ] navigationAnimation.beginTime = 6.0 navigationAnimation.duration = 1.0 carouselView.backwardTransitioningView.layer.add(navigationAnimation, forKey: "transform") // transitioningView navigationAnimation.values = [ CATransform3DIdentity, CATransform3DMakeTranslation(+width, 0, 0) ] navigationAnimation.beginTime = 0.0 navigationAnimation.duration = 1.0 carouselView.transitioningView.layer.add(navigationAnimation, forKey: "transform1") navigationAnimation.values = [ CATransform3DIdentity, CATransform3DIdentity ] navigationAnimation.beginTime = 2.0 navigationAnimation.duration = 1.0 carouselView.transitioningView.layer.add(navigationAnimation, forKey: "transform2") shadowRadiusAnimation.values = [5.0, 10.0] shadowOpacityAnimation.values = [0.5, 0.0] shadowRadiusAnimation.beginTime = 2.0 shadowRadiusAnimation.duration = 1.0 carouselView.transitioningView.layer.add(shadowRadiusAnimation, forKey: "shadowRadius") shadowOpacityAnimation.beginTime = 2.0 shadowOpacityAnimation.duration = 1.0 carouselView.transitioningView.layer.add(shadowOpacityAnimation, forKey: "shadowOpacity") shadowColorAnimation.beginTime = 2.0 shadowColorAnimation.duration = 1.0 carouselView.transitioningView.layer.add(shadowColorAnimation, forKey: "shadowColor") shadowOffsetAnimation.beginTime = 2.0 shadowOffsetAnimation.duration = 1.0 carouselView.transitioningView.layer.add(shadowOffsetAnimation, forKey: "shadowOffset") // forwardTransitioningView navigationAnimation.values = [ CATransform3DIdentity, CATransform3DIdentity ] shadowRadiusAnimation.values = [0.0, 5.0] shadowOpacityAnimation.values = [0.0, 0.5] navigationAnimation.beginTime = 4.0 navigationAnimation.duration = 1.0 carouselView.forwardTransitioningView.layer.add(navigationAnimation, forKey: "transform") shadowRadiusAnimation.beginTime = 4.0 shadowRadiusAnimation.duration = 1.0 carouselView.forwardTransitioningView.layer.add(shadowRadiusAnimation, forKey: "shadowRadius") shadowOpacityAnimation.beginTime = 4.0 shadowOpacityAnimation.duration = 1.0 carouselView.forwardTransitioningView.layer.add(shadowOpacityAnimation, forKey: "shadowOpacity") shadowColorAnimation.beginTime = 4.0 shadowColorAnimation.duration = 1.0 carouselView.forwardTransitioningView.layer.add(shadowColorAnimation, forKey: "shadowColor") shadowOffsetAnimation.beginTime = 4.0 shadowOffsetAnimation.duration = 1.0 carouselView.forwardTransitioningView.layer.add(shadowOffsetAnimation, forKey: "shadowOffset") } func carouselView(_ carouselView: CarouselView, animationEnded transitionCompleted: Bool) { carouselView.backwardTransitioningView.layer.removeAllAnimations() carouselView.transitioningView.layer.removeAllAnimations() carouselView.forwardTransitioningView.layer.removeAllAnimations() } } class Example3MenuCell: UICollectionViewCell { @IBOutlet weak var textLabel: UILabel! var transition: CGFloat = 0 { didSet { textLabel.textColor = UIColor(red: transition * 0xC1 / 255.0, green: transition * 0x06 / 255.0, blue: transition * 0x19 / 255.0, alpha: 1.0) let scale = 1.0 + transition * 0.1 textLabel.transform = CGAffineTransform(scaleX: scale, y: scale) } } }
mit
68a33c9723d2bd21c65aa4aad832869d
43.914005
231
0.641247
4.666837
false
false
false
false
swaruphs/Password-Validator-Swift
Password-Validator/Password-Validator.swift
1
1680
// // Password-Validator.swift // Password-Validator // // Created by Swarup on 20/2/17. // // import Foundation public enum ValidationRules { case UpperCase case LowerCase case Digit case SpecialCharacter fileprivate var characterSet:CharacterSet { switch self { case .UpperCase: return NSCharacterSet.uppercaseLetters case .LowerCase: return NSCharacterSet.lowercaseLetters case .Digit: return NSCharacterSet.decimalDigits case .SpecialCharacter: return NSCharacterSet.symbols } } } public struct PasswordValidator { var minLength = 0 var maxLength = 128 var rules: [ValidationRules] = [.LowerCase] public init(rules validationRules:[ValidationRules] = [.LowerCase], minLength min:Int = 0, maxLength max:Int = 128) { minLength = min maxLength = max if validationRules.count > 0 { rules = validationRules } } public func isValid(password pwdString: String) -> Bool { if pwdString.characters.count < minLength { return false } if pwdString.characters.count > maxLength { return false } for rule in self.rules { let hasMember = pwdString.unicodeScalars.contains { ( u: UnicodeScalar) -> Bool in rule.characterSet.contains(u) } if hasMember == false { return false } } return true } }
apache-2.0
6d2e44278135890226a223885c5f0b22
21.105263
121
0.544643
5.384615
false
false
false
false
crspybits/SMSyncServer
iOS/iOSTests/Pods/SMCoreLib/SMCoreLib/Classes/Views/SMImageTextView/SMImageTextView+JSON.swift
3
4656
// // SMImageTextView+JSON.swift // SMCoreLib // // Created by Christopher Prince on 6/2/16. // Copyright © 2016 Spastic Muffin, LLC. All rights reserved. // import Foundation public extension SMImageTextView { public func contentsToData() -> NSData? { guard let currentContents = self.contents else { return nil } return SMImageTextView.contentsToData(currentContents) } public class func contentsToData(contents:[ImageTextViewElement]) -> NSData? { // First create array of dictionaries. var array = [[String:AnyObject]]() for elem in contents { array.append(elem.toDictionary()) } var jsonData:NSData? do { try jsonData = NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions(rawValue: 0)) } catch (let error) { Log.error("Error serializing array to JSON data: \(error)") return nil } let jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding) as? String Log.msg("json results: \(jsonString)") return jsonData } public func saveContents(toFileURL fileURL:NSURL) -> Bool { guard let jsonData = self.contentsToData() else { return false } do { try jsonData.writeToURL(fileURL, options: .AtomicWrite) } catch (let error) { Log.error("Error writing JSON data to file: \(error)") return false } return true } // Give populateImagesUsing as non-nil to populate the images. private class func contents(fromJSONData jsonData:NSData?, populateImagesUsing smImageTextView:SMImageTextView?) -> [ImageTextViewElement]? { var array:[[String:AnyObject]]? if jsonData == nil { return nil } do { try array = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions(rawValue: 0)) as? [[String : AnyObject]] } catch (let error) { Log.error("Error converting JSON data to array: \(error)") return nil } if array == nil { return nil } var results = [ImageTextViewElement]() for dict in array! { if let elem = ImageTextViewElement.fromDictionary(dict) { var elemToAdd = elem switch elem { case .Image(_, let uuid, let range): if smImageTextView == nil { elemToAdd = .Image(nil, uuid, range) } else { if let image = smImageTextView!.imageDelegate?.smImageTextView(smImageTextView!, imageForUUID: uuid!) { elemToAdd = .Image(image, uuid, range) } else { return nil } } default: break } results.append(elemToAdd) } else { return nil } } return results } public class func contents(fromJSONData jsonData:NSData?) -> [ImageTextViewElement]? { return self.contents(fromJSONData: jsonData, populateImagesUsing: nil) } // Concatenates all of the string components. Ignores the images. public class func contentsAsConcatenatedString(fromJSONData jsonData:NSData?) -> String? { if let contents = SMImageTextView.contents(fromJSONData: jsonData) { var result = "" for elem in contents { switch elem { case .Text(let string, _): result += string default: break } } return result } return nil } public func loadContents(fromJSONData jsonData:NSData?) -> Bool { self.contents = SMImageTextView.contents(fromJSONData: jsonData, populateImagesUsing: self) return self.contents == nil ? false : true } public func loadContents(fromJSONFileURL fileURL:NSURL) -> Bool { guard let jsonData = NSData(contentsOfURL: fileURL) else { return false } return self.loadContents(fromJSONData: jsonData) } }
gpl-3.0
5b851d3586b793cc32f86ec2203c9b89
29.834437
145
0.526316
5.515403
false
false
false
false
Sherlouk/IGListKit
Examples/Examples-iOS/IGListKitExamples/ViewControllers/SingleSectionViewController.swift
2
3262
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import IGListKit final class SingleSectionViewController: UIViewController, IGListAdapterDataSource, IGListSingleSectionControllerDelegate { lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) let data = Array(0..<20) // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } //MARK: - IGListAdapterDataSource func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { return data as [IGListDiffable] } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { let configureBlock = { (item: Any, cell: UICollectionViewCell) in guard let cell = cell as? NibCell, let number = item as? Int else { return } cell.textLabel.text = "Cell: \(number + 1)" } let sizeBlock = { (item: Any, context: IGListCollectionContext?) -> CGSize in guard let context = context else { return CGSize() } return CGSize(width: context.containerSize.width, height: 44) } let sectionController = IGListSingleSectionController(nibName: NibCell.nibName, bundle: nil, configureBlock: configureBlock, sizeBlock: sizeBlock) sectionController.selectionDelegate = self return sectionController } func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil } // MARK: - IGListSingleSectionControllerDelegate func didSelect(_ sectionController: IGListSingleSectionController) { let section = adapter.section(for: sectionController) + 1 let alert = UIAlertController(title: "Section \(section) was selected \u{1F389}", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } }
bsd-3-clause
0a579e1a25a0ba8ec7a4fd230f0b66d9
40.291139
127
0.658798
5.643599
false
false
false
false
roambotics/swift
test/PrintAsObjC/empty.swift
2
1778
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -emit-objc-header-path %t/empty.h // RUN: %FileCheck %s < %t/empty.h // RUN: %check-in-clang -std=c99 %t/empty.h // RUN: %check-in-clang -std=c11 %t/empty.h // RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++98 -D_LIBCPP_CSTDLIB %t/empty.h // RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++11 -D_LIBCPP_CSTDLIB %t/empty.h // RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++14 -D_LIBCPP_CSTDLIB %t/empty.h // RUN: %check-in-clang -std=c99 -fno-modules -Qunused-arguments %t/empty.h // RUN: not %check-in-clang -I %S/Inputs/clang-headers %t/empty.h 2>&1 | %FileCheck %s --check-prefix=CUSTOM-OBJC-PROLOGUE // Make sure we can handle two bridging headers. rdar://problem/22702104 // RUN: %check-in-clang -include %t/empty.h -std=c99 -fno-modules -Qunused-arguments %t/empty.h // REQUIRES: objc_interop // CHECK-NOT: @import Swift; // CHECK-LABEL: #if !defined(__has_feature) // CHECK-NEXT: # define __has_feature(x) 0 // CHECK-NEXT: #endif // CHECK-LABEL: #include <Foundation/Foundation.h> // CHECK: #include <stdint.h> // CHECK: #include <stddef.h> // CHECK: #include <stdbool.h> // CHECK: # define SWIFT_METATYPE(X) // CHECK: # define SWIFT_CLASS // CHECK: # define SWIFT_CLASS_NAMED // CHECK: # define SWIFT_PROTOCOL // CHECK: # define SWIFT_PROTOCOL_NAMED // CHECK: # define SWIFT_EXTENSION(M) // CHECK: # define OBJC_DESIGNATED_INITIALIZER // CHECK-LABEL: #if __has_feature(objc_modules) // CHECK-NEXT: #if __has_warning // CHECK-NEXT: #pragma clang diagnostic // CHECK-NEXT: #endif // CHECK-NEXT: #endif // CHECK-NOT: {{[@;{}]}} // CUSTOM-OBJC-PROLOGUE: swift/objc-prologue.h:1:2: error: "Prologue included"
apache-2.0
d09ebf950b231d9cbec69998f0f44ce0
36.829787
122
0.681665
2.710366
false
false
false
false
xumx/ditto
Ditto/DittoStore.swift
2
12419
import UIKit import CoreData class DittoStore : NSObject { let MAX_CATEGORIES = 8 let PRESET_CATEGORIES = ["Instructions", "Driving", "Business", "Dating 🔥❤️"] let PRESET_DITTOS = [ "Instructions": [ "Welcome to Ditto! 👋", "Add Ditto in Settings > General > Keyboard > Keyboards.", "You must allow full access for Ditto to work properly. After you've added the Ditto keyboard, select it, and turn on Allow Full Access.", "We DO NOT access ANYTHING that you type on the keyboard.", "Everything is saved privately on your device. 🔒", "Use the Ditto app to customize your dittos.", "Add a triple underscore ___ to your ditto to control where your cursor lands.", "You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try! You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try! You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try! You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try!", "Hold down a keyboard tab to expand the category title, and swipe on the tab bar for quick access." ], "Driving": [ "I'm driving, can you call me?", "I'll be there in ___ minutes!", "What's the address?", "Can't text, I'm driving 🚘" ], "Business": [ "Hi ___,\n\nIt was great meeting you today. I'd love to chat in more detail about possible business opportunities. Please let me know your availability.\n\nBest,\nAsaf Avidan Antonir", "My name is Asaf, and I work at Shmoogle on the search team. We are always looking for talented candidates to join our team, and with your impressive background, we think you could be a great fit. Please let me know if you are interested, and if so, your availability to chat this week." ], "Dating 🔥❤️": [ "I'm not a photographer, but I can picture us together. 📷", "Was your dad a thief? Because someone stole the stars from the sky and put them in your eyes ✨👀✨.", "Do you have a Band-Aid? Because I just scraped my knee falling for you." ] ] let defaults = NSUserDefaults(suiteName: "group.io.kern.ditto")! static var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("Ditto", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() static var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let directory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.io.kern.ditto") let storeURL = directory?.URLByAppendingPathComponent("Ditto.sqlite") let options = [ NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true), NSInferMappingModelAutomaticallyOption: NSNumber(bool: true) ] let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) var err: NSError? = nil do { try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options) } catch var error as NSError { err = error fatalError(err!.localizedDescription) } catch { fatalError() } return persistentStoreCoordinator }() static var managedObjectContext: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator return managedObjectContext }() //=================== // MARK: Persistence lazy var context: NSManagedObjectContext = { return DittoStore.managedObjectContext }() func save() { var err: NSError? = nil do { try DittoStore.managedObjectContext.save() } catch let error as NSError { err = error fatalError(err!.localizedDescription) } } func createProfile() -> Profile { let profile = NSEntityDescription.insertNewObjectForEntityForName("Profile", inManagedObjectContext: DittoStore.managedObjectContext) as! Profile for categoryName in PRESET_CATEGORIES { let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: DittoStore.managedObjectContext) as! Category category.profile = profile category.title = categoryName for dittoText in PRESET_DITTOS[categoryName]! { let ditto = NSEntityDescription.insertNewObjectForEntityForName("Ditto", inManagedObjectContext: DittoStore.managedObjectContext) as! Ditto ditto.category = category ditto.text = dittoText } } // Migrate dittos from V1 defaults.synchronize() if let dittos = defaults.arrayForKey("dittos") as? [String] { let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: DittoStore.managedObjectContext) as! Category category.profile = profile category.title = "General" for dittoText in dittos { let ditto = NSEntityDescription.insertNewObjectForEntityForName("Ditto", inManagedObjectContext: DittoStore.managedObjectContext) as! Ditto ditto.category = category ditto.text = dittoText } } defaults.removeObjectForKey("dittos") defaults.synchronize() save() return profile } func getProfile() -> Profile { let fetchRequest = NSFetchRequest(entityName: "Profile") var error: NSError? do { let profiles = try DittoStore.managedObjectContext.executeFetchRequest(fetchRequest) if profiles.count > 0 { return profiles[0] as! Profile } else { return self.createProfile() } } catch let error1 as NSError { error = error1 fatalError(error!.localizedDescription) } } //=============== // MARK: Getters func getCategories() -> [String] { return Array(getProfile().categories).map({ (category) in let c = category as! Category return c.title }) } func getCategory(categoryIndex: Int) -> String { let category = getProfile().categories[categoryIndex] as! Category return category.title } func getDittosInCategory(categoryIndex: Int) -> [String] { let category = getProfile().categories[categoryIndex] as! Category let dittos = Array(category.dittos) return dittos.map({ (ditto) in let d = ditto as! Ditto return d.text }) } func getDittoInCategory(categoryIndex: Int, index dittoIndex: Int) -> String { let category = getProfile().categories[categoryIndex] as! Category let ditto = category.dittos[dittoIndex] as! Ditto return ditto.text } func getDittoPreviewInCategory(categoryIndex: Int, index dittoIndex: Int) -> String { return preview(getDittoInCategory(categoryIndex, index: dittoIndex)) } //================== // MARK: - Counting func isEmpty() -> Bool { return countCategories() == 0 } func oneCategory() -> Bool { return countCategories() == 1 } func countInCategory(categoryIndex: Int) -> Int { let category = getProfile().categories[categoryIndex] as! Category return category.dittos.count } func countCategories() -> Int { return getProfile().categories.count } //============================= // MARK: - Category Management func canCreateNewCategory() -> Bool { return countCategories() < MAX_CATEGORIES } func addCategoryWithName(name: String) { let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: context) as! Category category.profile = getProfile() category.title = name save() } func removeCategoryAtIndex(categoryIndex: Int) { let category = getProfile().categories[categoryIndex] as! Category context.deleteObject(category) save() } func moveCategoryFromIndex(fromIndex: Int, toIndex: Int) { let categories = getProfile().categories.mutableCopy() as! NSMutableOrderedSet let category = categories[fromIndex] as! Category categories.removeObjectAtIndex(fromIndex) categories.insertObject(category, atIndex: toIndex) getProfile().categories = categories as NSOrderedSet save() } func editCategoryAtIndex(index: Int, name: String) { let category = getProfile().categories[index] as! Category category.title = name save() } //========================== // MARK: - Ditto Management func addDittoToCategory(categoryIndex: Int, text: String) { let ditto = NSEntityDescription.insertNewObjectForEntityForName("Ditto", inManagedObjectContext: context) as! Ditto ditto.category = getProfile().categories[categoryIndex] as! Category ditto.text = text save() } func removeDittoFromCategory(categoryIndex: Int, index dittoIndex: Int) { let category = getProfile().categories[categoryIndex] as! Category let ditto = category.dittos[dittoIndex] as! Ditto context.deleteObject(ditto) save() } func moveDittoFromCategory(fromCategoryIndex: Int, index fromDittoIndex: Int, toCategory toCategoryIndex: Int, index toDittoIndex: Int) { if fromCategoryIndex == toCategoryIndex { let category = getProfile().categories[fromCategoryIndex] as! Category let dittos = category.dittos.mutableCopy() as! NSMutableOrderedSet let ditto = dittos[fromDittoIndex] as! Ditto dittos.removeObjectAtIndex(fromDittoIndex) dittos.insertObject(ditto, atIndex: toDittoIndex) category.dittos = dittos as NSOrderedSet } else { let fromCategory = getProfile().categories[fromCategoryIndex] as! Category let toCategory = getProfile().categories[toCategoryIndex] as! Category let fromDittos = fromCategory.dittos.mutableCopy() as! NSMutableOrderedSet let toDittos = toCategory.dittos.mutableCopy() as! NSMutableOrderedSet let ditto = fromDittos[fromDittoIndex] as! Ditto fromDittos.removeObjectAtIndex(fromDittoIndex) toDittos.insertObject(ditto, atIndex: toDittoIndex) fromCategory.dittos = fromDittos as NSOrderedSet toCategory.dittos = toDittos as NSOrderedSet } save() } func moveDittoFromCategory(fromCategoryIndex: Int, index dittoIndex: Int, toCategory toCategoryIndex: Int) { moveDittoFromCategory(fromCategoryIndex, index: dittoIndex, toCategory: toCategoryIndex, index: countInCategory(toCategoryIndex)) } func editDittoInCategory(categoryIndex: Int, index dittoIndex: Int, text: String) { let category = getProfile().categories[categoryIndex] as! Category let ditto = category.dittos[dittoIndex] as! Ditto ditto.text = text save() } //================= // MARK: - Helpers func preview(ditto: String) -> String { return ditto .stringByReplacingOccurrencesOfString("\n", withString: " ") .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " ")) } }
bsd-3-clause
759a593bd1e73fa9d9b16f25e0332b8a
38.829582
426
0.625545
5.109736
false
false
false
false
zjjzmw1/speedxSwift
speedxSwift/Pods/RealmSwift/RealmSwift/ObjectSchema.swift
21
2590
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /** This class represents Realm model object schemas. When using Realm, `ObjectSchema` objects allow performing migrations and introspecting the database's schema. `ObjectSchema`s map to tables in the core database. */ public final class ObjectSchema: CustomStringConvertible { // MARK: Properties internal let rlmObjectSchema: RLMObjectSchema /// Array of persisted `Property` objects for an object. public var properties: [Property] { return rlmObjectSchema.properties.map { Property($0) } } /// The name of the class this schema describes. public var className: String { return rlmObjectSchema.className } /// The property that serves as the primary key, if there is a primary key. public var primaryKeyProperty: Property? { if let rlmProperty = rlmObjectSchema.primaryKeyProperty { return Property(rlmProperty) } return nil } /// Returns a human-readable description of the properties contained in this object schema. public var description: String { return rlmObjectSchema.description } // MARK: Initializers internal init(_ rlmObjectSchema: RLMObjectSchema) { self.rlmObjectSchema = rlmObjectSchema } // MARK: Property Retrieval /// Returns the property with the given name, if it exists. public subscript(propertyName: String) -> Property? { if let rlmProperty = rlmObjectSchema[propertyName] { return Property(rlmProperty) } return nil } } // MARK: Equatable extension ObjectSchema: Equatable {} /// Returns whether the two object schemas are equal. public func == (lhs: ObjectSchema, rhs: ObjectSchema) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmObjectSchema.isEqualToObjectSchema(rhs.rlmObjectSchema) }
mit
76061a7606f2fb782a31b13c43382ad9
31.78481
100
0.674903
5.149105
false
false
false
false
FabrizioBrancati/BFKit-Swift
Tests/BFKitTests/Linux/Foundation/FileManagerExtensionTests.swift
1
7464
// // FileManagerExtensionTests.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // 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. @testable import BFKit import Foundation import XCTest internal class FileManagerExtensionTests: XCTestCase { override internal func setUp() { super.setUp() try? FileManager.default.delete(file: "Test.txt", from: .documents) try? FileManager.default.delete(file: "Test.plist", from: .documents) try? FileManager.default.delete(file: "Test2.plist", from: .documents) try? FileManager.default.delete(file: "Test.plist", from: .library) } internal func testPathFor() { let mainBundlePath = FileManager.default.pathFor(.mainBundle) let documentsPath = FileManager.default.pathFor(.documents) let libraryPath = FileManager.default.pathFor(.library) let cachePath = FileManager.default.pathFor(.cache) let applicationSupportPath = FileManager.default.pathFor(.applicationSupport) XCTAssertNotEqual(mainBundlePath, "") XCTAssertNotEqual(documentsPath, "") XCTAssertNotEqual(libraryPath, "") XCTAssertNotEqual(cachePath, "") XCTAssertNotEqual(applicationSupportPath, "") } internal func testReadFileOfType() { do { try FileManager.default.save(file: "Test.txt", in: .temporary, content: "Test") let file = try FileManager.default.read(file: "Test.txt", from: .temporary) XCTAssertNotNil(file) } catch { XCTFail("`testReadFileOfType` error: \(error.localizedDescription)") } } internal func testSavePlistObjectInFilename() { let saved = FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .temporary, filename: "Test") XCTAssertTrue(saved) } internal func testReadPlistFromFilename() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .temporary, filename: "Test") let readed = FileManager.default.readPlist(from: .temporary, filename: "Test") XCTAssertNotNil(readed) } internal func testMainBundlePathFile() { let path = FileManager.default.mainBundlePath() XCTAssertNotNil(path) } internal func testDocumentsPathFile() { let path = FileManager.default.documentsPath() XCTAssertNotNil(path) } internal func testLibraryPathFile() { let path = FileManager.default.libraryPath() XCTAssertNotNil(path) } internal func testCachePathFile() { let path = FileManager.default.cachePath() XCTAssertNotNil(path) } internal func testApplicationSupportPathFile() { let path = FileManager.default.applicationSupportPath() XCTAssertNotNil(path) } internal func testTemporaryPathFile() { let path = FileManager.default.temporaryPath() XCTAssertNotNil(path) } internal func testSizeFileFrom() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .temporary, filename: "Test") do { let size = try FileManager.default.size(file: "Test.plist", from: .temporary) XCTAssertNotNil(size) let sizeNil = try FileManager.default.size(file: "TestNil.plist", from: .temporary) XCTAssertNil(sizeNil) } catch { XCTFail("`testSizeFileFrom` error") } } internal func testDeleteFileFrom() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.delete(file: "Test.plist", from: .documents) XCTAssertTrue(true) } catch { XCTFail("`testDeleteFileFrom` error") } } internal func testMoveFileFromTo() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.move(file: "Test.plist", from: .documents, to: .library) XCTAssertTrue(true) } catch { XCTFail("`testMoveFileFromTo` error") } } internal func testCopyFileFromTo() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.copy(file: "Test.plist", from: .documents, to: .library) XCTAssertTrue(true) } catch { XCTFail("`testCopyFileFromTo` error") } } internal func testCopyFileFromToMainBundle() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.copy(file: "Test.plist", from: .documents, to: .mainBundle) XCTFail("`testCopyFileFromToMainBundle` error") } catch { XCTAssertTrue(true) } } internal func testRenameFileInFromTo() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.rename(file: "Test.plist", in: .documents, to: "Test2.plist") XCTAssertTrue(true) } catch { XCTFail("`testRenameFileInFromTo` error") } } internal func testSetSettingsFilenameObjectForKey() { let settings = FileManager.default.setSettings(filename: "Test", object: ["1", "2", "3", "4", "5"], forKey: "Test") XCTAssertTrue(settings) } internal func testGetSettingsFilenameForKey() { FileManager.default.setSettings(filename: "Test", object: ["1", "2", "3", "4", "5"], forKey: "Test") let settings = FileManager.default.getSettings(filename: "Test", forKey: "Test") XCTAssertNotNil(settings) } internal func testGetEmptySettingsFilenameForKey() { let settings = FileManager.default.getSettings(filename: "Test3", forKey: "Test") XCTAssertNil(settings) } }
mit
836c83a0103fd0aaf7fde48a80ddd7d8
34.712919
123
0.611602
4.548446
false
true
false
false
sicardf/MyRide
MyRide/UI/Maps/UIView/MapKitView.swift
1
1703
// // ApplePlan.swift // MyRide // // Created by Flavien SICARD on 24/05/2017. // Copyright © 2017 sicardf. All rights reserved. // import UIKit import MapKit class MapKitView: MapView, MKMapViewDelegate { private var mapView: MKMapView! private var pinView: UIImageView! var _delegate: MapDelegate! override init(frame: CGRect) { super.init(frame: frame) self.setup() } override func displayPin() {} override func changeCenterCoordinate(coordinate: CLLocationCoordinate2D) { let region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) mapView.setRegion(region, animated: true) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { mapView = MKMapView(frame: self.bounds) mapView.delegate = self mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.showsUserLocation = true mapView.setUserTrackingMode(MKUserTrackingMode.follow, animated: false) addSubview(mapView) let pinView = UIImageView(frame: CGRect(x: self.frame.size.width / 2 - 25, y: self.frame.size.height / 2 - 50, width: 50, height: 50)) pinView.image = #imageLiteral(resourceName: "pinIcon") addSubview(pinView) } // MARK : MGLMapViewDelegate func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { displayPin() print(mapView.centerCoordinate) delegate.centerCoordinateMapChange(coordinate: mapView.centerCoordinate) } }
mit
d1fe96c87ab9fd1f0a39d7a246639b59
28.859649
142
0.659812
4.526596
false
false
false
false
StanZabroda/Hydra
Pods/Nuke/Nuke/Source/Core/ImageMemoryCache.swift
10
2547
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import UIKit public protocol ImageMemoryCaching { func cachedResponseForKey(key: AnyObject) -> ImageCachedResponse? func storeResponse(response: ImageCachedResponse, forKey key: AnyObject) func removeAllCachedImages() } public class ImageCachedResponse { public let image: UIImage public let userInfo: Any? public init(image: UIImage, userInfo: Any?) { self.image = image self.userInfo = userInfo } } public class ImageMemoryCache: ImageMemoryCaching { public let cache: NSCache deinit { #if os(iOS) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) #endif } public init(cache: NSCache) { self.cache = cache #if os(iOS) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didReceiveMemoryWarning:"), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) #endif } public convenience init() { let cache = NSCache() cache.totalCostLimit = ImageMemoryCache.recommendedCacheTotalLimit() self.init(cache: cache) } public func cachedResponseForKey(key: AnyObject) -> ImageCachedResponse? { let object: AnyObject? = self.cache.objectForKey(key) return object as? ImageCachedResponse } public func storeResponse(response: ImageCachedResponse, forKey key: AnyObject) { let cost = self.costForImage(response.image) self.cache.setObject(response, forKey: key, cost: cost) } public func costForImage(image: UIImage) -> Int { let imageRef = image.CGImage let bits = CGImageGetWidth(imageRef) * CGImageGetHeight(imageRef) * CGImageGetBitsPerPixel(imageRef) return bits / 8 } public class func recommendedCacheTotalLimit() -> Int { #if os(iOS) let physicalMemory = NSProcessInfo.processInfo().physicalMemory let ratio = physicalMemory <= (1024 * 1024 * 512 /* 512 Mb */) ? 0.1 : 0.2 return Int(Double(physicalMemory) * ratio) #else return 1024 * 1024 * 30 // 30 Mb #endif } public func removeAllCachedImages() { self.cache.removeAllObjects() } @objc private func didReceiveMemoryWarning(notification: NSNotification) { self.cache.removeAllObjects() } }
mit
c0e484e92a6a60d386dcdd1dc5ca9111
31.653846
183
0.661563
4.898077
false
false
false
false
kristofer/anagram-go-java
anagram.swift
1
1262
//: Playground - noun: a place where people can play let string1 = "aab" let string2 = "aba" let string3 = "cab" let string4 = "kjfdhskdhfksdhk" let string5 = "Kjfdhskdhfksdhk" func anagram(_ x: String, _ y: String) -> Bool { if x == y { return true } if x.count != y.count { return false } var dictx = [String: Int]() var dicty = [String: Int]() for i in x { let ii = "\(i)" if dictx[ii] != nil { let n = dictx[ii]! + 1 dictx[ii] = n } else { dictx[ii] = 1 } } for i in y { let ii = "\(i)" if dicty[ii] != nil { // handles unwrapping Int? let n = dicty[ii]! + 1 dicty[ii] = n } else { dicty[ii] = 1 } } if dictx.count != dicty.count { return false } for (k, v) in dictx { if let vy = dicty[k] { // handles unwrapping Int? if v != vy { return false } } } return true } func main() { print(anagram(string1, string1)) print(anagram(string1, string2)) print(anagram(string1, string3)) print(anagram(string1, string4)) print(anagram(string4, string5)) } main()
mit
7368b1916cbdf175709ae9f38394453a
19.354839
57
0.482567
3.252577
false
false
false
false
alexanderedge/Toolbelt
Toolbelt/ToolbeltTests/ToolbeltTestsCommon.swift
1
3030
// // ToolbeltTestsCommon.swift // Toolbelt // // The MIT License (MIT) // // Copyright (c) 09/05/2015 Alexander G Edge // // 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 import CoreGraphics @testable import Toolbelt class ToolbeltTestsCommon: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testEmailValidation () { let email = "[email protected]" XCTAssert(email.isValidEmail(), "email is valid") } func testHexString () { let bytes: [UInt8] = [0x1a,0x2b,0x3c,0x4d,0x5e] let data = NSData(bytes: UnsafePointer<UInt8>(bytes), length: bytes.count) XCTAssertEqual(data.hexadecimalString, "1a2b3c4d5e") } func testImageGeneration () { let image = Image.imageWithColour(Colour.red, size: CGSize(width: 50, height: 50)) XCTAssertNotNil(image, "image shouldn't be nil") } func testColourCreationUsingHex () { let colour = Colour(hex: 0x00801e) XCTAssertEqual(colour, Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1)) } func testColourCreationUsingHexString () { let colour = Colour(hexString: "00801e") XCTAssertEqual(colour, Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1)) } func testHexFromColour () { let colour = Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1) XCTAssertEqual(colour.hex, 0x00801e) } func testHexStringFromColour () { let colour = Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1) print(colour.hexString) XCTAssertEqual(colour.hexString, "#00801e") } }
mit
cb19138bf60de0868d533a7c052a4f21
35.506024
111
0.669967
4.002642
false
true
false
false
mitchtreece/Spider
Spider/Classes/Core/SSE/EventBuffer.swift
1
2841
// // EventBuffer.swift // Spider-Web // // Created by Mitch Treece on 10/6/20. // import Foundation internal class EventBuffer { private var newlineCharacters: [String] private let buffer = NSMutableData() init(newlineCharacters: [String]) { self.newlineCharacters = newlineCharacters } func append(data: Data?) -> [String] { guard let data = data else { return [] } self.buffer.append(data) return parse() } private func parse() -> [String] { var events = [String]() var searchRange = NSRange(location: 0, length: self.buffer.length) while let foundRange = searchFirstEventDelimiter(in: searchRange) { // if we found a delimiter range that means that from the beggining of the buffer // until the beggining of the range where the delimiter was found we have an event. // The beggining of the event is: searchRange.location // The lenght of the event is the position where the foundRange was found. let chunk = self.buffer.subdata( with: NSRange( location: searchRange.location, length: foundRange.location - searchRange.location ) ) if let text = String(bytes: chunk, encoding: .utf8) { events.append(text) } // We move the searchRange start position (location) after the fundRange we just found and searchRange.location = foundRange.location + foundRange.length searchRange.length = self.buffer.length - searchRange.location } // We empty the piece of the buffer we just search in. self.buffer.replaceBytes( in: NSRange(location: 0, length: searchRange.location), withBytes: nil, length: 0 ) return events } private func searchFirstEventDelimiter(in range: NSRange) -> NSRange? { // This methods returns the range of the first delimiter found in the buffer. For example: // If in the buffer we have: `id: event-id-1\ndata:event-data-first\n\n` // This method will return the range for the `\n\n`. let delimiters = self.newlineCharacters.map { "\($0)\($0)".data(using: .utf8)! } for delimiter in delimiters { let foundRange = self.buffer.range( of: delimiter, options: NSData.SearchOptions(), in: range ) if foundRange.location != NSNotFound { return foundRange } } return nil } }
mit
e3629b6b9e1cae0fccc9d14d46611498
28.905263
102
0.55051
4.99297
false
false
false
false
NikitaAsabin/pdpDecember
DayPhoto/FlipDismissAnimationController.swift
1
2477
// // FlipDismissAnimationController.swift // DayPhoto // // Created by Nikita Asabin on 14.01.16. // Copyright © 2016 Flatstack. All rights reserved. // import UIKit class FlipDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var destinationFrame = CGRectZero func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.6 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey), let containerView = transitionContext.containerView(), let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else { return } let finalFrame = destinationFrame let snapshot = fromVC.view.snapshotViewAfterScreenUpdates(false) snapshot.layer.cornerRadius = 25 snapshot.layer.masksToBounds = true containerView.addSubview(toVC.view) containerView.addSubview(snapshot) fromVC.view.hidden = true AnimationHelper.perspectiveTransformForContainerView(containerView) toVC.view.layer.transform = AnimationHelper.yRotation(-M_PI_2) let duration = transitionDuration(transitionContext) UIView.animateKeyframesWithDuration( duration, delay: 0, options: .CalculationModeCubic, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1/3, animations: { snapshot.frame = finalFrame }) UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: { snapshot.layer.transform = AnimationHelper.yRotation(M_PI_2) }) UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: { toVC.view.layer.transform = AnimationHelper.yRotation(0.0) }) }, completion: { _ in fromVC.view.hidden = false snapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } }
mit
3e81c1e0786262affbed01a5875fa668
35.955224
108
0.629645
6.365039
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Home/View/CollectionGameCell.swift
1
2053
// // CollectionGameCell.swift // MGDYZB // // Created by ming on 16/10/26. // Copyright © 2016年 ming. All rights reserved. // 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles // github: https://github.com/LYM-mg // import UIKit class CollectionGameCell: UICollectionViewCell { // MARK: 控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var lineView: UIView! // MARK: 定义模型属性 var baseGame : BaseGameModel? { didSet { titleLabel.text = baseGame?.tag_name // iconImageView.image = UIImage(named: "home_more_btn") if let iconURL = URL(string: baseGame?.icon_url ?? "") { iconImageView.kf.setImage(with: iconURL) } else { iconImageView.image = UIImage(named: "home_more_btn") } // titleLabel.text = baseGame?.tag_name // if let iconURL = URL(string: baseGame?.icon_url ?? "") { // if baseGame?.tag_name == "更多" { // iconImageView.image = #imageLiteral(resourceName: "home_more_btn") // }else { // iconImageView.kf.setImage(with: (with: iconURL), placeholder: #imageLiteral(resourceName: "placehoderImage")) //// iconImageView.kf.setImage(with: iconURL, placeholder: #imageLiteral(resourceName: "placehoderImage")) //// iconImageView.kf.setImage(with: iconURL) // } // } else { // iconImageView.image = UIImage(named: "home_more_btn") // } } } override func awakeFromNib() { super.awakeFromNib() self.layoutIfNeeded() iconImageView.layer.cornerRadius = self.iconImageView.frame.size.height*0.5 iconImageView.clipsToBounds = true frame = CGRect(x: 0, y: 0, width: 80, height: 90) lineView.isHidden = true // backgroundColor = UIColor.orangeColor() } }
mit
4caf25312533e38e20a9bdac895c61db
33.827586
131
0.581683
4.190871
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Helpers/syncengine/ZMMessage+Likes.swift
1
2553
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel extension ZMConversationMessage { var canBeLiked: Bool { guard let conversation = conversationLike else { return false } let participatesInConversation = conversation.localParticipantsContain(user: SelfUser.current) let sentOrDelivered = deliveryState.isOne(of: .sent, .delivered, .read) let likableType = isNormal && !isKnock return participatesInConversation && sentOrDelivered && likableType && !isObfuscated && !isEphemeral } var liked: Bool { get { return likers.contains { $0.isSelfUser } } set { if newValue { ZMMessage.addReaction(.like, toMessage: self) } else { ZMMessage.removeReaction(onMessage: self) } } } func hasReactions() -> Bool { return self.usersReaction.map { (_, users) in return users.count }.reduce(0, +) > 0 } var likers: [UserType] { return usersReaction.filter { (reaction, _) -> Bool in reaction == MessageReaction.like.unicodeValue }.map { (_, users) in return users }.first ?? [] } var sortedLikers: [UserType] { return likers.sorted { $0.name < $1.name } } var sortedReadReceipts: [ReadReceipt] { return readReceipts.sorted { $0.userType.name < $1.userType.name } } } extension Message { static func setLikedMessage(_ message: ZMConversationMessage, liked: Bool) { return message.liked = liked } static func isLikedMessage(_ message: ZMConversationMessage) -> Bool { return message.liked } static func hasReactions(_ message: ZMConversationMessage) -> Bool { return message.hasReactions() } }
gpl-3.0
96aaf94bb2398d576e2a85c0da7ab730
28.344828
108
0.634548
4.550802
false
false
false
false
gregomni/swift
test/Generics/rdar75656022.swift
2
3288
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify 2>&1 | %FileCheck %s protocol P1 { associatedtype T } protocol P2 { associatedtype T : P1 } struct S1<A, B, C> : P2 where A : P1, C : P2, B == A.T.T, C.T == A.T { typealias T = C.T } struct S2<D : P1> : P2 { typealias T = D } // Make sure that we can resolve the nested type A.T // in the same-type requirement 'A.T == B.T'. // // A is concrete, and S1<C, E, S2<D>>.T resolves to // S2<D>.T, which is D. The typealias S1.T has a // structural type 'C.T'; since C is concrete, we // have to handle the case of an unresolved member // type with a concrete base. struct UnresolvedWithConcreteBase<A, B> { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where A == S1<C, E, S2<D>>, B : P2, A.T == B.T, C : P1, D == C.T, E == D.T { } } // Make sure that we drop the conformance requirement // 'A : P2' and rebuild the generic signature with the // correct same-type requirements. // // The original test case in the bug report (correctly) // produces two warnings about redundant requirements. struct OriginalExampleWithWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where C : P1, D : P1, // expected-warning {{redundant conformance constraint 'D' : 'P1'}} C.T : P1, // expected-warning {{redundant conformance constraint 'D' : 'P1'}} // expected-note@-1 {{conformance constraint 'D' : 'P1' implied here}} A == S1<C, C.T.T, S2<C.T>>, C.T == D, E == D.T { } } // Same as above but without the warnings. struct OriginalExampleWithoutWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where C : P1, A == S1<C, C.T.T, S2<C.T>>, C.T == D, E == D.T { } } // Same as above but without unnecessary generic parameters. struct WithoutBogusGenericParametersWithWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C where A == S1<C, B.[P2]T.[P1]T, S2<B.[P2]T>>, B : P2, C : P1, B.[P2]T == C.[P1]T> init<C>(_: C) where C : P1, C.T : P1, // expected-warning {{redundant conformance constraint 'C.T' : 'P1'}} A == S1<C, C.T.T, S2<C.T>> {} } // Same as above but without unnecessary generic parameters // or the warning. struct WithoutBogusGenericParametersWithoutWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C where A == S1<C, B.[P2]T.[P1]T, S2<B.[P2]T>>, B : P2, C : P1, B.[P2]T == C.[P1]T> init<C>(_: C) where C : P1, A == S1<C, C.T.T, S2<C.T>> {} }
apache-2.0
c70964d7d3341dbf39e566b04ec7de6c
38.142857
187
0.577859
2.655897
false
false
false
false
jenasubodh/tasky-ios
Tasky/TaskTableViewCell.swift
1
1360
// // TaskTableViewCell.swift // Tasky // // Created by Subodh Jena on 02/05/17. // Copyright © 2017 Subodh Jena. All rights reserved. // import UIKit class TaskTableViewCell: UITableViewCell { @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var labelDateTime: UILabel! @IBOutlet weak var labelDescription: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setUpCell(task: Task) { labelTitle.text = task.title labelDescription.text = task.description let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy, HH:mm" labelDateTime.text = dateFormatter.string(from: self.getFormattedDate(string: task.updatedAt!)) } func getFormattedDate(string: String) -> Date { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" formatter.timeZone = TimeZone(secondsFromGMT: 0) let date = formatter.date(from: string)! return date } }
mit
84986c87731d8ece4e08814d334ef966
26.734694
103
0.639441
4.455738
false
false
false
false
getwagit/Baya
Baya/BayaLayout.swift
1
3532
// // Copyright (c) 2016-2017 wag it GmbH. // License: MIT // import Foundation import UIKit /** Protocol for any layout. */ public protocol BayaLayout: BayaLayoutable {} /** Methods just for the layout! */ public extension BayaLayout { /** Kick off the layout routine of the root element. Only call this method on the root element. Measures child layoutables but tries to keep them within the frame. */ mutating public func startLayout(with frame: CGRect) { let origin = CGPoint( x: frame.origin.x + self.bayaMargins.left, y: frame.origin.y + self.bayaMargins.top) let combinedSize = Self.combineSizeForLayout( for: self, wrappingSize: self.sizeThatFitsWithMargins(frame.size), matchingSize: frame.size.subtractMargins(ofElement: self)) let size = CGSize( width: min(frame.width, combinedSize.width), height: min(frame.height, combinedSize.height)) self.layoutWith(frame: CGRect( origin: origin, size: size)) } /** Start a dedicated measure pass. Note: You do NOT need to call this method under common conditions. Only if you need to measure your layouts for e.g. a UICollectionViewCell's sizeThatFits method, use this convenience helper. */ mutating public func startMeasure(with size: CGSize) -> CGSize { guard self.bayaModes.width == .wrapContent || self.bayaModes.height == .wrapContent else { return size } let measuredSize = self.sizeThatFitsWithMargins(size) let adjustedSize = measuredSize.addMargins(ofElement: self) return CGSize( width: self.bayaModes.width == .wrapContent ? adjustedSize.width : size.width, height: self.bayaModes.height == .wrapContent ? adjustedSize.height : size.height) } } /** Internal helper. */ internal extension BayaLayout { /** Measure or remeasure the size of a child element. - Parameter forChildElement: The element to measure. This element will be modified in the process. - Parameter cachedMeasuredSize: If available supply the size that was measured and cached during the measure pass. - Parameter availableSize: The size available, most of time the size of the frame. */ func calculateSizeForLayout( forChild element: inout BayaLayoutable, cachedSize measuredSize: CGSize?, ownSize availableSize: CGSize) -> CGSize { return Self.combineSizeForLayout( for: element, wrappingSize: measuredSize ?? element.sizeThatFitsWithMargins(availableSize), matchingSize: availableSize.subtractMargins(ofElement: element)) } /** Combines two sizes based on the measure modes defined by the element. - Parameter forElement: The element that holds the relevant measure modes. - Parameter wrappingSize: The measured size of the element. - Parameter matchingSize: The size of the element when matching the parent. */ static func combineSizeForLayout( `for` element: BayaLayoutable, wrappingSize: CGSize, matchingSize: CGSize) -> CGSize { return CGSize( width: element.bayaModes.width == .matchParent ? matchingSize.width : wrappingSize.width, height: element.bayaModes.height == .matchParent ? matchingSize.height : wrappingSize.height) } }
mit
62878f1780cf1f3b3b1942390c25c6c7
36.178947
122
0.657418
4.581064
false
false
false
false
xuxulll/XLPickerNode
XLPickerNode.swift
1
25821
// // XLPickerNode.swift // createpickerNode // // Created by 徐磊 on 15/7/3. // Copyright (c) 2015年 xuxulll. All rights reserved. // import SpriteKit /** * Data Source */ @objc protocol XLPickerNodeDataSource: NSObjectProtocol { /** * Number of component in picker node * Default value is set to 1 if not implemented */ optional func numberOfComponentsInPickerNode(pickerNode: XLPickerNode) -> Int /** * Number of rows in component */ func pickerNode(pickerNode: XLPickerNode, numberOfRowsInComponent component: Int) -> Int /** * Cell for row in component */ func pickerNode(pickerNode: XLPickerNode, cellForRow row: Int, inComponent component: Int) -> SKNode } /** * Delegate */ @objc protocol XLPickerNodeDelegate: NSObjectProtocol { /** * Called after user dragged on the picker node or manually set selectedRow */ optional func pickerNode(pickerNode: XLPickerNode, didSelectRow row: Int, inComponent component: Int) /** * customize component width and row height for each component */ optional func pickerNode(pickerNode: XLPickerNode, widthForComponent component: Int) -> CGFloat optional func pickerNode(pickerNode: XLPickerNode, rowHeightForComponent components: Int) -> CGFloat /** * called before display cell */ optional func pickerNode(pickerNode: XLPickerNode, willDisplayCell cell: SKNode, forRow row: Int, forComponent component: Int) } // MARK: - Extension for SKNode private var cellIdentifier: NSString? extension SKNode { var identifier: String? { get { return objc_getAssociatedObject(self, &cellIdentifier) as? String } set { objc_setAssociatedObject(self, &cellIdentifier, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)) } } func prepareForReuse() { /** * Clear all action */ self.removeAllActions() for child in self.children { (child as! SKNode).removeAllActions() } } } // MARK: - XLPickerNode @availability(iOS, introduced=7.0) class XLPickerNode: SKNode, UIGestureRecognizerDelegate { weak var dataSource: XLPickerNodeDataSource? weak var delegate: XLPickerNodeDelegate? /// general config of row height for each component /// will be overrided if delegate methods are implemented var rowHeight: CGFloat = 44.0 //MARK: Computed Data /// Methods /** * info fetched from the data source and will be cached */ func numberOfComponents() -> Int { if _numberOfComponents == -1 { _numberOfComponents = dataSource?.numberOfComponentsInPickerNode?(self) ?? 1 } return _numberOfComponents } func numberOfRowsInComponent(Component: Int) -> Int { return dataSource!.pickerNode(self, numberOfRowsInComponent: Component) } func contentSizeForComponent(component: Int) -> CGSize { return contentNodes[component].frame.size } func rowHeightForComponent(component: Int) -> CGFloat { return componentRowHeights[component] } func widthForComponent(component: Int) -> CGFloat { return componentWidths[component] } /// Computed properties private var _maxRowHeight: CGFloat { var maxHeight: CGFloat = 0.0 for height in componentRowHeights { maxHeight = max(maxHeight, height) } return maxHeight } //MARK: Data affecting UI /// set during initialization, read-only to public private(set) var size: CGSize /// default to show indicator var showsSelectionIndicator: Bool = true { didSet { if showsSelectionIndicator { /** * Re-initialize indicator node since we deinit it when hiding indicator */ indicatorNode = SKSpriteNode(color: indicatorColor, size: CGSizeMake(size.width, _maxRowHeight)) backgroundNode.addChild(indicatorNode!) } else { /** * Release indicator node when hide indicator */ indicatorNode?.removeFromParent() indicatorNode = nil } } } var indicatorColor: UIColor = UIColor.whiteColor() { didSet { indicatorNode?.color = indicatorColor } } /// Set background color or texture var backgroundColor: UIColor = UIColor.clearColor() { didSet { if backgroundColor == UIColor.clearColor() { colorNode?.removeFromParent() colorNode = nil } else { if colorNode == nil { colorNode = SKSpriteNode(color: backgroundColor, size: size) self.addChild(colorNode!) } else { colorNode?.color = backgroundColor } } } } var backgroundTexture: SKTexture? { didSet { if backgroundTexture == nil { colorNode?.removeFromParent() colorNode = nil } else { if colorNode == nil { colorNode = SKSpriteNode(texture: backgroundTexture, size: size) self.addChild(colorNode!) } else { colorNode?.texture = backgroundTexture } } } } /// default to enable scroll var scrollEnabled: Bool = true { didSet { if scrollEnabled { /** * re-initialize pan gesture and add to view since we released it for avoid crash for scene transit */ if panGesture == nil { panGesture = UIPanGestureRecognizer(target: self, action: "panGestureDiDTriggered:") panGesture!.delegate = self self.scene?.view?.addGestureRecognizer(panGesture!) } self.userInteractionEnabled = true } else { /** * Remove gesture from view for disable scroll and avoid crash after new scene is presented */ if panGesture != nil { self.scene!.view!.removeGestureRecognizer(panGesture!) panGesture = nil } self.userInteractionEnabled = false } } } //MARK: Nested nodes private var maskedNode: SKCropNode! private var colorNode: SKSpriteNode? private var backgroundNode: SKNode! private var contentNodes = [SKSpriteNode]() private var indicatorNode: SKSpriteNode? /// bound to current drag node private weak var currentActionNode: SKSpriteNode? //MARK: Stored properties private var identifiers = [String: String]() private var reusableCells = [String: [SKNode]]() private var visibleItems = [Int: [Int: SKNode]]() private var componentWidths = [CGFloat]() private var componentRowHeights = [CGFloat]() private var maxRows = [Int]() private var _numberOfComponents: Int = -1 /* Gesture handler */ private var panGesture: UIPanGestureRecognizer? private var kScrollDuration: NSTimeInterval = 5.0 //MARK: - Initializers init(position: CGPoint, size: CGSize) { self.size = size super.init() self.position = position } convenience override init() { self.init(position: CGPointZero, size: CGSizeZero) } required init?(coder aDecoder: NSCoder) { self.size = CGSizeZero super.init(coder: aDecoder) } /** Register class for reusable cell. :param: className Class that will be registered to XLPickerNode. The Class should be SKNode or its subclass :param: identifier Reusable identifier */ func registerClass(className: AnyClass, withReusableIdentifer identifier: String) { identifiers[identifier] = "\(NSStringFromClass(className))" } //MARK: - Deinitializers deinit { println("XLPickerNode: deinit.") removeGestures() } override func removeFromParent() { /** * Remove gesture to avoid crash when picker node is deinited while pan gesture still refers to the node. */ removeGestures() super.removeFromParent() } private func removeGestures() { if panGesture != nil { self.scene!.view!.removeGestureRecognizer(panGesture!) panGesture = nil //println("XLPickerNode: Pan gesture is successfully removed.") } } //MARK: - Methods //MARK: Cell reuse func dequeueReusableCellWithIdentifier(identifier: String) -> AnyObject? { if identifiers.isEmpty { fatalError("XLPickerNode: No class is registered for reusable cell.") } if let array = reusableCells[identifier] { if var element = array.last { reusableCells[identifier]!.removeLast() element.prepareForReuse() return element } } let nodeClass = NSClassFromString(identifiers[identifier]) as! SKNode.Type return nodeClass() } private func enqueueReusableCell(cell: SKNode) { if let identifer = cell.identifier { var array = reusableCells[identifer] ?? [SKNode]() if array.isEmpty { reusableCells[identifer] = array } array.append(cell) //println("reusable count: \(array.count)") } } private func layoutCellsForComponent(component: Int) { let visibleRect = visibleRectForComponent(component) let oldVisibleRows = rowsForVisibleCellsInComponent(component) let newVisibleRows = rowsForCellInRect(visibleRect, forComponent: component) var rowsToRemove = NSMutableArray(array: oldVisibleRows) rowsToRemove.removeObjectsInArray(newVisibleRows) var rowsToAdd = NSMutableArray(array: newVisibleRows) rowsToAdd.removeObjectsInArray(oldVisibleRows) for row in rowsToRemove { if let cell = cellForRow(row as! Int, forComponent: component) { enqueueReusableCell(cell) cell.removeFromParent() visibleItems[component]?.removeValueForKey(row as! Int) } } let size = CGSizeMake(widthForComponent(component), rowHeightForComponent(component)) for row in rowsToAdd { var node = dataSource?.pickerNode(self, cellForRow: row as! Int, inComponent: component) assert(node != nil, "XLPickerNode: Unexpected to find optional nil in content cell. At lease one delegate method for returning picker cell.") contentNodes[component].addChild(node!) let n = Array(identifiers.keys)[0] node?.identifier = Array(identifiers.keys)[0] let info = positionAndSizeForRow(row as! Int, forComponent: component) node!.position = info.position node?.zPosition = 100 delegate?.pickerNode?(self, willDisplayCell: node!, forRow: row as! Int, forComponent: component) if visibleItems[component] == nil { visibleItems[component] = [Int: SKNode]() } visibleItems[component]![row as! Int] = node! } } //MARK: - Data Handler func reloadData() { if dataSource == nil { return } prepareForPickerNode() for component in 0 ..< numberOfComponents() { layoutCellsForComponent(component) updateAlphaForRow(0, forComponent: component) } } /** * called when reloadData() */ private func prepareForPickerNode() { /** * Nested methods. Only called when prepareForPickerNode() is called. */ func reloadParentNodes() { backgroundNode.removeAllChildren() componentWidths = [] componentRowHeights = [] contentNodes = [] maxRows = [] if delegate != nil && delegate!.respondsToSelector("pickerNode:widthForComponent:") { for s in 0 ..< numberOfComponents() { componentWidths.append(delegate!.pickerNode!(self, widthForComponent: s)) } } else { let fixedWidth = size.width / CGFloat(numberOfComponents()) for s in 0 ..< numberOfComponents() { componentWidths.append(fixedWidth) } } if delegate != nil && delegate!.respondsToSelector("pickerNode:rowHeightForComponent:") { for s in 0 ..< numberOfComponents() { let height = delegate!.pickerNode!(self, rowHeightForComponent: s) componentRowHeights.append(height) } } else { for _ in 0 ..< numberOfComponents() { componentRowHeights.append(rowHeight) } } for height in componentRowHeights { let rows = ceil(size.height / height) maxRows.append(Int(rows)) } for (index, componentWidth) in enumerate(componentWidths) { let contentNode = SKSpriteNode( color: UIColor.clearColor(), size: CGSizeMake( componentWidth, componentRowHeights[index] * CGFloat(numberOfRowsInComponent(index) ) ) ) contentNode.anchorPoint = CGPointMake(0, 1) var accuWidth: CGFloat = -size.width / 2 for i in 0 ..< index { accuWidth += componentWidths[i] } contentNode.position = CGPointMake(accuWidth, rowHeightForComponent(index) / 2) contentNode.identifier = "_contentNode" contentNode.userData = NSMutableDictionary(dictionary: ["_component": index]) backgroundNode.addChild(contentNode) contentNodes.append(contentNode) } } if maskedNode == nil { maskedNode = SKCropNode() self.addChild(maskedNode) backgroundNode = SKNode() maskedNode.addChild(backgroundNode) backgroundNode.zPosition = -1000 } /** * Re-mask */ let mask = SKSpriteNode(color: UIColor.blackColor(), size: size) maskedNode.maskNode = mask /** * reload all components in self */ reloadParentNodes() if showsSelectionIndicator && indicatorNode == nil { indicatorNode = SKSpriteNode(color: indicatorColor, size: CGSizeMake(size.width, _maxRowHeight)) backgroundNode.addChild(indicatorNode!) indicatorNode?.size = CGSizeMake(size.width, _maxRowHeight) } if scrollEnabled && panGesture == nil { panGesture = UIPanGestureRecognizer(target: self, action: "panGestureDiDTriggered:") panGesture!.delegate = self self.scene!.view!.addGestureRecognizer(panGesture!) } } // selection. in this case, it means showing the appropriate row in the middle // scrolls the specified row to center. func selectRow(row: Int, forComponent component: Int, animated: Bool) { currentActionNode = contentNodes[component] if animated { let rawPnt = contentNodes[component].position let newPosition = positionAndSizeForRow(row, forComponent: component).position currentNodeAnimateMoveToPosition(CGPointMake(rawPnt.x, -newPosition.y), fromPoint: rawPnt, duration: kScrollDuration) } else { let rawPnt = contentNodes[component].position let newPosition = positionAndSizeForRow(row, forComponent: component).position currentActionNode!.position = CGPointMake(rawPnt.x, -newPosition.y) delegate?.pickerNode?(self, didSelectRow: row, inComponent: component) } } // returns selected row. -1 if nothing selected func selectedRowForComponent(component: Int) -> Int { return max(0, min(Int((contentNodes[component].position.y/* + contentNodes[component].size.height / 2*/) / rowHeightForComponent(component)), numberOfRowsInComponent(component) - 1)) } //MARK: - Data calculations //MARK: Reusable private func visibleRectForComponent(component: Int) -> CGRect { let node = contentNodes[component] return CGRectMake(0, node.position.y - rowHeightForComponent(component) / 2 - size.height / 2, widthForComponent(component), size.height) } private func rowsForVisibleCellsInComponent(component: Int) -> [Int] { var rows = [Int]() if let comps = visibleItems[component] { for (key, _) in comps { rows.append(key) } return rows } return [Int]() } private func rowsForCellInRect(rect: CGRect, forComponent component: Int) -> [Int] { var rows = [Int]() for row in 0 ..< numberOfRowsInComponent(component) { var cellRect = rectForCellAtRow(row, inComponent: component) if CGRectIntersectsRect(cellRect, rect) { rows.append(row) } } return rows } private func rectForCellAtRow(row: Int, inComponent component: Int) -> CGRect { return CGRectMake(0, rowHeightForComponent(component) * CGFloat(row), widthForComponent(component), rowHeightForComponent(component)) } private func cellForRow(row: Int, forComponent component: Int) -> SKNode? { if let componentCells = visibleItems[component] { return componentCells[row] } return nil } //MARK: Position and size /** Position and size for a specific row and component :param: row row :param: component component :returns: Cell Info<Tuple> (position, size) */ private func positionAndSizeForRow(row: Int, forComponent component: Int) -> (position: CGPoint, size: CGSize) { func positionForRow(row: Int, forComponent component: Int) -> CGPoint { let rowHeight = -rowHeightForComponent(component) let totalHeight = CGFloat(row) * rowHeight + rowHeight * 0.5 return CGPointMake(widthForComponent(component) / 2, totalHeight) } func sizeForRow(row: Int, forComponent component: Int) -> CGSize { return CGSizeMake(widthForComponent(component), rowHeightForComponent(component)) } return (positionForRow(row, forComponent: component), sizeForRow(row, forComponent: component)) } /** Nearest anchor of cell for current drag location :param: point drag location :param: component component number for calculation :returns: nearest anchor point */ private func contentOffsetNearPoint(point: CGPoint, inComponent component: Int) -> CGPoint { var mult = round((point.y + rowHeightForComponent(component) / 2) / rowHeightForComponent(component)) let info = positionAndSizeForRow(Int(mult) - 1, forComponent: component) return CGPointMake(info.position.x, -info.position.y) } private func calculateThresholdYOffsetWithPoint(point: CGPoint, forComponent component: Int) -> CGPoint { var retVal = point retVal.x = contentNodes[component].position.x retVal.y = max(retVal.y, minYOffsetForComponents(component)) retVal.y = min(retVal.y, maxYOffsetForComponent(component)) return retVal } private func minYOffsetForComponents(component: Int) -> CGFloat { return rowHeightForComponent(component) / 2 } private func maxYOffsetForComponent(component: Int) -> CGFloat { return contentSizeForComponent(component).height - rowHeightForComponent(component) / 2 } //MARK: - Gesture Handler func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { let touchLocation = touch.locationInNode(self) weak var tNode: SKSpriteNode? for node in (self.nodesAtPoint(touchLocation) as! [SKNode]) { if node.identifier == "_contentNode" { currentActionNode = node as? SKSpriteNode return true } } return false } func panGestureDiDTriggered(recognizer: UIPanGestureRecognizer) { if recognizer.state == .Began { currentActionNode!.removeAllActions() } else if recognizer.state == .Changed { var translation = recognizer.translationInView(recognizer.view!) translation.y = -translation.y let pos = CGPointMake(currentActionNode!.position.x, currentActionNode!.position.y + translation.y) currentActionNode!.position = pos recognizer.setTranslation(CGPointZero, inView: recognizer.view!) let component = currentActionNode!.userData!.valueForKey("_component")!.integerValue layoutCellsForComponent(component) let row = round((pos.y + rowHeightForComponent(component) / 2) / rowHeightForComponent(component)) - 1 updateAlphaForRow(Int(row), forComponent: component) } else if recognizer.state == .Ended { if let component = find(contentNodes, currentActionNode!) { let velocity = recognizer.velocityInView(recognizer.view!) let rawPnt = currentActionNode!.position var newPosition = CGPointMake(rawPnt.x, rawPnt.y - velocity.y) newPosition = contentOffsetNearPoint(newPosition, inComponent: component) let endPoint = calculateThresholdYOffsetWithPoint(newPosition, forComponent: component) var duration = kScrollDuration if !CGPointEqualToPoint(newPosition, endPoint) { duration = 0.5 } currentNodeAnimateMoveToPosition(endPoint, fromPoint: rawPnt, duration: duration) } } } //MARK: - UI Update private func currentNodeAnimateMoveToPosition(endPoint: CGPoint, fromPoint startPoint: CGPoint, duration: NSTimeInterval) { let component = currentActionNode!.userData!.valueForKey("_component")!.integerValue let moveBlock = SKAction.customActionWithDuration(duration, actionBlock: { [unowned self](node, elapsedTime) -> Void in func easeStep(p: CGFloat) -> CGFloat { let f: CGFloat = (p - 1) return f * f * f * (1 - p) + 1 } let t = CGFloat(elapsedTime) / CGFloat(duration) let x = startPoint.x + easeStep(t) * (endPoint.x - startPoint.x); let y = startPoint.y + easeStep(t) * (endPoint.y - startPoint.y); let targetPoint = CGPointMake(x, y) node.position = targetPoint self.layoutCellsForComponent(component) let row = Int(round((node.position.y + self.rowHeightForComponent(component) / 2) / self.rowHeightForComponent(component))) - 1 self.updateAlphaForRow(row, forComponent: component) }) let finishBlock = SKAction.runBlock({ [unowned self]() -> Void in dispatch_async(dispatch_get_main_queue(), { [unowned self]() -> Void in self.delegate?.pickerNode?(self, didSelectRow: selectedRowForComponent(component), inComponent: component) }) }) currentActionNode!.runAction(SKAction.sequence([moveBlock, finishBlock])) } private func updateAlphaForRow(row: Int, forComponent component: Int) { let scope = CGFloat(maxRows[component] - 1) / 2 let reloadRow = CGFloat(maxRows[component] + 1) / 2 let step: CGFloat = 1.0 / reloadRow var currentStep: CGFloat = step for cRow in (row - Int(scope))...(row + Int(scope)) { cellForRow(cRow, forComponent: component)?.alpha = currentStep currentStep += cRow < row ? step : -step } } }
mit
dc65956ca543fc2590e6a80a6b30be64
32.657106
190
0.577068
5.454257
false
false
false
false
felixjendrusch/Matryoshka
MatryoshkaPlayground/MatryoshkaPlayground/Networking/HTTPStatusCode.swift
1
8369
// http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml public enum HTTPStatusCode: Equatable { // Informational case Continue case SwitchingProtocols case Processing // Success case OK case Created case Accepted case NonAuthoritativeInformation case NoContent case ResetContent case PartialContent case MultiStatus case AlreadyReported case IMUsed // Redirection case MultipleChoices case MovedPermanently case Found case SeeOther case NotModified case UseProxy case TemporaryRedirect case PermanentRedirect // Client Error case BadRequest case Unauthorized case PaymentRequired case Forbidden case NotFound case MethodNotAllowed case NotAcceptable case ProxyAuthenticationRequired case RequestTimeout case Conflict case Gone case LengthRequired case PreconditionFailed case PayloadTooLarge case URITooLong case UnsupportedMediaType case RangeNotSatisfiable case ExceptionFailed case MisdirectedRequest case UnprocessableEntity case Locked case FailedDependency case UpgradeRequired case PreconditionRequired case TooManyRequests case RequestHeaderFieldsTooLarge // Server Error case InternalServerError case NotImplemented case BadGateway case ServiceUnavailable case GatewayTimeout case HTTPVersionNotSupported case VariantAlsoNegotiates case InsufficientStorage case LoopDetected case NotExtended case NetworkAuthenticationRequired // Unknown case Unknown(Int) } public func == (lhs: HTTPStatusCode, rhs: HTTPStatusCode) -> Bool { return lhs.rawValue == rhs.rawValue } extension HTTPStatusCode: Printable { public var description: String { return String(rawValue) } } extension HTTPStatusCode: RawRepresentable { public var rawValue: Int { switch self { case .Continue: return 100 case .SwitchingProtocols: return 101 case .Processing: return 102 case .OK: return 200 case .Created: return 201 case .Accepted: return 202 case .NonAuthoritativeInformation: return 203 case .NoContent: return 204 case .ResetContent: return 205 case .PartialContent: return 206 case .MultiStatus: return 207 case .AlreadyReported: return 208 case .IMUsed: return 226 case .MultipleChoices: return 300 case .MovedPermanently: return 301 case .Found: return 302 case .SeeOther: return 303 case .NotModified: return 304 case .UseProxy: return 305 case .TemporaryRedirect: return 307 case .PermanentRedirect: return 308 case .BadRequest: return 400 case .Unauthorized: return 401 case .PaymentRequired: return 402 case .Forbidden: return 403 case .NotFound: return 404 case .MethodNotAllowed: return 405 case .NotAcceptable: return 406 case .ProxyAuthenticationRequired: return 407 case .RequestTimeout: return 408 case .Conflict: return 409 case .Gone: return 410 case .LengthRequired: return 411 case .PreconditionFailed: return 412 case .PayloadTooLarge: return 413 case .URITooLong: return 414 case .UnsupportedMediaType: return 415 case .RangeNotSatisfiable: return 416 case .ExceptionFailed: return 417 case .MisdirectedRequest: return 421 case .UnprocessableEntity: return 422 case .Locked: return 423 case .FailedDependency: return 424 case .UpgradeRequired: return 426 case .PreconditionRequired: return 428 case .TooManyRequests: return 429 case .RequestHeaderFieldsTooLarge: return 431 case .InternalServerError: return 500 case .NotImplemented: return 501 case .BadGateway: return 502 case .ServiceUnavailable: return 503 case .GatewayTimeout: return 504 case .HTTPVersionNotSupported: return 505 case .VariantAlsoNegotiates: return 506 case .InsufficientStorage: return 507 case .LoopDetected: return 508 case .NotExtended: return 510 case .NetworkAuthenticationRequired: return 511 case let .Unknown(statusCode): return statusCode } } public init(rawValue: Int) { switch rawValue { case 100: self = .Continue case 101: self = .SwitchingProtocols case 102: self = .Processing case 200: self = .OK case 201: self = .Created case 202: self = .Accepted case 203: self = .NonAuthoritativeInformation case 204: self = .NoContent case 205: self = .ResetContent case 206: self = .PartialContent case 207: self = .MultiStatus case 208: self = .AlreadyReported case 226: self = .IMUsed case 300: self = .MultipleChoices case 301: self = .MovedPermanently case 302: self = .Found case 303: self = .SeeOther case 304: self = .NotModified case 305: self = .UseProxy case 307: self = .TemporaryRedirect case 308: self = .PermanentRedirect case 400: self = .BadRequest case 401: self = .Unauthorized case 402: self = .PaymentRequired case 403: self = .Forbidden case 404: self = .NotFound case 405: self = .MethodNotAllowed case 406: self = .NotAcceptable case 407: self = .ProxyAuthenticationRequired case 408: self = .RequestTimeout case 409: self = .Conflict case 410: self = .Gone case 411: self = .LengthRequired case 412: self = .PreconditionFailed case 413: self = .PayloadTooLarge case 414: self = .URITooLong case 415: self = .UnsupportedMediaType case 416: self = .RangeNotSatisfiable case 417: self = .ExceptionFailed case 421: self = .MisdirectedRequest case 422: self = .UnprocessableEntity case 423: self = .Locked case 424: self = .FailedDependency case 426: self = .UpgradeRequired case 428: self = .PreconditionRequired case 429: self = .TooManyRequests case 431: self = .RequestHeaderFieldsTooLarge case 500: self = .InternalServerError case 501: self = .NotImplemented case 502: self = .BadGateway case 503: self = .ServiceUnavailable case 504: self = .GatewayTimeout case 505: self = .HTTPVersionNotSupported case 506: self = .VariantAlsoNegotiates case 507: self = .InsufficientStorage case 508: self = .LoopDetected case 510: self = .NotExtended case 511: self = .NetworkAuthenticationRequired case let statusCode: self = .Unknown(statusCode) } } }
mit
20a7c8202074436a9b3e5dfbc2de77a2
24.283988
76
0.547019
5.624328
false
false
false
false