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
dreamsxin/swift
test/SILGen/objc_metatypes.swift
6
2076
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: objc_interop import gizmo @objc class ObjCClass {} class A { // CHECK-LABEL: sil hidden @_TFC14objc_metatypes1A3foo // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_metatypes1A3foo dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type { // CHECK: bb0([[M:%[0-9]+]] : $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : $A): // CHECK: strong_retain [[SELF]] : $A // CHECK: [[M_AS_THICK:%[0-9]+]] = objc_to_thick_metatype [[M]] : $@objc_metatype ObjCClass.Type to $@thick ObjCClass.Type // CHECK: [[NATIVE_FOO:%[0-9]+]] = function_ref @_TFC14objc_metatypes1A3foo // CHECK: [[NATIVE_RESULT:%[0-9]+]] = apply [[NATIVE_FOO]]([[M_AS_THICK]], [[SELF]]) : $@convention(method) (@thick ObjCClass.Type, @guaranteed A) -> @thick ObjCClass.Type // CHECK: [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type // CHECK: return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type return m } // CHECK-LABEL: sil hidden @_TZFC14objc_metatypes1A3bar // CHECK-LABEL: sil hidden [thunk] @_TToZFC14objc_metatypes1A3bar // CHECK: bb0([[SELF:%[0-9]+]] : $@objc_metatype A.Type): // CHECK-NEXT: [[OBJC_SELF:%[0-9]+]] = objc_to_thick_metatype [[SELF]] : $@objc_metatype A.Type to $@thick A.Type // CHECK: [[BAR:%[0-9]+]] = function_ref @_TZFC14objc_metatypes1A3bar // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[BAR]]([[OBJC_SELF]]) : $@convention(method) (@thick A.Type) -> () // CHECK-NEXT: return [[RESULT]] : $() dynamic class func bar() { } dynamic func takeGizmo(_ g: Gizmo.Type) { } // CHECK-LABEL: sil hidden @_TFC14objc_metatypes1A7callFoo func callFoo() { // Make sure we peephole Type/thick_to_objc_metatype. // CHECK-NOT: thick_to_objc_metatype // CHECK: metatype $@objc_metatype ObjCClass.Type foo(ObjCClass.self) // CHECK: return } }
apache-2.0
a105e55204140767c4f6b3077d8760f5
45.133333
177
0.635356
3.213622
false
false
false
false
nickfrey/knightsapp
Newman Knights/CalendarDayViewController.swift
1
7230
// // CalendarDayViewController.swift // Newman Knights // // Created by Nick Frey on 12/24/15. // Copyright © 2015 Nick Frey. All rights reserved. // import UIKit class CalendarDayViewController: FetchedViewController, UITableViewDataSource, UITableViewDelegate, UIViewControllerPreviewingDelegate { let date: Date fileprivate var events: Array<Event> = [] fileprivate weak var tableView: UITableView? fileprivate let eventCellIdentifier = "Event" fileprivate let emptyCellIdentifier = "Empty" init(date: Date) { self.date = date super.init(nibName: nil, bundle: nil) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none self.title = dateFormatter.string(from: date) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(fetch)) let tableView = UITableView(frame: .zero, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.isHidden = true tableView.rowHeight = 55 tableView.register(EventCell.self, forCellReuseIdentifier: self.eventCellIdentifier) tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.emptyCellIdentifier) self.view.addSubview(tableView) self.tableView = tableView registerForPreviewing(with: self, sourceView: tableView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.tableView?.frame = self.view.bounds } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let selectedIndexPath = self.tableView?.indexPathForSelectedRow { self.tableView?.deselectRow(at: selectedIndexPath, animated: true) } } override func viewDidLoad() { super.viewDidLoad() self.fetch() } @objc override func fetch() { self.tableView?.isHidden = true self.navigationItem.rightBarButtonItem?.isEnabled = false super.fetch() _ = EventCalendar.fetchEvents(self.date) { (events, error) -> Void in DispatchQueue.main.async(execute: { guard let events = events, error == nil else { return self.fetchFinished(error) } self.events = events self.fetchFinished(nil) self.tableView?.reloadData() self.tableView?.isHidden = false }) } } override func fetchFinished(_ error: Error?) { super.fetchFinished(error) self.navigationItem.rightBarButtonItem?.isEnabled = true } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return max(self.events.count, 1) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.events.count == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: self.emptyCellIdentifier, for: indexPath) cell.backgroundColor = .clear cell.selectionStyle = .none cell.textLabel?.textColor = UIColor(white: 0, alpha: 0.4) cell.textLabel?.textAlignment = .center cell.textLabel?.text = "No events occur on this day." return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: self.eventCellIdentifier, for: indexPath) as! EventCell cell.event = self.events[indexPath.row] return cell } } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if self.events.count > 0 { let viewController = CalendarEventViewController(event: self.events[indexPath.row]) self.navigationController?.pushViewController(viewController, animated: true) } } // MARK: UIViewControllerPreviewingDelegate func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let tableView = self.tableView, let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) as? EventCell, let event = cell.event else { return nil } return CalendarEventViewController(event: event) } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.navigationController?.pushViewController(viewControllerToCommit, animated: true) } // MARK: Event Cell class EventCell: UITableViewCell { fileprivate let dateFormatter: DateFormatter var dateFormat = "h:mm a" { didSet { if dateFormat != oldValue { self.dateFormatter.dateFormat = dateFormat self.updateLabels() } } } var event: Event? { didSet { if event != oldValue { self.updateLabels() } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.dateFormatter = DateFormatter() self.dateFormatter.dateFormat = self.dateFormat super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) self.accessoryType = .disclosureIndicator } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateLabels() { guard let event = self.event else { return } var eventDetails = Array<String>() if let startDate = event.startDate { let startTime = self.dateFormatter.string(from: startDate) if startTime != "12:00 AM" { eventDetails.append(startTime) } } if let location = event.location, location.count > 0 { if location != "Newman Catholic" { eventDetails.append("@ " + location) } } if let details = event.details, eventDetails.count == 0 { eventDetails.append(details) } if let status = event.status, status.count > 0 { eventDetails.append("(" + status + ")") } self.textLabel?.text = event.computedTitle() self.detailTextLabel?.text = eventDetails.joined(separator: " ") } } }
mit
cb0d419f8480d6c9854c4334112167a7
35.326633
143
0.597178
5.547966
false
false
false
false
JasonJasonJason/LoadingButton
LoadingButton/Classes/LoadingButton.swift
1
4950
// // LoadingButton.swift // Pods // // Created by Septiyan Andika on 6/26/16. // // import UIKit public enum ActivityIndicatorAlignment: Int { case Left case Right } public class LoadingButton: UIButton { lazy var activityIndicatorView:UIActivityIndicatorView! = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) public var indicatorAlignment:ActivityIndicatorAlignment = ActivityIndicatorAlignment.Right { didSet { setupPositionIndicator() } } public var loading:Bool = false { didSet { realoadView() } } public var indicatorColor:UIColor = UIColor.lightGrayColor() { didSet { activityIndicatorView.color = indicatorColor } } public var normalText:String? = nil { didSet { if(normalText == nil){ normalText = self.titleLabel?.text } self.titleLabel?.text = normalText } } public var loadingText:String? = "Please Wait" var topContraints:NSLayoutConstraint? var bottomContraints:NSLayoutConstraint? var widthContraints:NSLayoutConstraint? var rightContraints:NSLayoutConstraint? var leftContraints:NSLayoutConstraint? required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } public override init(frame: CGRect) { super.init(frame: frame) setupView() } public override func setTitle(title: String?, forState state: UIControlState) { super.setTitle(title, forState: state) if normalText == nil{ normalText = title } } func setupView() { activityIndicatorView.hidesWhenStopped = true; self.normalText = self.titleLabel?.text self.addSubview(activityIndicatorView) setupPositionIndicator() } func realoadView() { if(loading){ self.enabled = false activityIndicatorView.hidden = false; activityIndicatorView.startAnimating() if(self.loadingText != nil ){ self.setTitle(loadingText, forState: .Normal) } }else{ self.enabled = true activityIndicatorView.stopAnimating() self.setTitle(normalText, forState: .Normal) } } func setupPositionIndicator() { activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false if(topContraints==nil){ topContraints = NSLayoutConstraint(item: activityIndicatorView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0) } if(bottomContraints==nil){ bottomContraints = NSLayoutConstraint(item: activityIndicatorView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0) } if(widthContraints==nil){ widthContraints = NSLayoutConstraint(item: activityIndicatorView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 30) } if(rightContraints==nil){ rightContraints = NSLayoutConstraint(item: activityIndicatorView, attribute: .TrailingMargin, relatedBy: .Equal, toItem: self, attribute: .TrailingMargin, multiplier: 1.0, constant: 0) } if(leftContraints==nil){ leftContraints = NSLayoutConstraint(item: activityIndicatorView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 0) } if(indicatorAlignment == .Right ){ NSLayoutConstraint.deactivateConstraints([leftContraints!]) NSLayoutConstraint.activateConstraints([topContraints!,rightContraints!,widthContraints!,bottomContraints!]) }else{ NSLayoutConstraint.deactivateConstraints([rightContraints!]) NSLayoutConstraint.activateConstraints([topContraints!,leftContraints!,widthContraints!,bottomContraints!]) } } deinit { activityIndicatorView.removeFromSuperview() activityIndicatorView = nil } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
c81c664601f1b60f89e0c38d37542383
29.9375
144
0.593939
5.702765
false
false
false
false
firemuzzy/slugg
mobile/Slug/Slug/controllers/SlugNavigationController.swift
1
1064
// // SlugNavigationController.swift // Slug // // Created by Andrew Charkin on 3/22/15. // Copyright (c) 2015 Slug. All rights reserved. // import UIKit @IBDesignable class SlugNavigationController: UINavigationController, UIViewControllerTransitioningDelegate { @IBInspectable var barColor: UIColor? { didSet { self.navigationBar.barTintColor = barColor } } @IBInspectable var fontName: String? { didSet { if let fontName = fontName { if let font = UIFont(name: fontName, size: 17) { self.navigationBar.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.whiteColor()] UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState: .Normal) } } } } override func viewDidLoad() { super.viewDidLoad() self.navigationBar.barStyle = UIBarStyle.Black self.navigationBar.tintColor = UIColor.whiteColor() } }
mit
1f7c010430ec382d7fa09965f52ddc0f
24.95122
162
0.68703
5.018868
false
false
false
false
Zewo/Log
Source/Logger.swift
1
4599
// Appender.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. #if os(Linux) @_exported import Glibc #else @_exported import Darwin.C #endif public final class Logger { var appenders = [Appender]() var levels: Log.Level var name: String public init(name: String = "Logger", appender: Appender? = StandardOutputAppender(), levels: Log.Level = .all) { if let appender = appender { self.appenders.append(appender) } self.levels = levels self.name = name } public init(name: String = "Logger", appenders: [Appender], levels: Log.Level = .all) { self.appenders.append(contentsOf: appenders) self.levels = levels self.name = name } public func log(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { let locationInfo = LocationInfo(file: file, line: line, column: column, function: function) let event = LoggingEvent(locationInfo: locationInfo, timestamp: currentTime, level: self.levels, name: self.name, logger: self, message: item, error: error) for apender in appenders { apender.append(event) } } private func log(level: Log.Level, item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { let locationInfo = LocationInfo(file: file, line: line, column: column, function: function) let event = LoggingEvent(locationInfo: locationInfo, timestamp: currentTime, level: level, name: self.name, logger: self, message: item, error: error) for apender in appenders { apender.append(event) } } public func trace(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { log(level: .trace, item: item, error: error, file: file, function: function, line: line, column: column) } public func debug(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { log(level: .debug, item: item, error: error, file: file, function: function, line: line, column: column) } public func info(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { log(level: .info, item: item, error: error, file: file, function: function, line: line, column: column) } public func warning(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { log(level: .warning, item: item, error: error, file: file, function: function, line: line, column: column) } public func error(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { log(level: .error, item: item, error: error, file: file, function: function, line: line, column: column) } public func fatal(_ item: Any?, error: Error? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) { log(level: .fatal, item: item, error: error, file: file, function: function, line: line, column: column) } private var currentTime: Int { var tv = timeval() gettimeofday(&tv, nil) return tv.tv_sec } }
mit
bd42ad44fc73e2658857f9b4038b6ed4
46.90625
167
0.66297
3.871212
false
false
false
false
Beaver/BeaverCodeGen
Pods/Beaver/Beaver/Type/Subscriber.swift
3
4799
#if os(iOS) import UIKit #endif extension Store { /// An object observing state updates public struct Subscriber { /// Called when the store's state changed /// /// - Parameters: /// - oldState: previous state /// - newState: generated state /// - completion: a completion handler called when done public typealias StateDidUpdate = (_ oldState: StateType?, _ newState: StateType, _ completion: @escaping () -> ()) -> () public let name: String public let stateDidUpdate: StateDidUpdate public init(name: String, stateDidUpdate: @escaping StateDidUpdate) { self.name = name self.stateDidUpdate = stateDidUpdate } } } // MARK: - Equatable extension Store.Subscriber: Equatable { public static func ==(lhs: Store<StateType>.Subscriber, rhs: Store<StateType>.Subscriber) -> Bool { return lhs.name == rhs.name } } // MARK: - Hashable extension Store.Subscriber: Hashable { public var hashValue: Int { return name.hashValue } } // MARK: - Description extension Store.Subscriber: CustomDebugStringConvertible { public var debugDescription: String { return name } } /// A type responsible for handling state updates public protocol Subscribing: class { associatedtype StateType: State /// Name automatically given to the store when subscribing var subscriptionName: String { get } /// Should store be able to retain an instance of the subscribing class or not var isSubscriptionWeak: Bool { get } func stateDidUpdate(oldState: StateType?, newState: StateType, completion: @escaping () -> ()) } extension Subscribing { public var subscriptionName: String { return String(describing: type(of: self)) } public typealias StateUpdateEvent = (_ oldState: StateType?, _ newState: StateType) -> () } extension Subscribing where Self: Storing { /// Subscribes to a store. public func subscribe() { if isSubscriptionWeak { // Copy subscription and store name outside of self let subscriptionName = self.subscriptionName let store = self.store store.subscribe(name: subscriptionName) { [weak self] oldState, newState, completion in if let weakSelf = self { weakSelf.stateDidUpdate(oldState: oldState, newState: newState, completion: completion) } else { store.unsubscribe(subscriptionName) completion() } } } else { store.subscribe(name: subscriptionName) { oldState, newState, completion in self.stateDidUpdate(oldState: oldState, newState: newState, completion: completion) } } } // Unsubscribe from a store public func unsubscribe() { store.unsubscribe(subscriptionName) } } extension Subscribing where Self: ChildStoring { /// Subscribes to a store. public func subscribe() { if isSubscriptionWeak { // Copy subscription name and store outside of self let subscriptionName = self.subscriptionName let store = self.store store.subscribe(name: subscriptionName) { [weak self] oldState, newState, completion in if let weakSelf = self { weakSelf.stateDidUpdate(oldState: oldState, newState: newState, completion: completion) } else { store.unsubscribe(subscriptionName) completion() } } } else { store.subscribe(name: subscriptionName) { oldState, newState, completion in self.stateDidUpdate(oldState: oldState, newState: newState, completion: completion) } } } // Unsubscribe from a store public func unsubscribe() { store.unsubscribe(subscriptionName) } } extension Subscribing where Self: Presenting { public var isSubscriptionWeak: Bool { return false } } #if os(iOS) extension Subscribing where Self: UIViewController { public var isSubscriptionWeak: Bool { return true } } #endif
mit
2bc127ac47b0173b401293b4b0bcd8bc
28.62963
103
0.554282
5.645882
false
false
false
false
ThePacielloGroup/CCA-OSX
Colour Contrast Analyser/CCAColourBrightnessDifferenceController.swift
1
2721
// // ResultsController.swift // Colour Contrast Analyser // // Created by Cédric Trévisan on 27/01/2015. // Copyright (c) 2015 Cédric Trévisan. All rights reserved. // import Cocoa class CCAColourBrightnessDifferenceController: NSViewController { @IBOutlet weak var colourDifferenceText: NSTextField! @IBOutlet weak var brightnessDifferenceText: NSTextField! @IBOutlet weak var colourBrightnessSample: CCAColourBrightnessDifferenceField! @IBOutlet weak var menuShowRGBSliders: NSMenuItem! var fColor: NSColor = NSColor(red: 0, green: 0, blue: 0, alpha: 1.0) var bColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1.0) var colourDifferenceValue:Int? var brightnessDifferenceValue:Int? override func viewDidLoad() { super.viewDidLoad() // Do view setup here. self.updateResults() NotificationCenter.default.addObserver(self, selector: #selector(CCAColourBrightnessDifferenceController.updateForeground(_:)), name: NSNotification.Name(rawValue: "ForegroundColorChangedNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(CCAColourBrightnessDifferenceController.updateBackground(_:)), name: NSNotification.Name(rawValue: "BackgroundColorChangedNotification"), object: nil) } func updateResults() { brightnessDifferenceValue = ColourBrightnessDifference.getBrightnessDifference(self.fColor, bc:self.bColor) colourDifferenceValue = ColourBrightnessDifference.getColourDifference(self.fColor, bc:self.bColor) colourDifferenceText.stringValue = String(format: NSLocalizedString("colour_diff", comment:"Colour difference: %d (minimum 500)"), colourDifferenceValue!) brightnessDifferenceText.stringValue = String(format: NSLocalizedString("brightness_diff", comment:"Brightness difference: %d (minimum 125)"), brightnessDifferenceValue!) colourBrightnessSample.validateColourBrightnessDifference(brightnessDifferenceValue!, colour: colourDifferenceValue!) } @objc func updateForeground(_ notification: Notification) { self.fColor = notification.userInfo!["colorWithOpacity"] as! NSColor self.updateResults() var color:NSColor = self.fColor // Fix for #3 : use almost black color if (color.isBlack()) { color = NSColor(red: 0.000001, green: 0, blue: 0, alpha: 1.0) } colourBrightnessSample.textColor = color } @objc func updateBackground(_ notification: Notification) { self.bColor = notification.userInfo!["color"] as! NSColor self.updateResults() colourBrightnessSample.backgroundColor = self.bColor } }
gpl-3.0
17663438301bbd0b705e51a7e9755437
49.314815
223
0.729481
4.644444
false
false
false
false
tonyarnold/Differ
Sources/Differ/Patch+Apply.swift
1
950
public extension RangeReplaceableCollection { /// Applies the changes described by the provided patches to a copy of this collection and returns the result. /// /// - Parameter patches: a collection of ``Patch`` instances to apply. /// - Returns: A copy of the current collection with the provided patches applied to it. func apply<C: Collection>(_ patches: C) -> Self where C.Element == Patch<Element> { var mutableSelf = self for patch in patches { switch patch { case let .insertion(i, element): let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: i) mutableSelf.insert(element, at: target) case let .deletion(i): let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: i) mutableSelf.remove(at: target) } } return mutableSelf } }
mit
e58e7439ae5cbea282ff3584a43186cd
42.181818
114
0.603158
5
false
false
false
false
qualaroo/QualarooSDKiOS
QualarooTests/Interactors/AnswerBinaryInteractorSpec.swift
1
3460
// // AnswerBinaryInteractorSpec.swift // QualarooTests // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class AnswerBinaryInteractorSpec: QuickSpec { override func spec() { super.spec() describe("AnswerBinaryInteractor") { var interactor: AnswerBinaryInteractor! var builder: SingleSelectionAnswerResponseBuilder! var answerHandler: SurveyInteractorMock! beforeEach { let answers = [JsonLibrary.answer(id: 5), JsonLibrary.answer(id: 9)] let question = try! QuestionFactory(with: JsonLibrary.question(id: 1, type: "binary", answerList: answers)).build() builder = SingleSelectionAnswerResponseBuilder(question: question) answerHandler = SurveyInteractorMock() interactor = AnswerBinaryInteractor(responseBuilder: builder, answerHandler: answerHandler) } it("passes first answer on selecting left button") { interactor.selectLeftAnswer() let response = answerHandler.answerChangedValue let answer = AnswerResponse(id: 5, alias: nil, text: nil) let model = QuestionResponse(id: 1, alias: nil, answerList: [answer]) expect(response).to(equal(NodeResponse.question(model))) } it("passes second answer on selecting left button") { interactor.selectRightAnswer() let response = answerHandler.answerChangedValue let answer = AnswerResponse(id: 9, alias: nil, text: nil) let model = QuestionResponse(id: 1, alias: nil, answerList: [answer]) expect(response).to(equal(NodeResponse.question(model))) } it("is not sending response if there is no such answer") { let answers = [JsonLibrary.answer(id: 5), JsonLibrary.answer(id: 9)] let question = try! QuestionFactory(with: JsonLibrary.question(type: "binary", answerList: answers)).build() builder = SingleSelectionAnswerResponseBuilderMock(question: question) answerHandler = SurveyInteractorMock() interactor = AnswerBinaryInteractor(responseBuilder: builder, answerHandler: answerHandler) interactor.selectRightAnswer() expect(answerHandler.answerChangedValue).to(beNil()) expect(answerHandler.goToNextNodeFlag).to(beFalse()) } it("tries to show next node on selecting first button") { interactor.selectLeftAnswer() expect(answerHandler.goToNextNodeFlag).to(beTrue()) } it("tries to show next node on selecting second button") { interactor.selectRightAnswer() expect(answerHandler.goToNextNodeFlag).to(beTrue()) } } } }
mit
8607e197bd61fad32fb92556e442fff6
42.25
100
0.569364
5.306748
false
false
false
false
dnseitz/YAPI
YAPI/YAPI/ImageReference.swift
1
7639
// // ImageLoader.swift // Chowroulette // // Created by Daniel Seitz on 7/28/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import Foundation import UIKit final class ImageCache { static let globalCache = ImageCache() fileprivate var imageCache = [String: ImageReference]() fileprivate let cacheAccessQueue = DispatchQueue(label: "CacheAcess", attributes: .concurrent) fileprivate init() {} fileprivate subscript(key: String) -> ImageReference? { get { var imageReference: ImageReference? = nil self.readLock() { imageReference = self.imageCache[key] } return imageReference } set { guard let imageReference = newValue else { return } self.writeLock() { self.imageCache[key] = imageReference } } } /** Flush all images in the cache */ func flush() { self.writeLock() { self.imageCache.removeAll() } } /** Check if an image for a given url is stored in the cache - Parameter url: The url to check for - Returns: true if the image is in the cache, false if it is not */ func contains(_ url: URL) -> Bool { return self[url.absoluteString] != nil } /** Check if an image for a given image reference is stored in the cache - Parameter imageReference: The image reference to check for - Returns: true if the image is in the cache, false if it is not */ func contains(_ imageReference: ImageReference) -> Bool { return self[imageReference.url.absoluteString] != nil } fileprivate func readLock(_ block: () -> Void) { self.cacheAccessQueue.sync(execute: block) } fileprivate func writeLock(_ block: () -> Void) { self.cacheAccessQueue.sync(flags: .barrier, execute: block) } } /** A class representing an image retrieved from a network source. After being loaded an ImageReference instance will contain a cachedImage property that allows you to access a copy of the image that was loaded from the network source. It's less safe to use this cachedImage property than it is to just load the ImageReference again through an image loader, so it is preferred to load and use the image returned by that. Be aware that every time you access a cached image either through a load or the cachedImage property you are recieving a **copy**, so each image can be scaled or modified independently of any others if they need to be used more than once. - Usage: ``` let imageReference = ImageReference(withURL: NSURL("some.image.com/path/to/image.jpg")) // This is an asynchronous operation, don't expect to have the cached image // available after calling this imageReference.load() { (image, error) in // Do something with the image here } imageReference.cachedImage // COULD BE NIL HERE EVEN IF THE IMAGE WILL BE SUCCESSFULLY LOADED ``` */ public final class ImageReference { fileprivate enum State { case idle case loading } fileprivate var state: ImageReference.State fileprivate let session: YelpHTTPClient fileprivate var _cachedImage: UIImage? /// A copy of the cached image or nil if no image has been loaded yet fileprivate(set) var cachedImage: UIImage? { get { guard let imageCopy = self._cachedImage?.cgImage?.copy() else { return nil } return UIImage(cgImage: imageCopy) } set { if self._cachedImage == nil { self._cachedImage = newValue } } } let url: URL /** Initialize a new ImageReference with the specified url. Two ImageReferences initialized with the same url will functionally be the same image reference. - Parameter url: The url to retrieve the image from - Parameter session: The session to use to make network requests, generally keep this as default - Returns: An ImageLoader that is ready to load an image from the url */ init(from url: URL, session: YelpHTTPClient = YelpHTTPClient.sharedSession) { self.url = url self.state = .idle self.session = session } convenience init?(from string: String, session: YelpHTTPClient = YelpHTTPClient.sharedSession) { guard let url = URL(string: string) else { return nil } self.init(from: url, session: session) } /** Load an image in the background and pass it to the completion handler once finished. This can be called multiple times to retrieve the same image at different scales. Only one load is allowed to be in progress at a time. Each call will return a new instance of a UIImage - Parameter scale: The scale factor to apply to the image - Parameter completionHandler: The handler to call once the image load has completed. This handler takes a UIImage? and a ImageLoaderError? as arguments. If the load was a success, the handler will be called with the UIImage created and the error will be nil. If there is an error, the image will be nil and an error object will be returned */ public func load(withScale scale: CGFloat = 1.0, completionHandler handler: @escaping (_ image: UIImage?, _ error: ImageLoadError?) -> Void) { if self.state == .loading { handler(nil, .loadInProgress) return } self.state = .loading if let imageReference = ImageCache.globalCache[self.url.absoluteString] { self.cachedImage = imageReference.cachedImage } if let image = self.cachedImage { guard let imageCopy = image.cgImage?.copy() else { handler(nil, .copyError) return } handler(UIImage(cgImage: imageCopy, scale: scale, orientation: image.imageOrientation), nil) self.state = .idle return } self.session.send(self.url) {(data, response, error) in var imageResult: UIImage? var errorResult: ImageLoadError? defer { self.state = .idle handler(imageResult, errorResult) } if let err = error { imageResult = nil errorResult = .requestError(err as NSError) return } guard let imageData = data else { imageResult = nil errorResult = .noDataRecieved return } guard let image = UIImage(data: imageData) else { imageResult = nil errorResult = .invalidData return } self.cachedImage = image ImageCache.globalCache[self.url.absoluteString] = self imageResult = UIImage(data: imageData, scale: scale) errorResult = nil } } } public enum ImageLoadError: Error, Equatable { /// An error occurred when trying to send the request, check the wrapped NSError object for more details case requestError(NSError) /// No data was recieved when trying to load the image case noDataRecieved /// Data was recieved, but it was not an image case invalidData /// A load is currently in progress, wait for that to finish case loadInProgress /// Failed to create a valid copy of the cached image case copyError } public func ==(lhs: ImageLoadError, rhs: ImageLoadError) -> Bool { switch (lhs, rhs) { case (let .requestError(err1), let .requestError(err2)): return err1.domain == err2.domain && err1.code == err2.code case (.noDataRecieved, .noDataRecieved): return true case (.invalidData, .invalidData): return true case (.loadInProgress, .loadInProgress): return true case (.copyError, .copyError): return true default: return false } }
mit
d7119f75d9a4a53a0305247fccfa508b
30.303279
144
0.665488
4.530249
false
false
false
false
rabotyaga/bars-ios
baranov/MyDatabase.swift
1
17738
// // MyDatabase.swift // baranov // // Created by Ivan on 07/07/15. // Copyright (c) 2015 Rabotyaga. All rights reserved. // import UIKit import SQLite // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } extension Connection { public var userVersion: Int { get { return Int(try! scalar("PRAGMA user_version") as! Int64) } set { try! run("PRAGMA user_version = \(newValue)") } } } class MyDatabase { static let sharedInstance = MyDatabase() let dbFilename = "articles.db" let db: Connection let articles_table: Table let search_history_table: Table let articles_table_name = "articles" let search_history_table_name = "search_history" let nr = Expression<Int64>("nr") let ar_inf = Expression<String>("ar_inf") let ar_inf_wo_vowels = Expression<String>("ar_inf_wo_vowels") let transcription = Expression<String>("transcription") let translation = Expression<String>("translation") let root = Expression<String>("root") let form = Expression<String>("form") let vocalization = Expression<String?>("vocalization") let homonym_nr = Expression<Int64?>("homonym_nr") let opt = Expression<String>("opt") let ar1 = Expression<String>("ar1") let ar2 = Expression<String>("ar2") let ar3 = Expression<String>("ar3") let mn1 = Expression<String>("mn1") let mn2 = Expression<String>("mn2") let mn3 = Expression<String>("mn3") let ar123_wo_vowels_n_hamza = Expression<String>("ar123_wo_vowels_n_hamza") let updated_at = Expression<Date>("updated_at") let search_string = Expression<String>("search_string") let details_string = Expression<String>("details_string") let matchAttr = [NSAttributedString.Key.backgroundColor : UIColor.matchBg()] let translationSizeAttr = [NSAttributedString.Key.font : UIFont.translationFont()] let arabicAttr = [NSAttributedString.Key.foregroundColor : UIColor.arabicText()] static let arabicVowels = "[\\u064b\\u064c\\u064d\\u064e\\u064f\\u0650\\u0651\\u0652\\u0653\\u0670]" let arabicVowelsPattern = "\(arabicVowels)*" static let arabicTextPattern = "[\\p{Arabic}]+((\\s*~)*(\\s*[\\p{Arabic}]+)+)*" let arabicTextRegex = try! NSRegularExpression(pattern: arabicTextPattern, options: []) static let anyAlifPattern = "[\\u0622\\u0623\\u0625\\u0627]" //alif-madda, alif-hamza, hamza-alif, alif static let anyWawPattern = "[\\u0624\\u0648]" //waw-hamza, waw static let anyYehPattern = "[\\u0626\\u0649]" //yeh-hamza, yeh let anyAlifRegex = try! NSRegularExpression(pattern: anyAlifPattern, options: []) let anyWawRegex = try! NSRegularExpression(pattern: anyWawPattern, options: []) let anyYehRegex = try! NSRegularExpression(pattern: anyYehPattern, options: []) let lastArticleNr: Int64? fileprivate init() { let sourceFilename = (Bundle.main.resourcePath! as NSString).appendingPathComponent(dbFilename) let destinationPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let destinationFilename = (destinationPath as NSString).appendingPathComponent(dbFilename) //var error: NSError? // nested func to allow code reuse in init // before stored properties db & articles_table are initialized func copyDatabase() { do { try FileManager.default.copyItem(atPath: sourceFilename, toPath: destinationFilename) } catch let error as NSError { print("Couldn't copy database: \(error.localizedDescription)") } let Url = URL(fileURLWithPath: destinationFilename) do { try (Url as NSURL).setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey) } catch let error as NSError { print("Error excluding \(Url.lastPathComponent) from backup \(error.localizedDescription)") } } if (!FileManager.default.fileExists(atPath: destinationFilename)) { copyDatabase() } else { do { let documentsDb = try Connection(destinationFilename) let resourcesDb = try Connection(sourceFilename) if (resourcesDb.userVersion > documentsDb.userVersion) { do { try FileManager.default.removeItem(atPath: destinationFilename) } catch let error as NSError { print("Couldn't remove old database in Documents directory: \(error.localizedDescription)") } copyDatabase() } } catch { } } try! db = Connection(destinationFilename) articles_table = Table(articles_table_name) lastArticleNr = try! db.scalar(articles_table.select(nr.max)) search_history_table = Table(search_history_table_name) try! db.run(search_history_table.create(ifNotExists: true) { t in t.column(updated_at) t.column(search_string) t.column(details_string) }) } func getSearchHistory(_ searchString: String) -> [SearchHistory] { var searchHistory: [SearchHistory] = [] let q = search_history_table.filter(search_string.like("\(searchString)%")).order(updated_at.desc).limit(100) for s in try! db.prepare(q) { searchHistory.append(SearchHistory(searchString: s[search_string], details: s[details_string])) } return searchHistory } func saveSearchHistory(_ searchHistory: SearchHistory) { let sh = search_history_table.filter(search_string == searchHistory.searchString) let update = sh.update(details_string <- searchHistory.details, updated_at <- Date()) do { if try db.run(update) > 0 { // updated, do nothing //print("updated history for \(searchHistory.searchString)") } else { // insert do { try db.run(search_history_table.insert(search_string <- searchHistory.searchString, details_string <- searchHistory.details, updated_at <- Date())) //print("inserted history for \(searchHistory.searchString)") } catch { //print("search hist insert failed") } } } catch { //print("update failed: \(error)") } } func deleteSearchHistory(_ searchHistory: SearchHistory) { //print("delete search hist where \(searchHistory.searchString)") do { try db.run(search_history_table.filter(search_string == searchHistory.searchString).delete()) } catch { //print("delete search hist where \(searchHistory.searchString) failed") } } func clearSearchHistory() { //print("clear Search hist") do { try db.run(search_history_table.delete()) } catch { //print("clearSearchHistory failed") } } func searchHistoryCount() -> Int64 { //print("search hist count: \(db.scalar(search_history_table.count))") return try! db.scalar("SELECT COUNT(*) FROM search_history") as! Int64 } func fillInArticles(_ query: AQuery) -> QueryResult { //var startTime = NSDate.timeIntervalSinceReferenceDate() //var stopTime: NSTimeInterval = 0 var searchingInArabic: Bool = true let queryRegex: NSRegularExpression? var articles: [Article] = [] var sections: [SectionInfo] = [] var f_articles: Table? switch(query) { case let .like(query_string): if let _ = query_string.range(of: "^\\p{Arabic}+$", options: .regularExpression) { let qs = query_string.stripForbiddenCharacters() f_articles = articles_table.filter(ar_inf_wo_vowels.like("%\(qs)%") || ar123_wo_vowels_n_hamza.like("%\(qs)%")).order(nr) queryRegex = makeRegexWithVowels(query_string.stripForbiddenCharacters()) } else { f_articles = articles_table.filter(translation.like("%\(query_string.stripForbiddenCharacters())%")).order(nr) searchingInArabic = false queryRegex = try? NSRegularExpression(pattern: query_string.stripForbiddenCharacters(), options: []) } case let .exact(query_string): if let _ = query_string.range(of: "^\\p{Arabic}+$", options: .regularExpression) { let qs = query_string.stripForbiddenCharacters() f_articles = articles_table.filter( qs == articles_table[ar_inf_wo_vowels] || qs == articles_table[ar123_wo_vowels_n_hamza] || ar123_wo_vowels_n_hamza.like("\(qs) %") || ar123_wo_vowels_n_hamza.like("% \(qs)") || ar123_wo_vowels_n_hamza.like("% \(qs) %") ).order(nr) queryRegex = makeRegexWithVowels(query_string.stripForbiddenCharacters()) } else { let qs = query_string.stripForbiddenCharacters() f_articles = articles_table.filter( qs == translation || translation.like("\(qs) %") || translation.like("% \(qs)") || translation.like("% \(qs);%") || translation.like("% \(qs) %") || translation.like("% \(qs)!%") || translation.like("% \(qs).%") || translation.like("% \(qs),%") ).order(nr) searchingInArabic = false queryRegex = try? NSRegularExpression(pattern: query_string.stripForbiddenCharacters(), options: []) } case let .root(root_to_load): f_articles = articles_table.filter(root_to_load == articles_table[root]).order(nr) queryRegex = nil default: queryRegex = nil f_articles = nil } var i = 0 var sa: Article var si = 0 var current_section = SectionInfo(name: "", rows: 0, articles: [], matchScore: 0) //var opts: String = "" var current_article_match_score = 0 if let unwrapped_f_articles = f_articles { for a in try! db.prepare(unwrapped_f_articles) { sa = Article.init( nr: a[nr], ar_inf: a[ar_inf], ar_inf_wo_vowels: a[ar_inf_wo_vowels], transcription: a[transcription], translation: a[translation], root: a[root], form: a[form], vocalization: a[vocalization], homonym_nr: a[homonym_nr], opt: a[opt], ar1: a[ar1], ar2: a[ar2], ar3: a[ar3], mn1: a[mn1], mn2: a[mn2], mn3: a[mn3] ) current_article_match_score = 0 if let qRegex = queryRegex { if (searchingInArabic) { for match in qRegex.matches(in: sa.ar_inf.string, options: [], range: NSMakeRange(0, sa.ar_inf.length)) { sa.ar_inf.addAttributes(matchAttr, range: match.range) current_article_match_score += Int(Float(match.range.length) / Float(sa.ar_inf.string.length) * 100) } for match in qRegex.matches(in: sa.opts.string, options: [], range: NSMakeRange(0, sa.opts.length)) { sa.opts.addAttributes(matchAttr, range: match.range) current_article_match_score += Int(Float(match.range.length) / Float(sa.opts.string.length) * 100) } } else { for match in qRegex.matches(in: sa.translation.string, options: [], range: NSMakeRange(0, sa.translation.length)) { sa.translation.addAttributes(matchAttr, range: match.range) current_article_match_score += Int(Float(match.range.length) / Float(sa.translation.string.length) * 100) } } } //sa.translation = NSMutableAttributedString(string: "\(current_article_match_score) nr \(sa.nr)") sa.translation.addAttributes(translationSizeAttr, range: NSMakeRange(0, sa.translation.length)) for match in arabicTextRegex.matches(in: sa.translation.string, options: [], range: NSMakeRange(0, sa.translation.length)) { sa.translation.addAttributes(arabicAttr, range: match.range) } for match in arabicTextRegex.matches(in: sa.opts.string, options: [], range: NSMakeRange(0, sa.opts.length)) { sa.opts.addAttributes(arabicAttr, range: match.range) } if (i == 0) { current_section = SectionInfo(name: sa.root, rows: 0, articles: [sa], matchScore: current_article_match_score) si += 1 } else { if (sa.root == current_section.name) { current_section.articles.append(sa) if (current_section.matchScore < current_article_match_score) { current_section.matchScore = current_article_match_score } si += 1 } else { current_section.rows = si sections.append(current_section) current_section = SectionInfo(name: sa.root, rows: 0, articles: [sa], matchScore: current_article_match_score) si = 1 } } articles.append(sa) i += 1 } } if (articles.count > 0) { current_section.rows = si sections.append(current_section) } sections.sort { (lhs: SectionInfo, rhs: SectionInfo) -> Bool in if (lhs.matchScore == rhs.matchScore) { return lhs.articles.first?.nr < rhs.articles.first?.nr } return lhs.matchScore > rhs.matchScore } // articles still not sorted // but only articles.count is used from articles //stopTime = NSDate.timeIntervalSinceReferenceDate() //let readTime: Double = stopTime - startTime //print("* time is \(Int(readTime*1000))") return QueryResult(query: query, articles: articles, sections: sections) } func getNextRootByNr(_ nr: Int64, current_root: String) throws -> String { if let root = try db.pluck(articles_table.filter(articles_table[self.nr] > nr && articles_table[self.root] != current_root).order(self.nr).limit(1))?.get(self.root) { return root } return "" } func getPreviousRootByNr(_ nr: Int64, current_root: String) throws -> String { if let root = try db.pluck(articles_table.filter(articles_table[self.nr] < nr && articles_table[self.root] != current_root).order(self.nr.desc).limit(1))?.get(self.root) { return root } return "" } fileprivate func makeRegexWithVowels(_ query: String) -> NSRegularExpression? { var pattern = "" for char in query { var char_str: String = String([char]) if let _ = anyAlifRegex.firstMatch(in: char_str, options: [], range: NSMakeRange(0, char_str.length)) { char_str = MyDatabase.anyAlifPattern } else { if let _ = anyWawRegex.firstMatch(in: char_str, options: [], range: NSMakeRange(0, char_str.length)) { char_str = MyDatabase.anyWawPattern } else { if let _ = anyYehRegex.firstMatch(in: char_str, options: [], range: NSMakeRange(0, char_str.length)) { char_str = MyDatabase.anyYehPattern } } } pattern = pattern + char_str + arabicVowelsPattern } let queryRegex = try? NSRegularExpression(pattern: pattern, options: []) return queryRegex } /* * Only for development needs * * func makeTranscriptionsForAll() { var tr: CFMutableStringRef var tr_str: String var i = 0 for article in articles_table.select(nr, ar_inf) { tr = NSMutableString(string: article[ar_inf]) as CFMutableStringRef CFStringTransform(tr, nil, kCFStringTransformToLatin, Boolean(0)) tr_str = tr as String articles_table.filter(article[nr] == articles_table[nr]).update(transcription <- tr_str) i++ println("\(i): \(tr_str)") } }*/ }
isc
cc1540dab9a2e1eed511db8f37638ad7
42.158151
179
0.55553
4.422339
false
false
false
false
GeekSpeak/GeekSpeak-Show-Timer
GeekSpeak Show Timer/BreakCount-2/Timer+Types.swift
2
6243
import UIKit // TODO: Refactor and abstract out the following hard coded time. // These structs and enums were a quick and dirty way to get the // Timer up and running. This should be abstrated out and use // some sort of configuration file that allows the timer to have // user definded Phases, Durations, soft and hard segment times and // break times. extension Timer { // MARK: - Enums enum CountingState: String, CustomStringConvertible { case Ready = "Ready" case Counting = "Counting" case Paused = "Paused" case PausedAfterComplete = "PausedAfterComplete" case CountingAfterComplete = "CountingAfterComplete" var description: String { return self.rawValue } } enum ShowPhase: String, CustomStringConvertible { case PreShow = "PreShow" case Section1 = "Section1" case Break1 = "Break1" case Section2 = "Section2" case PostShow = "PostShow" var description: String { return self.rawValue } } // ShowTiming struct ShowTiming { var durations = Durations() var timeElapsed = TimeElapsed() var phase = ShowPhase.PreShow var formatter: NumberFormatter = { let formatter = NumberFormatter() formatter.minimumIntegerDigits = 2 formatter.maximumIntegerDigits = 2 formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 0 formatter.negativePrefix = "" return formatter }() var totalShowTimeElapsed: TimeInterval { return timeElapsed.totalShowTime } var totalShowTimeRemaining: TimeInterval { return durations.totalShowTime - timeElapsed.totalShowTime } var elapsed: TimeInterval { get { switch phase { case .PreShow: return timeElapsed.preShow case .Section1: return timeElapsed.section1 case .Break1: return timeElapsed.break1 case .Section2: return timeElapsed.section2 case .PostShow: return timeElapsed.postShow } } set(newElapsed) { switch phase { case .PreShow: timeElapsed.preShow = newElapsed case .Section1: timeElapsed.section1 = newElapsed case .Break1: timeElapsed.break1 = newElapsed case .Section2: timeElapsed.section2 = newElapsed case .PostShow: timeElapsed.postShow = newElapsed } } } var duration: TimeInterval { get { switch phase { case .PreShow: return durations.preShow case .Section1: return durations.section1 case .Break1: return durations.break1 case .Section2: return durations.section2 case .PostShow: return TimeInterval(0.0) } } set(newDuration) { switch phase { case .PreShow: durations.preShow = newDuration case .Section1: durations.section1 = newDuration case .Break1: durations.break1 = newDuration case .Section2: durations.section2 = newDuration case .PostShow: break } } } var remaining: TimeInterval { return max(duration - elapsed, 0) } @discardableResult mutating func incrementPhase() -> ShowPhase { switch phase { case .PreShow: phase = .Section1 case .Section1: // Before moving to the next phase of the show, // get the difference between the planned duration and the elapsed time // and add that to the next show section. let difference = duration - elapsed durations.section1 -= difference durations.section2 += difference phase = .Break1 case .Break1: phase = .Section2 case .Section2: phase = .PostShow case .PostShow: break } return phase } func asString(_ interval: TimeInterval) -> String { let roundedInterval = Int(interval) let seconds = roundedInterval % 60 let minutes = (roundedInterval / 60) % 60 let intervalNumber = NSNumber(value: interval * TimeInterval(100)) let subSeconds = formatter.string(from: intervalNumber)! return String(format: "%02d:%02d:\(subSeconds)", minutes, seconds) } func asShortString(_ interval: TimeInterval) -> String { let roundedInterval = Int(interval) let seconds = roundedInterval % 60 let minutes = (roundedInterval / 60) % 60 return String(format: "%02d:%02d", minutes, seconds) } } // Durations struct Durations { var preShow: TimeInterval = 0 var section1: TimeInterval = 0 var break1: TimeInterval = 0 var section2: TimeInterval = 0 /** Setup struct with timer durations - returns: Timer Duractions Struct -note: Until a real preferences mechenism is built for the Lyle: The Pledge Drive Durations are currently active. Remember to switch them back to the standard "useGeekSpeakDurations()" */ init() { useKBCZDurations() } var totalShowTime: TimeInterval { return section1 + section2 } func advancePhaseOnCompletion(_ phase: ShowPhase) -> Bool { switch phase { case .PreShow, .Section2, .Break1: return true case .Section1, .PostShow: return false } } mutating func useDemoDurations() { preShow = 2.0 section1 = 30.0 break1 = 2.0 section2 = 30.0 } /** The current KBCZ timings (59 minutes) */ mutating func useKBCZDurations() { preShow = 1.0 * oneMinute section1 = 29.5 * oneMinute break1 = 1.0 * oneMinute section2 = 29.5 * oneMinute } } // TimeElapsed struct TimeElapsed { var preShow: TimeInterval = 0.0 var section1: TimeInterval = 0.0 var break1: TimeInterval = 0.0 var section2: TimeInterval = 0.0 var postShow: TimeInterval = 0.0 var totalShowTime: TimeInterval { return section1 + section2 } } } // Timer Extention
mit
edaf98b2f00677bd213be71998f7a9fa
26.623894
81
0.608522
4.5837
false
false
false
false
soxjke/Redux-ReactiveSwift
Redux-ReactiveSwift/Classes/Store.swift
1
1642
// // Store.swift // Redux-ReactiveSwift // // Created by Petro Korienev on 10/12/17. // Copyright © 2017 Petro Korienev. All rights reserved. // import Foundation import ReactiveSwift import Result public protocol Defaultable { static var defaultValue: Self { get } } infix operator <~ : BindingPrecedence open class Store<State, Event> { public typealias Reducer = (State, Event) -> State fileprivate var innerProperty: MutableProperty<State> fileprivate var reducers: [Reducer] public required init(state: State, reducers: [Reducer]) { self.innerProperty = MutableProperty<State>(state) self.reducers = reducers } public func consume(event: Event) { self.innerProperty.value = reducers.reduce(self.innerProperty.value) { $1($0, event) } } } extension Store: PropertyProtocol { public var value: State { return innerProperty.value } public var producer: SignalProducer<State, NoError> { return innerProperty.producer } public var signal: Signal<State, NoError> { return innerProperty.signal } } public extension Store { @discardableResult public static func <~ <Source: BindingSource> (target: Store<State, Event>, source: Source) -> Disposable? where Event == Source.Value { return source.producer .take(during: target.innerProperty.lifetime) .startWithValues(target.consume) } } public extension Store where State: Defaultable { convenience init(reducers: [Reducer]) { self.init(state: State.defaultValue, reducers: reducers) } }
mit
8b01312446de5c969bddd43eb33c612d
25.047619
110
0.672761
4.251295
false
false
false
false
PauloMigAlmeida/Signals
SwiftSignalKit/Timer.swift
1
1344
import Foundation public final class Timer { private var timer: dispatch_source_t! private var timeout: NSTimeInterval private var repeat: Bool private var completion: Void -> Void private var queue: Queue public init(timeout: NSTimeInterval, repeat: Bool, completion: Void -> Void, queue: Queue) { self.timeout = timeout self.repeat = repeat self.completion = completion self.queue = queue } deinit { self.invalidate() } public func start() { self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue.queue) dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, Int64(self.timeout * NSTimeInterval(NSEC_PER_SEC))), self.repeat ? UInt64(self.timeout * NSTimeInterval(NSEC_PER_SEC)) : DISPATCH_TIME_FOREVER, 0); dispatch_source_set_event_handler(self.timer, { [weak self] in if let strongSelf = self { strongSelf.completion() if !strongSelf.repeat { strongSelf.invalidate() } } }) dispatch_resume(self.timer) } public func invalidate() { if self.timer != nil { dispatch_source_cancel(self.timer) self.timer = nil } } }
mit
ad3a4095dc6dd1e785e1ea55ee0e9fb6
31.780488
226
0.596726
4.37785
false
false
false
false
aleufms/JeraUtils
JeraUtils/Messages/Views/MessageView.swift
1
2731
// // MessageView.swift // beblueapp // // Created by Alessandro Nakamuta on 8/27/15. // Copyright (c) 2015 Jera. All rights reserved. // import UIKit import FontAwesome_swift public enum MessageViewType { case EmptyError case ConnectionError case GenericError case GenericMessage } public class MessageView: UIView { @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var textLabel: UILabel! @IBOutlet private weak var retryButton: UIButton! private var reloadBlock:(()->Void)? public class func instantiateFromNib() -> MessageView { let podBundle = NSBundle(forClass: self) if let bundleURL = podBundle.URLForResource("JeraUtils", withExtension: "bundle") { if let bundle = NSBundle(URL: bundleURL) { return bundle.loadNibNamed("MessageView", owner: nil, options: nil)!.first as! MessageView }else { assertionFailure("Could not load the bundle") } } assertionFailure("Could not create a path to the bundle") return MessageView() // return NSBundle.mainBundle().loadNibNamed("MessageView", owner: nil, options: nil).first as! MessageView } public var color: UIColor? { didSet { refreshAppearence() } } private func refreshAppearence() { textLabel.textColor = color imageView.tintColor = color } public func populateWith(text: String, messageViewType: MessageViewType, reloadBlock: (()->Void)? = nil ) { switch messageViewType { case .EmptyError: imageView.image = UIImage.fontAwesomeIconWithName(FontAwesome.List, textColor: UIColor.blackColor(), size: CGSize(width: 41, height: 41)).imageWithRenderingMode(.AlwaysTemplate) imageView.tintColor = color case .ConnectionError: imageView.image = UIImage.fontAwesomeIconWithName(FontAwesome.Globe, textColor: UIColor.blackColor(), size: CGSize(width: 41, height: 41)).imageWithRenderingMode(.AlwaysTemplate) imageView.tintColor = color case .GenericError: imageView.image = UIImage.fontAwesomeIconWithName(FontAwesome.ExclamationCircle, textColor: UIColor.blackColor(), size: CGSize(width: 41, height: 41)).imageWithRenderingMode(.AlwaysTemplate) imageView.tintColor = color case .GenericMessage: imageView.image = nil } textLabel.text = text self.reloadBlock = reloadBlock retryButton.hidden = (reloadBlock == nil) } @IBAction func retryButtonAction(sender: AnyObject) { if let reloadBlock = reloadBlock { reloadBlock() } } }
mit
88ae736f7e885927cdef8015615ce5be
32.716049
202
0.660198
5.020221
false
false
false
false
mbuchetics/DataSource
Example/ViewControllers/SeparatedSectionViewController.swift
1
5587
// // SeparatedSectionViewController.swift // Example // // Created by Michael Heinzl on 12.09.18. // Copyright © 2018 aaa - all about apps GmbH. All rights reserved. // import UIKit import DataSource class SeparatedSectionViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var counter = 0 lazy var dataSource: DataSource = { DataSource( cellDescriptors: [ CellDescriptor<DiffItem, TitleCell>() .configure { (item, cell, indexPath) in cell.textLabel?.text = item.text }, CellDescriptor<ColorItem, TitleCell>() .configure { (item, cell, indexPath) in cell.textLabel?.text = item.text }, CellDescriptor<IntItem, TitleCell>() .configure { (item, cell, indexPath) in cell.textLabel?.text = String(describing: item.number) } ]) }() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = dataSource tableView.delegate = dataSource tableView.separatorStyle = .none dataSource.sections = createSections() dataSource.reloadData(tableView, animated: false) } func createSections() -> [SectionType] { // Default section let texts = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"] let values = counter % 2 == 0 ? [1, 2, 3, 8, 9, 10] : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let defaultSection = SeparatedSection("Default section", items: values.map { DiffItem($0, text: texts[$0 - 1]) }) // Custom insets let insets = [16, 32, 48, 64].map { DiffItem($0, text: "\($0)") } let insetsSection = SeparatedSection("Custom insets", items: insets) { (transition) -> SeparatorStyle? in if transition.isFirst { return SeparatorStyle(leftInset: 0.0) } else { let inset = (transition.from as? DiffItem)?.value ?? 0 return SeparatorStyle(leftInset: CGFloat(inset)) } } // Custom colors let colors = [ColorItem(diffIdentifier: "color-1", color: .red, text: "red"), ColorItem(diffIdentifier: "color-2", color: .green, text: "green"), ColorItem(diffIdentifier: "color-3", color: .blue, text: "blue"), ColorItem(diffIdentifier: "color-4", color: .purple, text: "purple")] let colorSection = SeparatedSection("Custom colors", items: colors) { (transition) -> SeparatorStyle? in let color = (transition.from as? ColorItem)?.color return color.map { SeparatorStyle(edgeEnsets: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16), color: $0) } } // Custom view let customImageItems = [DiffItem(40, text: "custom image 1"), DiffItem(41, text: "custom image 2"), DiffItem(42, text: "custom image 3"), DiffItem(43, text: "custom image 4")] let customViewSection = SeparatedSection("Custom view", items: customImageItems) { (transition) -> UIView? in if transition.isFirst || transition.isLast { return nil } else { let imageView = UIImageView(image: #imageLiteral(resourceName: "wave")) imageView.contentMode = .scaleAspectFit return imageView } } // Custom height let customHeightItems = [2, 3, 5, 10].map { IntItem(diffIdentifier: "height-\($0)", number: $0) } let heightSection = SeparatedSection("Custom height", items: customHeightItems) { (transition) -> SeparatorStyle? in let height = (transition.from as? IntItem)?.number ?? 1 return SeparatorStyle(height: CGFloat(height)) } // Skip separator let skipSeparatorItems = (1...4).map { IntItem(diffIdentifier: "skip-separator-\($0)", number: $0) } let skipSeparatorSection = SeparatedSection("Skip separator", items: skipSeparatorItems) { (transition) -> SeparatorStyle? in let number = (transition.from as? IntItem)?.number ?? 0 return number % 2 == 0 ? SeparatorStyle(leftInset: 0) : nil } return [ defaultSection, insetsSection, colorSection, customViewSection, heightSection, skipSeparatorSection ] } @IBAction func refresh(_ sender: Any) { counter += 1 dataSource.sections = createSections() dataSource.reloadData(tableView, animated: true) } } struct IntItem: Diffable { let diffIdentifier: String let number: Int func isEqualToDiffable(_ other: Diffable?) -> Bool { guard let other = other as? IntItem else { return false } return other.number == self.number } } struct ColorItem: Diffable { let diffIdentifier: String let color: UIColor let text: String func isEqualToDiffable(_ other: Diffable?) -> Bool { guard let other = other as? ColorItem else { return false } return other.color == self.color && other.text == self.text } }
mit
25b334f349494ec6a47b2b046c54516d
35.75
133
0.551378
4.709949
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Search/MultipleIndex/IndexedQuery.swift
1
1137
// // IndexedQuery.swift // // // Created by Vladislav Fitc on 04/04/2020. // import Foundation /// The composition of search parameters with an associated index name public struct IndexedQuery { /// The name of the index to search in. public let indexName: IndexName /// The Query to filter results. public let query: Query /// - parameter indexName: The name of the index to search in. /// - parameter query: The Query to filter results. public init(indexName: IndexName, query: Query) { self.indexName = indexName self.query = query } } extension IndexedQuery: Codable { enum CodingKeys: String, CodingKey { case indexName case query = "params" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) indexName = try container.decode(forKey: .indexName) query = .empty } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(indexName, forKey: .indexName) try container.encode(query.urlEncodedString, forKey: .query) } }
mit
93e9e14d96db4b30c28219a3f437f24e
23.191489
70
0.703606
4.104693
false
false
false
false
PedroTrujilloV/TIY-Assignments
14--A-New-HIG/Cellect-Em-All/Cellect-Em-All/CharacterListTableViewController.swift
1
3739
// // CharacterListTableViewController.swift // Cellect-Em-All // // Created by Pedro Trujillo on 10/22/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit class CharacterListTableViewController: UITableViewController { var characters:[String]? var delegate: CharacterListTableViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return characters!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CharacterCell", forIndexPath: indexPath) // Configure the cell... let aCharacter = characters?[indexPath.row] cell.textLabel?.text = aCharacter return cell } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) delegate?.characterWasChosen((characters?[indexPath.row])!) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc0-1.0
f7ef902ce1d50e576e14e7eec74e3180
32.981818
157
0.691814
5.663636
false
false
false
false
PedroTrujilloV/TIY-Assignments
23--Partly-Cloudy-Skies/DudeWhereIsMyCar_Parse/DudeWhereIsMyCar/AppDelegate.swift
1
4606
// // AppDelegate.swift // DudeWhereIsMyCar // // Created by Pedro Trujillo on 11/3/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit //import Parse //import Bolts @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. Parse.setApplicationId("QQwQZOrQwLn0ZX1YmEspXAzBb1N9w80jE1mo09hW", clientKey: "0NzP1GpXWY8mPLbXgOQFysD5Jof1c3L3mIfM8wcO") // [Optional] Track statistics around application opens. //PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions) // let player = PFObject(className: "Player") // player["name"] = "Pedro" // player["score"] = 234 // player.saveInBackgroundWithBlock // { // (success: Bool, error: NSError?) -> Void in // if success // {print("YAY!!!")} // else // { // print(error?.description) // } // } // // let query = PFQuery(className: "Player") // query.whereKey("score", greaterThan: 500) // query.findObjectsInBackgroundWithBlock // { // (results: [PFObject]?, error: NSError?) -> Void in // if error == nil // { // print(results) // } // else // { // print(error?.description) // } // } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. //http://stackoverflow.com/questions/27715861/how-do-you-check-current-view-controller-class-in-swift if let wd = self.window { var vc = wd.rootViewController if(vc is UINavigationController) { vc = (vc as! UINavigationController).visibleViewController } if(vc is MapViewController) { // print("-------> Encontrado MapViewController!: ") // print(vc) (vc as! MapViewController).saveAnnotationsData() } } // let navController = window!.rootViewController as! UINavigationController //let citiesVC = navController.viewControllers[0] as! MapViewController //citiesVC.saveAnnotationsData() } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. // let navController = window?.rootViewController as! UINavigationController // let citiesVC = navController.viewControllers[0] as! MapViewController //citiesVC.loadAnnotationsData() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
cc0-1.0
79583fea56996fdbc4dbe99a4fec71f3
39.752212
285
0.609338
5.232955
false
false
false
false
grigaci/Sensoriada
SensoriadaTests/SRSendorsNodeTests.swift
1
1674
// // SRSendorsNodeTests.swift // SensoriadaExample // // Created by Bogdan Iusco on 1/11/15. // Copyright (c) 2015 Grigaci. All rights reserved. // import XCTest import Sensoriada class SRSendorsNodeTests: XCTestCase { func testWithEmptyDictionary() { let dictionary = [String : AnyObject]() let node = SRSensorsNode(dictionary: dictionary) XCTAssertEqual(node.nodeID, SRSensorsNodeErrorCodes.MissingNodeID.rawValue) XCTAssert(node.voltage == nil) XCTAssert(node.secondsAgo == nil) XCTAssert(node.date == nil) XCTAssert(node.sensors.count == 0) } func testWithValidDictionary() { var nodeDictionary = self.validSensorsNodesDictionary() let temperatureDictionary = self.validTemperatureSensorDictionary() let sensorsArray = [temperatureDictionary] nodeDictionary[SRSensorsNodeDictionaryKeys.sensors.rawValue] = sensorsArray let node = SRSensorsNode(dictionary: nodeDictionary) XCTAssertEqual(node.nodeID, nodeDictionary[SRSensorsNodeDictionaryKeys.nodeID.rawValue] as Int) let voltage = nodeDictionary[SRSensorsNodeDictionaryKeys.voltage.rawValue] as Int XCTAssertEqual(node.voltage!, Float(voltage)) XCTAssertEqual(node.secondsAgo, nodeDictionary[SRSensorsNodeDictionaryKeys.secondsAgo.rawValue] as Int) let dateString = node.date!.SR_toString() XCTAssertEqual(dateString, nodeDictionary[SRSensorsNodeDictionaryKeys.date.rawValue] as String) XCTAssert(node.sensors.count == 1) let testSensor = node.sensors[0] XCTAssert(testSensor is SRSensorTemperature) } }
mit
9ceea4be4e9511bde6af76b501043a85
35.391304
111
0.715651
4.348052
false
true
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Services/GameService.swift
1
3174
// // GameService.swift // ScoreReporterCore // // Created by Bradley Smith on 12/10/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation public struct GameService { fileprivate let client: APIClient public init(client: APIClient) { self.client = client } } // MARK: - Public public extension GameService { func update(with gameUpdate: GameUpdate, completion: DownloadCompletion?) { guard let userToken = KeychainService.load(.accessToken) else { let error = NSError(type: .invalidUserToken) completion?(DownloadResult(error: error)) return } let parameters: [String: Any] = [ APIConstants.Path.Keys.function: APIConstants.Path.Values.updateGame, APIConstants.Request.Keys.gameID: gameUpdate.gameID, APIConstants.Request.Keys.homeScore: gameUpdate.homeTeamScore, APIConstants.Request.Keys.awayScore: gameUpdate.awayTeamScore, APIConstants.Request.Keys.gameStatus: gameUpdate.gameStatus, APIConstants.Request.Keys.userToken: userToken ] client.request(.get, path: "", parameters: parameters) { result in switch result { case .success(let value): self.parseUpdateGame(response: value, completion: completion) case .failure(let error): completion?(DownloadResult(error: error)) } } } } // MARK: - Private private extension GameService { func parseUpdateGame(response: [String: Any], completion: DownloadCompletion?) { guard let updateDictionary = response[APIConstants.Response.Keys.updatedGameRecord] as? [String: AnyObject], let gameUpdate = GameUpdate(dictionary: updateDictionary) else { let error = NSError(type: .invalidResponse) completion?(DownloadResult(error: error)) return } Game.update(with: gameUpdate) { error in completion?(DownloadResult(error: error)) } } } public struct GameUpdate { public let gameID: NSNumber public let homeTeamScore: String public let awayTeamScore: String public let gameStatus: String public init?(dictionary: [String: Any]) { guard let gameID = dictionary[APIConstants.Response.Keys.gameID] as? NSNumber, let homeTeamScore = dictionary[APIConstants.Response.Keys.homeTeamScore] as? String, let awayTeamScore = dictionary[APIConstants.Response.Keys.awayTeamScore] as? String, let gameStatus = dictionary[APIConstants.Response.Keys.gameStatus] as? String else { return nil } self.gameID = gameID self.homeTeamScore = homeTeamScore self.awayTeamScore = awayTeamScore self.gameStatus = gameStatus } public init(game: Game, homeTeamScore: String, awayTeamScore: String, gameStatus: String) { self.gameID = game.gameID self.homeTeamScore = homeTeamScore self.awayTeamScore = awayTeamScore self.gameStatus = gameStatus } }
mit
c8f593c8b570a531ecc99503363cf923
33.48913
116
0.645446
4.679941
false
false
false
false
thirteen23/T23Kit-Colour
T23Kit-Colour/Swift/Colour.swift
1
56907
// // T23Kit-Colour.swift // T23Kit-Colour // // Created by Michael Van Milligan on 12/11/14. // Copyright (c) 2014 Thirteen23. All rights reserved. // import UIKit import Foundation import Darwin // MARK: - UIColor Extensions extension UIColor { var hue:CGFloat { get { return self.getHSB().h } } var saturation:CGFloat { get { return self.getHSB().s } } var brightness:CGFloat { get { return self.getHSB().b } } var red:CGFloat { get { return self.getRGB().r } } var green:CGFloat { get { return self.getRGB().g } } var blue:CGFloat { get { return self.getRGB().b } } var alpha:CGFloat { get { return CGColorGetAlpha(self.CGColor) } } var hexString:String { get { let rgb = self.getRGB() var R:UInt8 = UInt8(255.0 * rgb.r) var G:UInt8 = UInt8(255.0 * rgb.g) var B:UInt8 = UInt8(255.0 * rgb.b) return NSString(format: "%02x%02x%02x", R, G, B) as String } } /// /// Initialize a UIColor with RYB colour values /// /// UIColor returned is generated from RYB->RGB conversion. (Please /// see http://vis.computer.org/vis2004/DVD/infovis/papers/gossett.pdf) /// /// :param: red Red value as percentage /// :param: yellow Yellow value as percentage /// :param: blue Blue value as percentage /// :returns: A converted UIColor object convenience init(red: CGFloat, yellow: CGFloat, blue: CGFloat, alpha: CGFloat) { let ryb:RYB = RYB(r: red, y: yellow, b: blue) let rgb:RGB = ryb.toRGB() self.init(red: rgb.r, green: rgb.g, blue: rgb.b, alpha: alpha) } /// /// Initialize a UIColor with Hex colour values /// /// Proper value regex: ^(#{0,2}|0x{0,1})([a-f]|[A-F]|\d){1,6} /// /// :param: hexString String of hexidecimal value for colour /// :returns: A UIColor object convenience init(hexString: String, alpha: CGFloat) { var r:CGFloat = 0.0 var g:CGFloat = 0.0 var b:CGFloat = 0.0 if 9 > hexString.utf16Count { let scanner:NSScanner = NSScanner(string: hexString) scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#") var hexInt:UInt32 = 0 if scanner.scanHexInt(&hexInt) { r = CGFloat(((hexInt & 0xFF0000) >> 16)) / 255.0 g = CGFloat(((hexInt & 0xFF00) >> 8)) / 255.0 b = CGFloat(((hexInt & 0xFF) >> 0)) / 255.0 } } self.init(red: r, green: g, blue: b, alpha: alpha) } /// /// Helper method to convert standard UIColor API to our HSB /// struct /// /// :returns: A HSB structure func getHSB() -> HSB { var h:CGFloat = 0.0 var s:CGFloat = 0.0 var b:CGFloat = 0.0 var a:CGFloat = 0.0 self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return HSB(h: h, s: s, b: b) } /// /// Helper method to convert standard UIColor API to our RGB /// struct /// /// :returns: A RGB structure func getRGB() -> RGB { var r:CGFloat = 0.0 var g:CGFloat = 0.0 var b:CGFloat = 0.0 var a:CGFloat = 0.0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return RGB(r: r, g: g, b: b) } /// /// Convert current colour to the XYZ colour space /// /// Values returned are nominal values and therefore aren't /// normalized in any way, e.g., not a ratio or percentage. /// /// The conversions are from RGB space and uses the sRGB matrix for calculation, /// i.e, sRGB matrices to XYZ and back with (Observer = 2°, Illuminant = D65) /// using Bradford adaptation. /// /// :returns: A XYZ structure func getXYZ() -> XYZ { return self.getRGB().toXYZ(.sRGBD65) } /// /// Convert current colour to the Hunter 1948 L, a, b colour space /// /// Values returned are nominal values and therefore aren't normalized in any way, /// e.g., not a ratio or percentage. /// /// :returns: A HLAB structure func getHLAB() -> HLAB { return self.getRGB().toHLAB(.sRGBD65) } /// /// Convert current colour to the CIELAB colour space /// /// Values returned are nominal values and therefore aren't normalized in any way, /// e.g., not a ratio or percentage. /// /// :returns: A LAB structure func getLAB() -> LAB { return self.getRGB().toLAB(.sRGBD65) } /// /// Convert current colour to the CIELUV colour space /// /// Values returned are nominal values and therefore aren't normalized in any way, /// e.g., not a ratio or percentage. /// /// :returns: A LUV structure func getLUV() -> LUV { return self.getRGB().toLUV(.sRGBD65) } /// /// Convert current colour to the CIELCH(ab) colour space /// /// Values returned are nominal values and therefore aren't normalized in any way, /// e.g., not a ratio or percentage. /// /// :returns: A LCHab structure func getLCHab() -> LCHab { return self.getRGB().toLCHab(.sRGBD65) } /// /// Convert current colour to the CIELCH(uv) colour space /// /// Values returned are nominal values and therefore aren't normalized in any way, /// e.g., not a ratio or percentage. /// /// :returns: A LCHuv structure func getLCHuv() -> LCHuv { return self.getRGB().toLCHuv(.sRGBD65) } /// /// Convert current colour to the CMYK colour space /// /// Values returned are normalized percentage values 0.0f-1.0f /// /// :returns: A CMYK structure func getCMYK() -> CMYK { return self.getRGB().toCMYK() } /// /// Convert current colour to the HSL colour space /// /// Values returned are normalized percentage values 0.0f-1.0f. The Hue value is the /// radian angle over 2π. Saturation and lightness are both just the normalized /// percentage. /// /// :returns: A HSL structure func getHSL() -> HSL { return self.getRGB().toHSL() } /// /// Convert current colour to the HSI colour space /// /// Values returned are normalized percentage values 0.0f-1.0f. The Hue value is the /// radian angle over 2π. Saturation and intensity are both just the normalized /// percentage. /// /// :returns: A HSI structure func getHSI() -> HSI { return self.getRGB().toHSI() } /// /// Grab the triadic set from the HSV space /// /// Tuple contains 3 UIColors: The original colour and 2 others where the hue is /// shifted ±120º while keeping S and V held constant /// /// :returns: A 3-tuple of triadic UIColors func getTriadic() -> (thisColor: UIColor, right: UIColor, left: UIColor) { let hsb:HSB = self.getHSB() let inflect:CGFloat = 120.0 let HUE:CGFloat = (hsb.h * M_2PI) let HUEM:CGFloat = (0.0 > HUE - inflect.radians) ? M_2PI + (HUE - inflect.radians) : HUE - inflect.radians let HUEP:CGFloat = (M_2PI < HUE + inflect.radians) ? (HUE + inflect.radians) - M_2PI : HUE + inflect.radians let plus120:UIColor = UIColor(hue: HUEP, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) let minus120:UIColor = UIColor(hue: HUEM, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) return (self, plus120, minus120) } /// /// Grab the split complements from the HSV space /// /// Tuple contains 3 UIColors: The original colour and 2 others where the hue is /// shifted ±150º while keeping S and V held constant /// /// :returns: A 3-tuple of split complement UIColors func getSplitCompliments() -> (thisColor: UIColor, right: UIColor, left: UIColor) { let hsb:HSB = self.getHSB() let inflect:CGFloat = 150.0 let HUE:CGFloat = (hsb.h * M_2PI) let HUEM:CGFloat = (0.0 > HUE - inflect.radians) ? M_2PI + (HUE - inflect.radians) : HUE - inflect.radians let HUEP:CGFloat = (M_2PI < HUE + inflect.radians) ? (HUE + inflect.radians) - M_2PI : HUE + inflect.radians let plus150:UIColor = UIColor(hue: HUEP, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) let minus150:UIColor = UIColor(hue: HUEM, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) return (self, plus150, minus150) } /// /// Grab the analogous set from the HSV space /// /// Tuple contains 3 UIColors: The original colour and 2 others where the hue is /// shifted ±30º while keeping S and V held constant /// /// :returns: A 3-tuple of analogous UIColors func getAnalogous() -> (thisColor: UIColor, right: UIColor, left: UIColor) { let hsb:HSB = self.getHSB() let inflect:CGFloat = 30.0 let HUE:CGFloat = (hsb.h * M_2PI) let HUEM:CGFloat = (0.0 > HUE - inflect.radians) ? M_2PI + (HUE - inflect.radians) : HUE - inflect.radians let HUEP:CGFloat = (M_2PI < HUE + inflect.radians) ? (HUE + inflect.radians) - M_2PI : HUE + inflect.radians let plus30:UIColor = UIColor(hue: HUEP, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) let minus30:UIColor = UIColor(hue: HUEM, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) return (self, plus30, minus30) } /// /// Grab the complement from the HSV space /// /// UIColor returned is the colour rotated H by 180º while keeping S and V held /// constant /// /// :returns: A UIColor complement func getCompliment() -> UIColor { let hsb:HSB = self.getHSB() var HUE:CGFloat = (hsb.h * M_2PI) HUE += CGFloat(M_PI) HUE = (HUE > (M_2PI)) ? HUE - M_2PI : HUE let H:CGFloat = (HUE / M_2PI) return UIColor(hue: H, saturation: hsb.s, brightness: hsb.b, alpha: self.alpha) } /// /// Acquire colour distance measure between current UIColor object and the UIColor /// compare parameter. /// /// Return values vary based on what distance metric used. However, all distance /// values returned base closeness to 0.0f as closeness in colour range. /// (See literature on the topic) /// /// Colour Distance Formulas: /// /// T23UIColourDistanceFormulaCEI76: This is the formula based on the CIE76 /// standard /// /// T23UIColourDistanceFormulaCMC1984_1_1: This is the formula based on the CMC /// l:c (1984) standard where l=1 & c=1 /// /// T23UIColourDistanceFormulaCMC1984_2_1: This is the formula based on the CMC /// l:c (1984) standard where l=2 & c=1 /// /// T23UIColourDistanceFormulaCEI94_GRAPHICS: This is the formula based on the /// CIE94 standard using the graphics KL, K1 and K2 values of: {1, 0.045, 0.015} /// /// T23UIColourDistanceFormulaCEI94_TEXTILES: This is the formula based on the /// CIE94 standard using the textiles KL, K1 and K2 values of {2, 0.048, 0.014} /// /// T23UIColourDistanceFormulaCIEDE2000: This is the formula based on the /// CIEDE2000 standard /// /// :returns: A distance value as a CGFloat func getDistanceBetweenUIColor(compare: UIColor, options: ColourDistanceOptions) -> CGFloat { let cmpLAB = compare.getLAB() let selfLAB = self.getLAB() var delta:CGFloat = 100.0 switch options { case .CMC198411: delta = cmc1984(selfLAB, cmpLAB, 1.0, 1.0) case .CMC198421: delta = cmc1984(selfLAB, cmpLAB, 2.0, 1.0) case .CIE94G: delta = cie94(selfLAB, cmpLAB, .graphics) case .CIE94T: delta = cie94(selfLAB, cmpLAB, .textiles) case .CIEDE2000: delta = ciede2000(selfLAB, cmpLAB, 1.0, 1.0, 1.0) default: delta = cie76(selfLAB, cmpLAB) } return delta } } // MARK: - Operators infix operator ** { associativity left precedence 160 } func ** (left: Double, right: Double) -> Double { return pow(left, right) } func ** (left: CGFloat, right: CGFloat) -> CGFloat { return pow(left, right) } func ** (left: Float, right: Float) -> Float { return powf(left, right) } infix operator **= { associativity right precedence 90 } func **= (inout left: Double, right: Double) { left = left ** right } func **= (inout left: CGFloat, right: CGFloat) { left = left ** right } func **= (inout left: Float, right: Float) { left = left ** right } infix operator -** { associativity left precedence 160 } func -** (left: Double, right: Double) -> Double { return (0.0 <= left) ? pow(left, right) : -1.0 * pow(-1.0 * left, right) } func -** (left: CGFloat, right: CGFloat) -> CGFloat { return (0.0 <= left) ? pow(left, right) : -1.0 * pow(-1.0 * left, right) } func -** (left: Float, right: Float) -> Float { return (0.0 <= left) ? powf(left, right) : -1.0 * powf(-1.0 * left, right) } infix operator -**= { associativity right precedence 90 } func -**= (inout left: Double, right: Double) { left = left -** right } func -**= (inout left: CGFloat, right: CGFloat) { left = left -** right } func -**= (inout left: Float, right: Float) { left = left -** right } // MARK: - Floating Point Extensions extension CGFloat { var radians:CGFloat { get { return (CGFloat(M_PI) / 180.0) * self } } var degrees:CGFloat { get { return (180.0 / CGFloat(M_PI)) * self } } } extension Double { var radians:Double { get { return (M_PI / 180.0) * self } } var degrees:Double { get { return (180.0 / M_PI) * self } } } extension Float { var radians:Float { get { return (Float(M_PI) / 180.0) * self } } var degrees:Float { get { return (180.0 / Float(M_PI)) * self } } } // MARK: - Constants let M_2PI:CGFloat = CGFloat(M_PI) * 2.0 let ɛ:CGFloat = 0.008856 let κ:CGFloat = 7.787 // MARK: - Enums public enum ColourDistanceOptions: String { case CIE76 = "CIE76" case CMC198411 = "CMC198411" case CMC198421 = "CMC198421" case CIE94G = "CIE94G" case CIE94T = "CIE94T" case CIEDE2000 = "CIEDE2000" } public enum RGBWorkingSpace: String { case AdobeD65 = "AdobeD65" case AppleD65 = "AppleD65" case BestD50 = "BestD50" case BetaD50 = "BetaD50" case BruceD65 = "BruceD65" case CIEE = "CIEE" case ColormatchD50 = "ColormatchD50" case DonD50 = "DonD50" case ECID50 = "ECID50" case EktaSpaceD50 = "EktaSpaceD50" case NTSCC = "NTSCC" case PalSecamD65 = "PalSecamD65" case ProPhotoD50 = "ProPhotoD50" case SMPTECD65 = "SMPTECD65" case sRGBD65 = "sRGBD65" case WideGamutD50 = "WideGamutD50" case AdobeD50 = "AdobeD50" case AppleD50 = "AppleD50" case BruceD50 = "BruceD50" case CEID50 = "CEID50" case NTSCD50 = "NTSCD50" case PalSecamD50 = "PalSecamD50" case SMPTECD50 = "SMPTECD50" case sRGBD50 = "sRGBD50" var referenceWhite:ReferenceWhite { get { var rw:ReferenceWhite switch self { case NTSCC: rw = .C case BestD50: fallthrough case BetaD50: fallthrough case ColormatchD50: fallthrough case DonD50: fallthrough case ECID50: fallthrough case EktaSpaceD50: fallthrough case ProPhotoD50: fallthrough case WideGamutD50: fallthrough case AdobeD50: fallthrough case AppleD50: fallthrough case BruceD50: fallthrough case CEID50: fallthrough case NTSCD50: fallthrough case PalSecamD50: fallthrough case SMPTECD50: fallthrough case sRGBD50: rw = .D50 case AdobeD65: fallthrough case AppleD65: fallthrough case BruceD65: fallthrough case PalSecamD65: fallthrough case SMPTECD65: fallthrough case sRGBD65: rw = .D65 case CIEE: rw = .E default: rw = .D65 } return rw } } } public enum ReferenceWhite: String { case A = "A" case B = "B" case C = "C" case D50 = "D50" case D55 = "D55" case D65 = "D65" case D75 = "D75" case E = "E" case F2 = "F2" case F7 = "F7" case F11 = "F11" } public enum CIE94 { case graphics case textiles } // MARK: - Structures struct ReferenceWhiteMatrix { var Xw:CGFloat = 0.0 var Yw:CGFloat = 0.0 var Zw:CGFloat = 0.0 } struct RGBWorkingSpaceMatrix { var _00:CGFloat = 0.0 var _01:CGFloat = 0.0 var _02:CGFloat = 0.0 var _10:CGFloat = 0.0 var _11:CGFloat = 0.0 var _12:CGFloat = 0.0 var _20:CGFloat = 0.0 var _21:CGFloat = 0.0 var _22:CGFloat = 0.0 func applyWorkingSpace(xr: CGFloat, yg: CGFloat, zb: CGFloat) -> (xr: CGFloat, yg: CGFloat, zb: CGFloat) { let a:CGFloat = (xr * self._00) + (yg * self._01) + (zb * self._02) let b:CGFloat = (xr * self._10) + (yg * self._11) + (zb * self._12) let c:CGFloat = (xr * self._20) + (yg * self._21) + (zb * self._22) return (a, b, c) } } public struct RGB { public var r:CGFloat = 0.0 public var g:CGFloat = 0.0 public var b:CGFloat = 0.0 public init() {} public init(r: CGFloat, g: CGFloat, b: CGFloat) { self.r = r self.g = g self.b = b } mutating func sanitize() -> RGB { self.r = 0 != signbit(self.r) ? self.r * -1.0 : self.r self.r = (1.0 > (self.r * (100000.0))) ? 0.0 : (1.0 < self.r) ? 1.0 : self.r self.g = 0 != (signbit(self.g)) ? self.g * -1.0 : self.g; self.g = (1.0 > (self.g * (100000.0))) ? 0.0 : (1.0 < self.g) ? 1.0 : self.g; self.b = 0 != (signbit(self.b)) ? self.b * -1.0 : self.b; self.b = (1.0 > (self.b * (100000.0))) ? 0.0 : (1.0 < self.b) ? 1.0 : self.b; return self } public func toCMYK() -> CMYK { var cmyk:CMYK = CMYK() var m:CGFloat = max(max(self.r, self.g), self.b) cmyk.k = 1.0 - m cmyk.c = (1.0 - self.r - cmyk.k) / (1.0 - cmyk.k) cmyk.m = (1.0 - self.g - cmyk.k) / (1.0 - cmyk.k) cmyk.y = (1.0 - self.b - cmyk.k) / (1.0 - cmyk.k) return cmyk } public func toHSL() -> HSL { var hsl:HSL = HSL() let mn:CGFloat = min(min(self.r, self.g), self.b) let mx:CGFloat = max(max(self.r, self.g), self.b) let delta:CGFloat = mx - mn hsl.l = (mx + mn) / 2.0 if 0.0 == mx { hsl.h = 0.0 hsl.s = 0.0 } else { hsl.s = (0.5 > hsl.l) ? delta / (mx + mn) : delta / (2.0 - mx - mn) let dr:CGFloat = (((mx - self.r) / 6.0) + (delta / 2.0)) / delta let dg:CGFloat = (((mx - self.g) / 6.0) + (delta / 2.0)) / delta let db:CGFloat = (((mx - self.b) / 6.0) + (delta / 2.0)) / delta if self.r == mx { hsl.h = db - dg } else if self.g == mx { hsl.h = (1.0 / 3.0) + dr - db } else if self.b == mx { hsl.h = (2.0 / 3.0) + dg - dr } hsl.h = (0.0 > hsl.h) ? hsl.h + 1.0 : (1.0 < hsl.h) ? hsl.h - 1.0 : hsl.h } return hsl } public func toHSI() -> HSI { var hsi:HSI = HSI() let mn:CGFloat = min(min(self.r, self.g), self.b) let mx:CGFloat = max(max(self.r, self.g), self.b) let delta:CGFloat = mx - mn hsi.i = (1.0 / 3.0) * (self.r + self.b + self.g) if 0.0 == delta { hsi.h = 0.0 hsi.s = 0.0 } else { hsi.h = (mx == self.r) ? fmod(((self.g - self.b) / delta), 6.0) : (mx == self.g) ? (self.b - self.r) / delta + 2.0 : (self.r - self.g) / delta + 4.0 hsi.h *= 60.0 hsi.h = hsi.h.radians / M_2PI hsi.h = (0.0 > hsi.h) ? hsi.h + 1.0 : (1.0 < hsi.h) ? hsi.h - 1.0 : hsi.h hsi.s = 1.0 - (mn / (hsi.i)) } return hsi } public func toXYZ(rgbSpace: RGBWorkingSpace) -> XYZ { var xyz:XYZ = XYZ() let workingMatrix:[RGBWorkingSpaceMatrix] = Matrices.WorkingMatrices[rgbSpace]! let matrix:RGBWorkingSpaceMatrix = workingMatrix.first! let gamma:CGFloat = Gamma.RGB[rgbSpace]! xyz.x = self.r xyz.y = self.g xyz.z = self.b let sR:CGFloat = 0 != signbit(xyz.x) ? -1.0 : 1.0 let sG:CGFloat = 0 != signbit(xyz.y) ? -1.0 : 1.0 let sB:CGFloat = 0 != signbit(xyz.z) ? -1.0 : 1.0 if 0.0 < gamma { xyz.x -**= gamma xyz.y -**= gamma xyz.z -**= gamma } else if 0.0 > gamma { func translate(xyz: CGFloat) -> CGFloat { return (0.04045 >= fabs(xyz)) ? fabs(xyz) / 12.92 : ((fabs(xyz) + 0.055) / 1.055) -** 2.4 } xyz.x = translate(xyz.x) xyz.y = translate(xyz.y) xyz.z = translate(xyz.z) xyz.x *= sR xyz.y *= sG xyz.z *= sB } else { func translate(xyz: CGFloat) -> CGFloat { let lte:CGFloat = (2700.0 * fabs(xyz) / 24389.0) let gt:CGFloat = ((((1000000.0 * fabs(xyz) + 480000.0) * fabs(xyz) + 76800.0) * fabs(xyz) + 4096.0) / 1560896.0) return (0.08 >= fabs(xyz)) ? lte : gt } xyz.x = translate(xyz.x) xyz.y = translate(xyz.y) xyz.z = translate(xyz.z) xyz.x *= sR xyz.y *= sG xyz.z *= sB } xyz.x *= 100.0 xyz.y *= 100.0 xyz.z *= 100.0 let apply = matrix.applyWorkingSpace(xyz.x, yg: xyz.y, zb: xyz.z) xyz.x = apply.xr xyz.y = apply.yg xyz.z = apply.zb return xyz } public func toHLAB(rgbSpace: RGBWorkingSpace) -> HLAB { return self.toXYZ(rgbSpace).toHLAB() } public func toLAB(rgbSpace: RGBWorkingSpace) -> LAB { return self.toXYZ(rgbSpace).toLAB(rgbSpace.referenceWhite) } public func toLUV(rgbSpace: RGBWorkingSpace) -> LUV { return self.toXYZ(rgbSpace).toLUV(rgbSpace.referenceWhite) } public func toLCHab(rgbSpace: RGBWorkingSpace) -> LCHab { return self.toXYZ(rgbSpace).toLAB(rgbSpace.referenceWhite).toLCHab() } public func toLCHuv(rgbSpace: RGBWorkingSpace) -> LCHuv { return self.toXYZ(rgbSpace).toLUV(rgbSpace.referenceWhite).toLCHuv() } } public struct XYZ { public var x:CGFloat = 0.0 public var y:CGFloat = 0.0 public var z:CGFloat = 0.0 public init() {} public init(x: CGFloat, y: CGFloat, z: CGFloat) { self.x = x self.y = y self.z = z } public func toHLAB() -> HLAB { var hlab:HLAB = HLAB() hlab.l = 10.0 * sqrt(self.y) hlab.a = 17.5 * (((1.02 * self.x) - self.y) / sqrt(self.y)) hlab.b = 7.0 * ((self.y - (0.847 * self.z)) / sqrt(self.y)) return hlab } public func toLAB(refWhite: ReferenceWhite) -> LAB { var lab:LAB = LAB() let matrix:ReferenceWhiteMatrix = Matrices.ReferenceWhiteMatrices[refWhite]! var X:CGFloat = self.x / (matrix.Xw * 100.0) var Y:CGFloat = self.y / (matrix.Yw * 100.0) var Z:CGFloat = self.z / (matrix.Zw * 100.0) X = (X > ɛ) ? X ** (1.0 / 3.0) : (κ * X) + (16.0 / 116.0) Y = (Y > ɛ) ? Y ** (1.0 / 3.0) : (κ * Y) + (16.0 / 116.0) Z = (Z > ɛ) ? Z ** (1.0 / 3.0) : (κ * Z) + (16.0 / 116.0) lab.l = (116.0 * Y) - 16.0 lab.a = 500.0 * (X - Y) lab.b = 200.0 * (Y - Z) return lab } public func toLUV(refWhite: ReferenceWhite) -> LUV { var luv:LUV = LUV() let matrix:ReferenceWhiteMatrix = Matrices.ReferenceWhiteMatrices[refWhite]! luv.u = (4.0 * self.x) / (self.x + (15.0 * self.y) + (3.0 * self.z)) luv.v = (9.0 * self.y) / (self.x + (15.0 * self.y) + (3.0 * self.z)) luv.l = self.y / 100.0 luv.l = (ɛ < luv.l) ? luv.l ** (1.0 / 3.0) : (κ * luv.l) + (16.0 / 116.0) var refU:CGFloat = (4.0 * (matrix.Xw * 100.0)) / ((matrix.Xw * 100.0) + (15.0 * (matrix.Yw * 100.0)) + (3.0 * (matrix.Zw * 100.0))) var refV:CGFloat = (9.0 * (matrix.Yw * 100.0)) / ((matrix.Xw * 100.0) + (15.0 * (matrix.Yw * 100.0)) + (3.0 * (matrix.Zw * 100.0))) luv.l = (116.0 * luv.l) - 16.0 luv.u = 13.0 * luv.l * (luv.u - refU) luv.v = 13.0 * luv.l * (luv.v - refV) return luv } public func toRGB(rgbSpace: RGBWorkingSpace) -> RGB { var rgb:RGB = RGB() /* * We want all these impliclty unwrapped optionals to crash immediately because it means * that we have messed up our matrices somehow. */ let workingMatrix:[RGBWorkingSpaceMatrix] = Matrices.WorkingMatrices[rgbSpace]! let matrix = workingMatrix.last! let gamma:CGFloat = Gamma.RGB[rgbSpace]! let apply = matrix.applyWorkingSpace(self.x / 100.0, yg: self.y / 100.0, zb: self.z / 100.0) rgb.r = apply.xr rgb.g = apply.yg rgb.b = apply.zb let sR:CGFloat = 0 != signbit(rgb.r) ? -1.0 : 1.0 let sG:CGFloat = 0 != signbit(rgb.g) ? -1.0 : 1.0 let sB:CGFloat = 0 != signbit(rgb.b) ? -1.0 : 1.0 if 0.0 < gamma { rgb.r -**= (1.0 / gamma) rgb.g -**= (1.0 / gamma) rgb.b -**= (1.0 / gamma) } else if 0.0 > gamma { rgb.r = (abs(rgb.r) <= 0.0031308) ? 12.92 * abs(rgb.r) : 1.055 * (abs(rgb.r) -** (1.0 / 2.4)) - 0.055 rgb.g = (abs(rgb.g) <= 0.0031308) ? 12.92 * abs(rgb.g) : 1.055 * (abs(rgb.g) -** (1.0 / 2.4)) - 0.055 rgb.b = (abs(rgb.b) <= 0.0031308) ? 12.92 * abs(rgb.b) : 1.055 * (abs(rgb.b) -** (1.0 / 2.4)) - 0.055 rgb.r *= sR rgb.g *= sG rgb.b *= sB } else { rgb.r = (abs(rgb.r) <= (216.0 / 24389.0)) ? (abs(rgb.r) * 24389.0 / 2700.0) : (1.16 * (fabs(rgb.r) -** (1.0 / 3.0)) - 0.16) rgb.g = (abs(rgb.g) <= (216.0 / 24389.0)) ? (fabs(rgb.g) * 24389.0 / 2700.0) : (1.16 * (abs(rgb.g) -** (1.0 / 3.0)) - 0.16) rgb.b = (abs(rgb.b) <= (216.0 / 24389.0)) ? (abs(rgb.b) * 24389.0 / 2700.0) : (1.16 * (abs(rgb.b) -** (1.0 / 3.0)) - 0.16) rgb.r *= sR rgb.g *= sG rgb.b *= sB } return rgb.sanitize() } } public struct RYB { public var r:CGFloat = 0.0 public var y:CGFloat = 0.0 public var b:CGFloat = 0.0 public init() {} public init(r: CGFloat, y: CGFloat, b: CGFloat) { self.r = r self.y = y self.b = b } public func toRGB() -> RGB { var rgb:RGB = RGB() func cubicInterpolation(t: CGFloat, a: CGFloat, b: CGFloat) -> CGFloat { return (a + (t * t * (3.0 - 2.0 * t)) * (b - a)) } var x0 = cubicInterpolation(self.b, 1.0, 0.163) var x1 = cubicInterpolation(self.b, 1.0, 0.0) var x2 = cubicInterpolation(self.b, 1.0, 0.5) var x3 = cubicInterpolation(self.b, 1.0, 0.2) var y0 = cubicInterpolation(self.y, x0, x1) var y1 = cubicInterpolation(self.y, x2, x3) rgb.r = cubicInterpolation(self.r, y0, y1) x0 = cubicInterpolation(self.b, 1.0, 0.373) x1 = cubicInterpolation(self.b, 1.0, 0.66) x2 = cubicInterpolation(self.b, 0.0, 0.0) x3 = cubicInterpolation(self.b, 0.5, 0.094) y0 = cubicInterpolation(self.y, x0, x1) y1 = cubicInterpolation(self.y, x2, x3) rgb.g = cubicInterpolation(self.r, y0, y1) x0 = cubicInterpolation(self.b, 1.0, 0.6) x1 = cubicInterpolation(self.b, 0.0, 0.2) x2 = cubicInterpolation(self.b, 0.0, 0.5) x3 = cubicInterpolation(self.b, 0.0, 0.0) y0 = cubicInterpolation(self.y, x0, x1) y1 = cubicInterpolation(self.y, x2, x3) rgb.b = cubicInterpolation(self.r, y0, y1) return rgb.sanitize() } } public struct HSB { public var h:CGFloat = 0.0 public var s:CGFloat = 0.0 public var b:CGFloat = 0.0 public init() {} public init(h: CGFloat, s: CGFloat, b: CGFloat) { self.h = h self.s = s self.b = b } } public struct HSI { public var h:CGFloat = 0.0 public var s:CGFloat = 0.0 public var i:CGFloat = 0.0 public init() {} public init(h: CGFloat, s: CGFloat, i: CGFloat) { self.h = h self.s = s self.i = i } public func toRGB() -> RGB { var rgb:RGB = RGB() if 0.0 <= self.h && (M_2PI / 3.0) >= self.h { rgb.b = (1.0 / 3.0) * (1.0 - self.s) rgb.r = (1.0 / 3.0) * ((self.s * cos(self.h)) / cos((M_2PI / 6.0) - self.h)) rgb.g = 1.0 - (rgb.b + rgb.r) } else if (M_2PI / 3.0) < h && ((2.0 * M_2PI) / 3.0) >= self.h { let hA:CGFloat = self.h - (M_2PI / 3.0) rgb.r = (1.0 / 3.0) * (1.0 - self.s) rgb.g = (1.0 / 3.0) * ((self.s * cos(hA)) / cos((M_2PI / 6.0) - hA)) rgb.b = 1.0 - (rgb.g + rgb.r) } else { let hA:CGFloat = self.h - (2.0 * M_2PI / 3.0) rgb.g = (1.0 / 3.0) * (1.0 - self.s) rgb.b = (1.0 / 3.0) * ((self.s * cos(hA)) / cos((M_2PI / 6.0) - hA)) rgb.r = 1.0 - ((rgb.g) + (rgb.b)) } return rgb.sanitize() } } public struct HSL { public var h:CGFloat = 0.0 public var s:CGFloat = 0.0 public var l:CGFloat = 0.0 public init() {} public init(h: CGFloat, s: CGFloat, l: CGFloat) { self.h = h self.s = s self.l = l } public func toRGB() -> RGB { var rgb:RGB = RGB(r: 1.0, g: 1.0, b: 1.0) func hue2rgb(v1: CGFloat, v2: CGFloat, H: CGFloat) -> CGFloat { var vH:CGFloat = H if (0.0 > vH) { vH += 1.0 } if (1.0 < vH) { vH -= 1.0 } return (1.0 > (6.0 * vH)) ? (v1 + (v2 - v1) * 6.0 * vH) : (1.0 > (2.0 * vH)) ? (v2) : (2.0 > (3.0 * vH)) ? (v1 + (v2 - v1) * ((2.0 / 3.0) - vH) * 6.0) : (v1) } if 0.0 != self.s { let var_2:CGFloat = (0.5 > self.l) ? self.l * (1.0 + self.s) : (self.l + self.s) - (self.s * self.l); let var_1:CGFloat = 2.0 * self.l - var_2; rgb.r = hue2rgb(var_1, var_2, self.h + (1.0 / 3.0)); rgb.g = hue2rgb(var_1, var_2, self.h); rgb.b = hue2rgb(var_1, var_2, self.h - (1.0 / 3.0)); } return rgb.sanitize() } } public struct HSV { public var h:CGFloat = 0.0 public var s:CGFloat = 0.0 public var v:CGFloat = 0.0 public init() {} public init(h: CGFloat, s: CGFloat, v: CGFloat) { self.h = h self.s = s self.v = v } public func toRGB() -> RGB { var rgb:RGB = RGB() let h:CGFloat = (self.h * CGFloat(M_2PI)).degrees let i:Int = Int(floor(h)) let f:CGFloat = h - CGFloat(i) let p:CGFloat = self.v * (1.0 - self.s) let q:CGFloat = self.v * (1.0 - self.s * f) let t:CGFloat = self.v * (1.0 - self.s * (1.0 - f)) switch (i) { case 0: rgb.r = v rgb.g = t rgb.b = p case 1: rgb.r = q rgb.g = v rgb.b = p case 2: rgb.r = p rgb.g = v rgb.b = t case 3: rgb.r = p rgb.g = q rgb.b = v case 4: rgb.r = t rgb.g = p rgb.b = v default: rgb.r = v rgb.g = p rgb.b = q } return rgb.sanitize() } } public struct LCHab { public var l:CGFloat = 0.0 public var c:CGFloat = 0.0 public var h:CGFloat = 0.0 public init() {} public init(l: CGFloat, c: CGFloat, h: CGFloat) { self.l = l self.c = c self.h = h } public func toRGB() -> RGB { return RGB() } } public struct LCHuv { public var l:CGFloat = 0.0 public var c:CGFloat = 0.0 public var h:CGFloat = 0.0 public init() {} public init(l: CGFloat, c: CGFloat, h: CGFloat) { self.l = l self.c = c self.h = h } public func toRGB() -> RGB { return RGB() } } public struct HLAB { public var l:CGFloat = 0.0 public var a:CGFloat = 0.0 public var b:CGFloat = 0.0 public init() {} public init(l: CGFloat, a: CGFloat, b: CGFloat) { self.l = l self.a = a self.b = b } public func toXYZ() -> XYZ { var xyz:XYZ = XYZ() xyz.y = self.l / 10.0 xyz.x = self.a / 17.5 * self.l / 10.0 xyz.z = self.b / 7.0 * self.l / 10.0 xyz.y **= 2.0 xyz.x = (xyz.x + xyz.y) / 1.02 xyz.z = -1 * (xyz.z - xyz.y) / 0.847 return xyz } } public struct LAB { public var l:CGFloat = 0.0 public var a:CGFloat = 0.0 public var b:CGFloat = 0.0 public init() {} public init(l: CGFloat, a: CGFloat, b: CGFloat) { self.l = l self.a = a self.b = b } public func toXYZ(refWhite: ReferenceWhite) -> XYZ { var xyz:XYZ = XYZ() let matrix:ReferenceWhiteMatrix = Matrices.ReferenceWhiteMatrices[refWhite]! xyz.y = (self.l + 16.0) / 116.0 xyz.x = self.a / 500.0 + xyz.y xyz.z = xyz.y - self.b / 200.0 xyz.y = (ɛ < (xyz.y ** 3.0)) ? xyz.y ** 3.0 : (xyz.y - 16.0 / 116.0) / κ xyz.x = (ɛ < (xyz.x ** 3.0)) ? xyz.x ** 3.0 : (xyz.x - 16.0 / 116.0) / κ xyz.z = (ɛ < (xyz.z ** 3.0)) ? xyz.z ** 3.0 : (xyz.z - 16.0 / 116.0) / κ xyz.x *= matrix.Xw * 100.0 xyz.y *= matrix.Yw * 100.0 xyz.z *= matrix.Zw * 100.0 return xyz } public func toLCHab() -> LCHab { var lch:LCHab = LCHab() lch.l = self.l lch.c = sqrt((self.a ** 2.0) + (self.b ** 2.0)) lch.h = atan2(self.b, self.a).degrees while 0.0 > lch.h { lch.h += M_2PI.degrees } while M_2PI.degrees < lch.h { lch.h -= M_2PI.degrees } lch.h /= M_2PI.degrees return lch } public func toRGB(rgbSpace: RGBWorkingSpace) -> RGB { return self.toXYZ(rgbSpace.referenceWhite).toRGB(rgbSpace) } } public struct LUV { public var l:CGFloat = 0.0 public var u:CGFloat = 0.0 public var v:CGFloat = 0.0 public init() {} public init(l: CGFloat, u: CGFloat, v: CGFloat) { self.l = l self.u = u self.v = v } public func toLCHuv() -> LCHuv { var lch:LCHuv = LCHuv() lch.l = self.l lch.c = sqrt((self.u ** 2.0) + (self.v ** 2.0)) lch.h = atan2(self.v, self.u).degrees while 0.0 > lch.h { lch.h += M_2PI.degrees } while M_2PI.degrees < lch.h { lch.h -= M_2PI.degrees } lch.h /= M_2PI.degrees return lch } } public struct XYY { public var x:CGFloat = 0.0 public var y:CGFloat = 0.0 public var Y:CGFloat = 0.0 public init() {} public init(x: CGFloat, y: CGFloat, Y: CGFloat) { self.x = x self.y = y self.Y = Y } } public struct CMYK { public var c:CGFloat = 0.0 public var m:CGFloat = 0.0 public var y:CGFloat = 0.0 public var k:CGFloat = 0.0 public init() {} public init(c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat) { self.c = c self.m = m self.y = y self.k = k } public func toRGB() -> RGB { var rgb:RGB = RGB() rgb.r = (1.0 - self.c) * (1.0 - self.k) rgb.g = (1.0 - self.m) * (1.0 - self.k) rgb.b = (1.0 - self.y) * (1.0 - self.k) return rgb } } // MARK: - Constants struct Numerics { static let ε:CGFloat = 0.008856 static let κ:CGFloat = 7.787 } struct Gamma { static let RGB:[RGBWorkingSpace:CGFloat] = [ .AdobeD65 : 2.2, .AppleD65 : 1.8, .BestD50 : 2.2, .BetaD50 : 2.2, .BruceD65 : 2.2, .CIEE : 2.2, .ColormatchD50 : 1.8, .DonD50 : 2.2, .ECID50 : 0.0, .EktaSpaceD50 : 2.2, .NTSCC : 2.2, .PalSecamD65 : 2.2, .ProPhotoD50 : 1.8, .SMPTECD65 : 2.2, .sRGBD65 : -2.2, .WideGamutD50 : 2.2, .AdobeD50 : 2.2, .AppleD50 : 1.8, .BruceD50 : 2.2, .CEID50 : 2.2, .NTSCD50 : 2.2, .PalSecamD50 : 2.2, .SMPTECD50 : 2.2, .sRGBD50 : -2.2 ] } struct Matrices { static let ReferenceWhiteMatrices:[ReferenceWhite:ReferenceWhiteMatrix] = [ .A : ReferenceWhiteMatrix(Xw: 1.09850, Yw: 1.0, Zw: 0.35585), .B : ReferenceWhiteMatrix(Xw: 0.99072, Yw: 1.0, Zw: 0.85223), .C : ReferenceWhiteMatrix(Xw: 0.98074, Yw: 1.0, Zw: 1.18232), .D50 : ReferenceWhiteMatrix(Xw: 0.96422, Yw: 1.0, Zw: 0.82521), .D55 : ReferenceWhiteMatrix(Xw: 0.95682, Yw: 1.0, Zw: 0.92149), .D65 : ReferenceWhiteMatrix(Xw: 0.95047, Yw: 1.0, Zw: 1.08883), .D75 : ReferenceWhiteMatrix(Xw: 0.94972, Yw: 1.0, Zw: 1.22638), .E : ReferenceWhiteMatrix(Xw: 1.0, Yw: 1.0, Zw: 1.0), .F2 : ReferenceWhiteMatrix(Xw: 0.99186, Yw: 1.0, Zw: 0.67393), .F7 : ReferenceWhiteMatrix(Xw: 0.95041, Yw: 1.0, Zw: 1.08747), .F11 : ReferenceWhiteMatrix(Xw: 1.00962, Yw: 1.0, Zw: 0.64350) ] static let WorkingMatrices:[RGBWorkingSpace:[RGBWorkingSpaceMatrix]] = [ .AdobeD65 : [ RGBWorkingSpaceMatrix( _00: 0.5767309, _01: 0.1855540, _02: 0.1881852, _10: 0.2973769, _11: 0.6273491, _12: 0.0752741, _20: 0.0270343, _21: 0.0706872, _22: 0.9911085), RGBWorkingSpaceMatrix( _00: 2.0413690, _01: -0.5649464, _02: -0.3446944, _10: -0.9692660, _11: 1.8760108, _12: 0.0415560, _20: 0.0134474, _21: -0.1183897, _22: 1.0154096)], .AppleD65 : [ RGBWorkingSpaceMatrix( _00: 0.4497288, _01: 0.3162486, _02: 0.1844926, _10: 0.2446525, _11: 0.6720283, _12: 0.0833192, _20: 0.0251848, _21: 0.1411824, _22: 0.9224628), RGBWorkingSpaceMatrix( _00: 2.9515373, _01: -1.2894116, _02: -0.4738445, _10: -1.0851093, _11: 1.9908566, _12: 0.0372026, _20: 0.0854934, _21: -0.2694964, _22: 1.0912975)], .BestD50 : [ RGBWorkingSpaceMatrix( _00: 0.6326696, _01: 0.2045558, _02: 0.1269946, _10: 0.2284569, _11: 0.7373523, _12: 0.0341908, _20: 0.0000000, _21: 0.0095142, _22: 0.8156958), RGBWorkingSpaceMatrix( _00: 1.7552599, _01: -0.4836786, _02: -0.2530000, _10: -0.5441336, _11: 1.5068789, _12: 0.0215528, _20: 0.0063467, _21: -0.0175761, _22: 1.2256959)], .BetaD50 : [ RGBWorkingSpaceMatrix( _00: 0.6712537, _01: 0.1745834, _02: 0.1183829, _10: 0.3032726, _11: 0.6637861, _12: 0.0329413, _20: 0.0000000, _21: 0.0407010, _22: 0.7845090), RGBWorkingSpaceMatrix( _00: 1.6832270, _01: -0.4282363, _02: -0.2360185, _10: -0.7710229, _11: 1.7065571, _12: 0.0446900, _20: 0.0400013, _21: -0.0885376, _22: 1.2723640)], .BruceD65 : [ RGBWorkingSpaceMatrix( _00: 0.4674162, _01: 0.2944512, _02: 0.1886026, _10: 0.2410115, _11: 0.6835475, _12: 0.0754410, _20: 0.0219101, _21: 0.0736128, _22: 0.9933071), RGBWorkingSpaceMatrix( _00: 2.7454669, _01: -1.1358136, _02: -0.4350269, _10: -0.9692660, _11: 1.8760108, _12: 0.0415560, _20: 0.0112723, _21: -0.1139754, _22: 1.0132541)], .CIEE : [ RGBWorkingSpaceMatrix( _00: 0.4887180, _01: 0.3106803, _02: 0.2006017, _10: 0.1762044, _11: 0.8129847, _12: 0.0108109, _20: 0.0000000, _21: 0.0102048, _22: 0.9897952), RGBWorkingSpaceMatrix( _00: 2.3706743, _01: -0.9000405, _02: -0.4706338, _10: -0.5138850, _11: 1.4253036, _12: 0.0885814, _20: 0.0052982, _21: -0.0146949, _22: 1.0093968)], .ColormatchD50 : [ RGBWorkingSpaceMatrix( _00: 0.5093439, _01: 0.3209071, _02: 0.1339691, _10: 0.2748840, _11: 0.6581315, _12: 0.0669845, _20: 0.0242545, _21: 0.1087821, _22: 0.6921735), RGBWorkingSpaceMatrix( _00: 2.6422874, _01: -1.2234270, _02: -0.3930143, _10: -1.1119763, _11: 2.0590183, _12: 0.0159614, _20: 0.0821699, _21: -0.2807254, _22: 1.4559877)], .DonD50 : [ RGBWorkingSpaceMatrix( _00: 0.6457711, _01: 0.1933511, _02: 0.1250978, _10: 0.2783496, _11: 0.6879702, _12: 0.0336802, _20: 0.0037113, _21: 0.0179861, _22: 0.8035125), RGBWorkingSpaceMatrix( _00: 1.7603902, _01: -0.4881198, _02: -0.2536126, _10: -0.7126288, _11: 1.6527432, _12: 0.0416715, _20: 0.0078207, _21: -0.0347411, _22: 1.2447743)], .ECID50 : [ RGBWorkingSpaceMatrix( _00: 0.6502043, _01: 0.1780774, _02: 0.1359384, _10: 0.3202499, _11: 0.6020711, _12: 0.0776791, _20: 0.0000000, _21: 0.0678390, _22: 0.7573710), RGBWorkingSpaceMatrix( _00: 1.7827618, _01: -0.4969847, _02: -0.2690101, _10: -0.9593623, _11: 1.9477962, _12: -0.0275807, _20: 0.0859317, _21: -0.1744674, _22: 1.3228273)], .EktaSpaceD50 : [ RGBWorkingSpaceMatrix( _00: 0.5938914, _01: 0.2729801, _02: 0.0973485, _10: 0.2606286, _11: 0.7349465, _12: 0.0044249, _20: 0.0000000, _21: 0.0419969, _22: 0.7832131), RGBWorkingSpaceMatrix( _00: 2.0043819, _01: -0.7304844, _02: -0.2450052, _10: -0.7110285, _11: 1.6202126, _12: 0.0792227, _20: 0.0381263, _21: -0.0868780, _22: 1.2725438)], .NTSCC : [ RGBWorkingSpaceMatrix( _00: 0.6068909, _01: 0.1735011, _02: 0.2003480, _10: 0.2989164, _11: 0.5865990, _12: 0.1144845, _20: 0.0000000, _21: 0.0660957, _22: 1.1162243), RGBWorkingSpaceMatrix( _00: 1.9099961, _01: -0.5324542, _02: -0.2882091, _10: -0.9846663, _11: 1.9991710, _12: -0.0283082, _20: 0.0583056, _21: -0.1183781, _22: 0.8975535)], .PalSecamD65 : [ RGBWorkingSpaceMatrix( _00: 0.4306190, _01: 0.3415419, _02: 0.1783091, _10: 0.2220379, _11: 0.7066384, _12: 0.0713236, _20: 0.0201853, _21: 0.1295504, _22: 0.9390944), RGBWorkingSpaceMatrix( _00: 3.0628971, _01: -1.3931791, _02: -0.4757517, _10: -0.9692660, _11: 1.8760108, _12: 0.0415560, _20: 0.0678775, _21: -0.2288548, _22: 1.0693490)], .ProPhotoD50 : [ RGBWorkingSpaceMatrix( _00: 0.7976749, _01: 0.1351917, _02: 0.0313534, _10: 0.2880402, _11: 0.7118741, _12: 0.0000857, _20: 0.0000000, _21: 0.0000000, _22: 0.8252100), RGBWorkingSpaceMatrix( _00: 1.3459433, _01: -0.2556075, _02: -0.0511118, _10: -0.5445989, _11: 1.5081673, _12: 0.0205351, _20: 0.0000000, _21: 0.0000000, _22: 1.2118128)], .SMPTECD65 : [ RGBWorkingSpaceMatrix( _00: 0.3935891, _01: 0.3652497, _02: 0.1916313, _10: 0.2124132, _11: 0.7010437, _12: 0.0865432, _20: 0.0187423, _21: 0.1119313, _22: 0.9581563), RGBWorkingSpaceMatrix( _00: 3.5053960, _01: -1.7394894, _02: -0.5439640, _10: -1.0690722, _11: 1.9778245, _12: 0.0351722, _20: 0.0563200, _21: -0.1970226, _22: 1.0502026)], .sRGBD65 : [ RGBWorkingSpaceMatrix( _00: 0.4124564, _01: 0.3575761, _02: 0.1804375, _10: 0.2126729, _11: 0.7151522, _12: 0.0721750, _20: 0.0193339, _21: 0.1191920, _22: 0.9503041), RGBWorkingSpaceMatrix( _00: 3.2404542, _01: -1.5371385, _02: -0.4985314, _10: -0.9692660, _11: 1.8760108, _12: 0.0415560, _20: 0.0556434, _21: -0.2040259, _22: 1.0572252)], .WideGamutD50 : [ RGBWorkingSpaceMatrix( _00: 0.7161046, _01: 0.1009296, _02: 0.1471858, _10: 0.2581874, _11: 0.7249378, _12: 0.0168748, _20: 0.0000000, _21: 0.0517813, _22: 0.7734287), RGBWorkingSpaceMatrix( _00: 1.4628067, _01: -0.1840623, _02: -0.2743606, _10: -0.5217933, _11: 1.4472381, _12: 0.0677227, _20: 0.0349342, _21: -0.0968930, _22: 1.2884099)], .AdobeD50 : [ RGBWorkingSpaceMatrix( _00: 0.6097559, _01: 0.2052401, _02: 0.1492240, _10: 0.3111242, _11: 0.6256560, _12: 0.0632197, _20: 0.0194811, _21: 0.0608902, _22: 0.7448387), RGBWorkingSpaceMatrix( _00: 1.9624274, _01: -0.6105343, _02: -0.3413404, _10: -0.9787684, _11: 1.9161415, _12: 0.0334540, _20: 0.0286869, _21: -0.1406752, _22: 1.3487655)], .AppleD50 : [ RGBWorkingSpaceMatrix( _00: 0.4755678, _01: 0.3396722, _02: 0.1489800, _10: 0.2551812, _11: 0.6725693, _12: 0.0722496, _20: 0.0184697, _21: 0.1133771, _22: 0.6933632), RGBWorkingSpaceMatrix( _00: 2.8510695, _01: -1.3605261, _02: -0.4708281, _10: -1.0927680, _11: 2.0348871, _12: 0.0227598, _20: 0.1027403, _21: -0.2964984, _22: 1.4510659)], .BruceD50 : [ RGBWorkingSpaceMatrix( _00: 0.4941816, _01: 0.3204834, _02: 0.1495550, _10: 0.2521531, _11: 0.6844869, _12: 0.0633600, _20: 0.0157886, _21: 0.0629304, _22: 0.7464909), RGBWorkingSpaceMatrix( _00: 2.6502856, _01: -1.2014485, _02: -0.4289936, _10: -0.9787684, _11: 1.9161415, _12: 0.0334540, _20: 0.0264570, _21: -0.1361227, _22: 1.3458542)], .CEID50 : [ RGBWorkingSpaceMatrix( _00: 0.4868870, _01: 0.3062984, _02: 0.1710347, _10: 0.1746583, _11: 0.8247541, _12: 0.0005877, _20: -0.0012563, _21: 0.0169832, _22: 0.8094831), RGBWorkingSpaceMatrix( _00: 2.3638081, _01: -0.8676030, _02: -0.4988161, _10: -0.5005940, _11: 1.3962369, _12: 0.1047562, _20: 0.0141712, _21: -0.0306400, _22: 1.2323842)], .NTSCD50 : [ RGBWorkingSpaceMatrix( _00: 0.6343706, _01: 0.1852204, _02: 0.1446290, _10: 0.3109496, _11: 0.5915984, _12: 0.0974520, _20: -0.0011817, _21: 0.0555518, _22: 0.7708399), RGBWorkingSpaceMatrix( _00: 1.8464881, _01: -0.5521299, _02: -0.2766458, _10: -0.9826630, _11: 2.0044755, _12: -0.0690396, _20: 0.0736477, _21: -0.1453020, _22: 1.3018376)], .PalSecamD50 : [ RGBWorkingSpaceMatrix( _00: 0.4552773, _01: 0.3675500, _02: 0.1413926, _10: 0.2323025, _11: 0.7077956, _12: 0.0599019, _20: 0.0145457, _21: 0.1049154, _22: 0.7057489), RGBWorkingSpaceMatrix( _00: 2.9603944, _01: -1.4678519, _02: -0.4685105, _10: -0.9787684, _11: 1.9161415, _12: 0.0334540, _20: 0.0844874, _21: -0.2545973, _22: 1.4216174)], .SMPTECD50 : [ RGBWorkingSpaceMatrix( _00: 0.4163290, _01: 0.3931464, _02: 0.1547446, _10: 0.2216999, _11: 0.7032549, _12: 0.0750452, _20: 0.0136576, _21: 0.0913604, _22: 0.7201920), RGBWorkingSpaceMatrix( _00: 3.3921940, _01: -1.8264027, _02: -0.5385522, _10: -1.0770996, _11: 2.0213975, _12: 0.0207989, _20: 0.0723073, _21: -0.2217902, _22: 1.3960932)], .sRGBD50 : [ RGBWorkingSpaceMatrix( _00: 0.4360747, _01: 0.3850649, _02: 0.1430804, _10: 0.2225045, _11: 0.7168786, _12: 0.0606169, _20: 0.0139322, _21: 0.0971045, _22: 0.7141733), RGBWorkingSpaceMatrix( _00: 3.1338561, _01: -1.6168667, _02: -0.4906146, _10: -0.9787684, _11: 1.9161415, _12: 0.0334540, _20: 0.0719453, _21: -0.2289914, _22: 1.4052427)] ] } // MARK: - Colour Distance Functions public func cie76(lhs: LAB, rhs: LAB) -> CGFloat { return sqrt(((lhs.l - rhs.l) ** 2.0) + ((lhs.a - rhs.a) ** 2.0) + ((lhs.b - rhs.b) ** 2.0)) } public func cmc1984(lhs: LAB, rhs: LAB, l: CGFloat, c: CGFloat) -> CGFloat { let L_d:CGFloat = (lhs.l - rhs.l) let C_1:CGFloat = sqrt((lhs.a ** 2.0) + (lhs.b ** 2.0)) let C_2:CGFloat = sqrt((rhs.a ** 2.0) + (rhs.b ** 2.0)) let C_d:CGFloat = (C_1 - C_2) let H_d_ab2:CGFloat = ((lhs.a - rhs.a) ** 2.0) + ((lhs.b - rhs.b) ** 2.0) - (C_d ** 2.0) let F:CGFloat = sqrt((C_1 ** 4.0) / ((C_1 ** 4.0) + 1900.0)) let S_L:CGFloat = (16.0 <= lhs.l) ? (lhs.l * 0.040975) / (1.0 + (lhs.l * 0.01765)) : 0.511 let S_C:CGFloat = ((C_1 * 0.0638) / (1.0 + (C_1 * 0.0131))) + 0.638 var H_1:CGFloat = atan2(lhs.b, lhs.a).degrees while H_1 < 0.0 { H_1 += M_2PI.degrees } while H_1 > M_2PI.degrees { H_1 -= M_2PI.degrees } let T:CGFloat = (164.0 <= H_1 && 345.0 >= H_1) ? 0.56 + abs(0.2 * cos((H_1 + 168.0).radians)) : 0.36 + abs(0.4 * cos((H_1 + 35.0).radians)) let S_H:CGFloat = S_C * (F * T + 1.0 - F) /* * Commonly used values are 2:1 for acceptability and 1:1 for the threshold * of imperceptibility. */ return sqrt(((L_d / (l * S_L)) ** 2.0) + ((C_d / (c * S_C)) ** 2.0) + (H_d_ab2 / (S_H ** 2.0))) } public func cie94(lhs: LAB, rhs: LAB, media: CIE94) -> CGFloat { let L_d:CGFloat = (lhs.l - rhs.l) let C_1:CGFloat = sqrt((lhs.a ** 2.0) + (lhs.b ** 2.0)) let C_2:CGFloat = sqrt((rhs.a ** 2.0) + (rhs.b ** 2.0)) let C_d:CGFloat = (C_1 - C_2) let D_H_ab2:CGFloat = (((lhs.a - rhs.a) ** 2.0) + ((lhs.b - rhs.b) ** 2.0) - (C_d ** 2.0)) let K_L:CGFloat = (.textiles != media) ? 1.0 : 2.0 let K_C:CGFloat = 1.0 let K_H:CGFloat = K_C let K_1:CGFloat = (.textiles != media) ? 0.045 : 0.048 let K_2:CGFloat = (.textiles != media) ? 0.015 : 0.014 let S_L:CGFloat = 1.0 let S_C:CGFloat = 1.0 + (K_1 * C_1) let S_H:CGFloat = 1.0 + (K_2 * C_1) let term0:CGFloat = ((L_d / (K_L * S_L)) ** 2.0) let term1:CGFloat = ((C_d / (K_C * S_C)) ** 2.0) let term2:CGFloat = (D_H_ab2 / ((K_H ** 2.0) * (S_H ** 2.0))) return sqrt(term0 + term1 + term2) } public func ciede2000(lhs: LAB, rhs: LAB, kl: CGFloat, kc: CGFloat, kh: CGFloat) -> CGFloat { /* Calculate C_i_p, h_i_p */ let C_1_s:CGFloat = sqrt((lhs.a ** 2.0) + (lhs.b ** 2.0)) let C_2_s:CGFloat = sqrt((rhs.a ** 2.0) + (rhs.b ** 2.0)) let C_sb_p:CGFloat = (C_1_s + C_2_s) / 2.0 let G:CGFloat = 0.5 * (1.0 - sqrt((C_sb_p ** 7.0) / ((C_sb_p ** 7.0) + (25.0 ** 7.0)))) let a_1_p:CGFloat = lhs.a + (G * lhs.a) let a_2_p:CGFloat = rhs.a + (G * rhs.a) let C_1_p:CGFloat = sqrt((a_1_p ** 2.0) + (lhs.b ** 2.0)) let C_2_p:CGFloat = sqrt((a_2_p ** 2.0) + (rhs.b ** 2.0)) /* Apparently you must work in degrees from here on out? */ var h_1_p:CGFloat = (0.0 == C_1_p) ? 0.0 : atan2(lhs.b, a_1_p).degrees while h_1_p < 0.0 { h_1_p += M_2PI.degrees } while (h_1_p > M_2PI.degrees) { h_1_p -= M_2PI.degrees } var h_2_p:CGFloat = (0.0 == C_2_p) ? 0.0 : atan2(rhs.b, a_2_p).degrees while h_2_p < 0.0 { h_2_p += M_2PI.degrees } while h_2_p > M_2PI.degrees { h_2_p -= M_2PI.degrees } /* Calculate L_d_p, C_d_p, and H_d_p */ let L_d_p:CGFloat = (rhs.l - lhs.l) let C_d_p:CGFloat = (C_2_p - C_1_p) var h_d_p:CGFloat = 0.0 if 0.0 != (C_1_p * C_2_p) { h_d_p = (180.0 >= abs(h_2_p - h_1_p)) ? (h_2_p - h_1_p) : (180.0 < (h_2_p - h_1_p)) ? ((h_2_p - h_1_p) - M_2PI.degrees) : (-180.0 > (h_2_p - h_1_p)) ? ((h_2_p - h_1_p) + M_2PI.degrees) : 0.0 } let H_d_p:CGFloat = 2.0 * sqrt(C_1_p * C_2_p) * sin((h_d_p / 2.0).radians) /* Calculate CIEDE2000 Color-Difference E_d_00 */ let L_b_p:CGFloat = (lhs.l + rhs.l) / 2.0 let C_b_p:CGFloat = (C_1_p + C_2_p) / 2.0 let h_d_p_abs:CGFloat = abs(h_1_p - h_2_p) let h_d_p_sum:CGFloat = (h_1_p + h_2_p) var h_b_p:CGFloat = h_d_p_sum if (0.0 != (C_1_p * C_2_p)) { h_b_p = (180.0 >= h_d_p_abs) ? (h_d_p_sum / 2.0) : ((180.0 < h_d_p_abs) && (M_2PI.degrees > h_d_p_sum)) ? ((h_d_p_sum + M_2PI.degrees) / 2.0) : ((180.0 < h_d_p_abs) && (M_2PI.degrees <= h_d_p_sum)) ? ((h_d_p_sum - M_2PI.degrees) / 2.0) : CGFloat.NaN } let t0:CGFloat = (0.17 * cos((h_b_p - 30.0).radians)) let t1:CGFloat = (0.24 * cos((2.0 * h_b_p).radians)) let t2:CGFloat = (0.32 * cos(((3.0 * h_b_p) + 6.0).radians)) let t3:CGFloat = (0.20 * cos(((4.0 * h_b_p) - 63.0).radians)) let T:CGFloat = 1.0 - t0 + t1 + t2 - t3 let T_d:CGFloat = 30.0 * exp(-1.0 * (((h_b_p - 275.0) / 25.0) ** 2.0)) let R_C:CGFloat = 2.0 * sqrt((C_b_p ** 7.0) / (((C_b_p ** 7.0) + (25.0 ** 7.0)))) let S_L = 1.0 + ((0.015 * ((L_b_p - 50.0) ** 2.0)) / sqrt(20.0 + ((L_b_p - 50.0) ** 2.0))) let S_C:CGFloat = 1.0 + (0.045 * C_b_p) let S_H:CGFloat = 1.0 + (0.015 * C_b_p * T) let R_T:CGFloat = -1.0 * sin((2.0 * T_d).radians) * R_C let L_term:CGFloat = ((L_d_p / (kl * S_L)) ** 2.0) let C_term:CGFloat = ((C_d_p / (kc * S_C)) ** 2.0) let H_term:CGFloat = ((H_d_p / (kh * S_H)) ** 2.0) let R_term:CGFloat = R_T * (C_d_p / (kc * S_C)) * (H_d_p / (kh * S_H)) return sqrt(L_term + C_term + H_term + R_term) }
mit
a49d70573c97e8c352b5b18bb494b99c
31.576747
121
0.494066
2.833466
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/DrinkPoint/Games/Epigram/ThemeChooserViewController.swift
1
4674
// // ThemeChooserViewController.swift // DrinkPoint // // Created by Paul Kirk Adams on 7/28/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import UIKit import QuartzCore import Crashlytics class ThemeChooserViewController: UITableViewController { @IBOutlet weak var historyButton: UIBarButtonItem! @IBOutlet weak var tweetsButton: UIBarButtonItem! var logoView: UIImageView! var themes: [Theme] = [] let themeTableCellReuseIdentifier = "ThemeCell" override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() themes = Theme.getThemes() logoView = UIImageView(frame: CGRectMake(0, 0, 40, 40)) logoView.image = UIImage(named: "Logo")?.imageWithRenderingMode(.AlwaysTemplate) logoView.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) logoView.frame.origin.x = (view.frame.size.width - logoView.frame.size.width) / 2 logoView.frame.origin.y = -logoView.frame.size.height - 10 navigationController?.view.addSubview(logoView) navigationController?.view.bringSubviewToFront(logoView) let logoTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ThemeChooserViewController.logoTapped)) logoView.userInteractionEnabled = true logoView.addGestureRecognizer(logoTapRecognizer) tableView.alwaysBounceVertical = false let headerHeight: CGFloat = 15 let contentHeight = view.frame.size.height - headerHeight let navHeight = navigationController?.navigationBar.frame.height let navYOrigin = navigationController?.navigationBar.frame.origin.y tableView.tableHeaderView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, headerHeight)) let themeTableCellHeight = (contentHeight - navHeight! - navYOrigin!) / CGFloat(themes.count) tableView.rowHeight = themeTableCellHeight let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()] navigationController?.navigationBar.titleTextAttributes = titleDict as? [String: AnyObject] navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.topItem?.title = "" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .CurveEaseInOut, animations: { self.logoView.frame.origin.y = 8 }, completion: nil ) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) navigationController?.navigationBar.translucent = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if navigationController?.viewControllers.count > 1 { UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .CurveEaseInOut, animations: { self.logoView.frame.origin.y = -self.logoView.frame.size.height - 10 }, completion: nil ) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if sender!.isKindOfClass(ThemeCell) { let indexPath = tableView.indexPathForSelectedRow if let row = indexPath?.row { let epigramComposerViewController = segue.destinationViewController as! EpigramComposerViewController epigramComposerViewController.theme = themes[row] Crashlytics.sharedInstance().setObjectValue(themes[row].name, forKey: "Theme") Answers.logCustomEventWithName("Selected Theme", customAttributes: ["Theme": themes[row].name]) } } } func logoTapped() { performSegueWithIdentifier("ShowAbout", sender: self) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return themes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(themeTableCellReuseIdentifier, forIndexPath: indexPath) as! ThemeCell let theme = themes[indexPath.row] cell.configureWithTheme(theme) return cell } }
mit
5a5ce10b647a37ade547729a2bf1e79f
42.277778
136
0.690349
5.26832
false
false
false
false
xcplaygrounds/uikitplayground
Animations.playground/Pages/UIKit Dynamics.xcplaygroundpage/Contents.swift
1
1759
//: # UIKit Dynamics : Physics Fun ! import UIKit import XCPlayground //: Lets take a fun tour of UIKit Dynamics. Instead of using explicit animations , your views can now snap , stretch , crash and bounce based on physics ! //: //: Lets create a white container to hold our animations. let container = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 300.0)) container.backgroundColor = UIColor.whiteColor() //: You can see the action in the assistant editor on the right. //: Lets add a shiny black square . let view = UIView(frame: CGRect(x: 20.0, y: 10.0, width: 50.0, height: 50.0)) view.backgroundColor = UIColor.blackColor() container.addSubview(view) //: Now lets make him fall to the floor and bounce to a halt. //: ### Step 1 : Create the animator : //: We create the animator. The animator is an instance of *UIDynamicAnimator* which animates its items with respect to its referenceView. You usually do this in *viewDidLoad* and assign it as a property on the viewController. var animator = UIDynamicAnimator(referenceView: container) //: ### Step 2 : Create the behaviours : //: Now we move on to behaviors. Each behavior applies to a set of items . We need two behaviors here. A Collission behavior and a gravity behavior. var collision = UICollisionBehavior(items: [view]) collision.translatesReferenceBoundsIntoBoundary = true animator.addBehavior(collision) let itemBehaviour = UIDynamicItemBehavior(items: [view]) itemBehaviour.elasticity = 0.7 // try values from 0->1 animator.addBehavior(itemBehaviour) var gravity = UIGravityBehavior(items: [view]) animator.addBehavior(gravity) XCPShowView("container", view: container) //: WHEEE !! //: [Next](@next)
mit
3c0c2eefadf60c9a8cf6a3a82a937df4
39.906977
226
0.720296
4.208134
false
false
false
false
Yeahming/YMWeiBo_swiftVersion
YMWeibo_swiftVersion/YMWeibo_swiftVersion/Classes/Home/Controller/HomeTableViewController.swift
1
3902
// // HomeTableViewController.swift // YMWeibo_swiftVersion // // Created by 樊彦明 on 15/9/27. // Copyright © 2015年 developer_YM. All rights reserved. // import UIKit class HomeTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // 设置个性导航条 setupNaviBar() } // MARK: - 设置个性导航条 func setupNaviBar(){ navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: "navigationbar_friendattention") navigationItem.rightBarButtonItem = UIBarButtonItem.init(imageName: "navigationbar_icon_radar") let button = ImageRightButton() button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal) button.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected) button.setTitle("樊彦明" + " ", forState: UIControlState.Normal) navigationItem.titleView = button button.addTarget(self, action:Selector("titleButtonClicked:"), forControlEvents: UIControlEvents.TouchUpInside) } // MARK: - 监听标题按钮的点击 func titleButtonClicked(button: UIButton){ button.selected = !button.selected } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
ba300234c1dbc8a4614edba9aaad4338
34.564815
157
0.684197
5.327323
false
false
false
false
larryhou/swift
Tachograph/Tachograph/CameraModel.swift
1
14623
// // SessionModel.swift // Tachograph // // Created by larryhou on 1/7/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation struct ServerInfo { let addr: String let port: UInt32 } #if NATIVE_DEBUG let LIVE_SERVER = ServerInfo(addr: "10.66.195.149", port: 8800) #else let LIVE_SERVER = ServerInfo(addr: "192.168.42.1", port: 7878) #endif struct AcknowledgeMessage: Codable { let rval, msg_id: Int } //{ "rval": 0, "msg_id": 1, "type": "date_time", "param": "2017-06-29 19:25:12" } struct QueryMessage: Codable { let rval, msg_id: Int let type, param: String } struct TokenMessage: Codable { let rval, msg_id, param: Int } //{ "rval": 0, "msg_id": 1290, "totalFileNum": 37, "param": 0, "listing": [ struct AssetsMessage: Codable { struct Asset: Codable { let name: String } let rval, msg_id, totalFileNum, param: Int let listing: [Asset] } //{ "rval": 0, "msg_id": 1280, "listing": [ { "path": "\/mnt\/mmc01\/DCIM", "type": "nor_video" }, { "path": "\/mnt\/mmc01\/EVENT", "type": "event_video" }, { "path": "\/mnt\/mmc01\/PICTURE", "type": "cap_img" } ] } struct AssetIndexMessage: Codable { struct Folder: Codable { let path, type: String } let rval, msg_id: Int let listing: [Folder] } //{ "rval": 0, "msg_id": 11, "camera_type": "AE-CS2016-HZ2", "firm_ver": "V1.1.0", "firm_date": "build 161031", "param_version": "V1.3.0", "serial_num": "655136915", "verify_code": "JXYSNT" } struct VersionMessage: Codable { let rval, msg_id: Int let camera_type, firm_ver, firm_date, param_version, serial_num, verify_code: String } //{ "msg_id": 7, "type": "photo_taken", "param": "\/mnt\/mmc01\/PICTURE\/ch1_20170701_2022_0053.jpg" } struct CaptureNotification: Codable { let msg_id: Int let type, param: String } enum RemoteCommand: Int { case query = 1, fetchVersion = 11, fetchToken = 0x101/*257*/ case fetchAssetIndex = 0x500/*1280*/, fetchRouteVideos = 0x508/*1288*/, fetchEventVideos = 0x509/*1289*/, fetchImages = 0x50A/*1290*/ case captureVideo = 0x201/*513*/, captureImage = 0x301/*769*/, notification = 7 } protocol CameraModelDelegate { func model(assets: [CameraModel.CameraAsset], type: CameraModel.AssetType) func model(update: CameraModel.CameraAsset, type: CameraModel.AssetType) } class CameraModel: TCPSessionDelegate { struct NativeAssetInfo { let location: URL let size: UInt64 } struct CameraAsset { let id, name, url, icon: String let timestamp: Date var info: NativeAssetInfo? init(id: String, name: String, url: String, icon: String, timestamp: Date) { self.id = id self.name = name self.url = url self.icon = icon self.timestamp = timestamp } } enum AssetType { case image, event, route } struct AssetIndex { let image, event, route: String } static private var _model: CameraModel? static var shared: CameraModel { if _model == nil { _model = CameraModel() } return _model! } var delegate: CameraModelDelegate? private(set) var ready: Bool = false private var _session: TCPSession private var _decoder: JSONDecoder private var _dateFormatter: DateFormatter private var _trim: NSRegularExpression? private var _timer: Timer? init() { _session = TCPSession() _session.connect(address: LIVE_SERVER.addr, port: LIVE_SERVER.port) _decoder = JSONDecoder() _dateFormatter = DateFormatter() _dateFormatter.dateFormat = "'ch1_'yyyyMMdd_HHmm_SSSS" // ch1_20170628_2004_0042 _trim = try? NSRegularExpression(pattern: "\\.[^\\.]+$", options: .caseInsensitive) _session.delegate = self _timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(heartbeat), userInfo: nil, repeats: true) #if NATIVE_DEBUG _timer?.invalidate() #endif } var networkObserver: ((Bool) -> Void)? @objc func heartbeat() { if _session.connected { query(type: "app_status") networkObserver?(true) } else { networkObserver?(false) if _session.state != .connecting { _session.clear() _session.reconnect() } } } func tcpUpdate(session: TCPSession) { if _taskQueue.count > 0 && ready { _session.send(data: _taskQueue.remove(at: 0)) } } func tcp(session: TCPSession, state: TCPSessionState) { if state == .connected { fetchToken() } else if state == .closed { ready = false } } func tcp(session: TCPSession, data: Data) { do { if data.count == 0 { return } try data.withUnsafeBytes({ (pointer: UnsafePointer<UInt8>) in var position = pointer, start = pointer, found = false, depth = 0 for _ in 0..<data.count { if position.pointee == 0x5b || position.pointee == 0x7b { found = true depth += 1 } else if position.pointee == 0x5d || position.pointee == 0x7d { depth -= 1 } position = position.advanced(by: 1) if found && depth == 0 { let message = Data(bytes: start, count: start.distance(to: position)) if let jsonObject = try JSONSerialization.jsonObject(with: message, options: .allowFragments) as? Dictionary<String, Any> { try processMessage(data: jsonObject, bytes: message) } start = position found = false } } }) } catch { print(String(data: data, encoding: .utf8)!) print(error) } } var eventVideos: [CameraAsset] = [] var routeVideos: [CameraAsset] = [] var tokenImages: [CameraAsset] = [] var version: VersionMessage? var assetIndex: AssetIndex! var token: Int = 1 func processMessage(data: Dictionary<String, Any>, bytes: Data) throws { guard let id = data["msg_id"] as! Int? else { return } guard let command = RemoteCommand(rawValue: id) else { return } var response: Codable switch command { case .query: let msg = try _decoder.decode(QueryMessage.self, from: bytes) response = msg case .fetchVersion: self.version = try _decoder.decode(VersionMessage.self, from: bytes) response = self.version! case .fetchToken: let msg = try _decoder.decode(TokenMessage.self, from: bytes) self.token = msg.param response = msg preload() case .fetchAssetIndex: let msg = try _decoder.decode(AssetIndexMessage.self, from: bytes) var route = "", event = "", image = "" for item in msg.listing { let location = "/SMCAR/DOWNLOAD\(item.path)" switch item.type { case "nor_video": route = location case "event_video": event = location case "cap_img": image = location default:break } } response = msg self.assetIndex = AssetIndex(image: image, event: event, route: route) print(self.assetIndex) case .fetchRouteVideos: let msg = try _decoder.decode(AssetsMessage.self, from: bytes) parse(assets: msg, target: &routeVideos, type: .route) delegate?.model(assets: routeVideos, type: .route) response = msg case .fetchEventVideos: let msg = try _decoder.decode(AssetsMessage.self, from: bytes) parse(assets: msg, target: &eventVideos, type: .event) delegate?.model(assets: eventVideos, type: .event) response = msg case .fetchImages: let msg = try _decoder.decode(AssetsMessage.self, from: bytes) parse(assets: msg, target: &tokenImages, type: .image) delegate?.model(assets: tokenImages, type: .image) response = msg case .captureImage, .captureVideo: let msg = try _decoder.decode(AcknowledgeMessage.self, from: bytes) response = msg case .notification: let msg = try _decoder.decode(CaptureNotification.self, from: bytes) guard let name = msg.param.split(separator: "/").last else {return} if msg.type == "photo_taken" { if let asset = parse(name: String(name), type: .image) { tokenImages.insert(asset, at: 0) delegate?.model(update: asset, type: .image) } } else if msg.type == "file_new" { if msg.param.contains("/EVENT/") { if let asset = parse(name: String(name), type: .event) { eventVideos.insert(asset, at: 0) delegate?.model(update: asset, type: .event) } } else { if let asset = parse(name: String(name), type: .route) { routeVideos.insert(asset, at: 0) delegate?.model(update: asset, type: .route) } } } response = msg } print(response) if command == .fetchAssetIndex { ready = true } } private var _countAsset: [AssetType: Int] = [:] func parse(name: String, type: AssetType) -> CameraAsset? { guard let trim = _trim else {return nil} let range = NSRange(location: 0, length: name.count) let text = trim.stringByReplacingMatches(in: name, options: [], range: range, withTemplate: "") let timestamp = _dateFormatter.date(from: text)! let id: String = String(text.split(separator: "_").last!) #if NATIVE_DEBUG let index = String(format: "%03d", _countAsset[type] ?? 0) let server = "http://\(LIVE_SERVER.addr):8080/camera" let sample = "\(server)/videos/sample.mp4" let asset: CameraAsset switch type { case .event, .route: asset = CameraAsset(id: id, name: "sample.mp4", url: sample, icon: "\(server)/videos/\(index).thm", timestamp: timestamp) case .image: asset = CameraAsset(id: id, name: "x\(index).jpg", url: "\(server)/images/x\(index).jpg", icon: "\(server)/images/x\(index).thm", timestamp: timestamp) } return asset #else if assetIndex == nil {return nil} let subpath: String switch type { case .event:subpath = assetIndex.event case .image:subpath = assetIndex.image case .route:subpath = assetIndex.route } let server = "http://\(LIVE_SERVER.addr)/\(subpath)" return CameraAsset(id: id, name: name, url: "\(server)/\(name)", icon: "\(server)/\(text).thm", timestamp: timestamp) #endif } func parse(assets: AssetsMessage, target:inout [CameraAsset], type: AssetType) { var dict: [String: CameraAsset] = [:] for item in target { dict[item.name] = item } for item in assets.listing { let name = item.name if dict[name] != nil { continue } if let asset = parse(name: name, type: type) { target.append(asset) _countAsset[type] = target.count } } target.sort(by: {$0.timestamp > $1.timestamp}) print(target) } private func preload() { fetchVersion() query(type: "app_status") query(type: "date_time") fetchAssetIndex() } private var _taskQueue: [[String: Any]] = [] func query(type: String = "date_time") { let params: [String: Any] = ["token": self.token, "msg_id": RemoteCommand.query.rawValue, "type": type] _session.send(data: params) } func fetchToken() { let params: [String: Any] = ["token": 0, "msg_id": RemoteCommand.fetchToken.rawValue] _session.send(data: params) } func fetchVersion() { let params: [String: Any] = ["token": self.token, "msg_id": RemoteCommand.fetchVersion.rawValue] _session.send(data: params) } func fetchAssetIndex() { let params: [String: Any] = ["token": self.token, "msg_id": RemoteCommand.fetchAssetIndex.rawValue] _session.send(data: params) } func fetchEventVideos(position num: Int = 0) { fetchCameraAssets(command: .fetchEventVideos, position: num, storage: &eventVideos) } func fetchRouteVideos(position num: Int = 0) { fetchCameraAssets(command: .fetchRouteVideos, position: num, storage: &routeVideos) } func fetchImages(position num: Int = 0) { fetchCameraAssets(command: .fetchImages, position: num, storage: &tokenImages) } private func fetchCameraAssets(command: RemoteCommand, position num: Int = 0, storage:inout [CameraAsset]) { let offset = (num == 0 ? storage.count : num) / 20 * 20 let params: [String: Any] = ["token": self.token, "msg_id": command.rawValue, "param": offset] _taskQueue.append(params) } func captureImage() { let params: [String: Any] = ["token": self.token, "msg_id": RemoteCommand.captureImage.rawValue] _taskQueue.append(params) } func captureVideo() { let params: [String: Any] = ["token": self.token, "msg_id": RemoteCommand.captureVideo.rawValue] _taskQueue.append(params) } }
mit
8b10ae0e52cb6b874d6e9bd867246c2f
33.567376
215
0.540213
4.153977
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Browser/TabLocationView.swift
1
13083
/* 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 UIKit import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger protocol TabLocationViewDelegate { func tabLocationViewDidTapLocation(tabLocationView: TabLocationView) func tabLocationViewDidLongPressLocation(tabLocationView: TabLocationView) func tabLocationViewDidTapReaderMode(tabLocationView: TabLocationView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func tabLocationViewDidLongPressReaderMode(tabLocationView: TabLocationView) -> Bool func tabLocationViewLocationAccessibilityActions(tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? } struct TabLocationViewUX { static let HostFontColor = UIColor.blackColor() static let BaseURLFontColor = UIColor.grayColor() static let BaseURLPitch = 0.75 static let HostPitch = 1.0 static let LocationContentInset = 8 static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.URLFontColor = UIColor.lightGrayColor() theme.hostFontColor = UIColor.whiteColor() theme.backgroundColor = UIConstants.PrivateModeLocationBackgroundColor themes[Theme.PrivateMode] = theme theme = Theme() theme.URLFontColor = BaseURLFontColor theme.hostFontColor = HostFontColor theme.backgroundColor = UIColor.whiteColor() themes[Theme.NormalMode] = theme return themes }() } class TabLocationView: UIView { var delegate: TabLocationViewDelegate? var longPressRecognizer: UILongPressGestureRecognizer! var tapRecognizer: UITapGestureRecognizer! dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor { didSet { updateTextWithURL() } } dynamic var hostFontColor: UIColor = TabLocationViewUX.HostFontColor { didSet { updateTextWithURL() } } var url: NSURL? { didSet { let wasHidden = lockImageView.hidden lockImageView.hidden = url?.scheme != "https" if wasHidden != lockImageView.hidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } updateTextWithURL() setNeedsUpdateConstraints() } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { if newReaderModeState != self.readerModeButton.readerModeState { let wasHidden = readerModeButton.hidden self.readerModeButton.readerModeState = newReaderModeState readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable) if wasHidden != readerModeButton.hidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } UIView.animateWithDuration(0.1, animations: { () -> Void in if newReaderModeState == ReaderModeState.Unavailable { self.readerModeButton.alpha = 0.0 } else { self.readerModeButton.alpha = 1.0 } self.setNeedsUpdateConstraints() self.layoutIfNeeded() }) } } } lazy var placeholder: NSAttributedString = { let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home") return NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()]) }() lazy var urlTextField: UITextField = { let urlTextField = DisplayTextField() self.longPressRecognizer.delegate = self urlTextField.addGestureRecognizer(self.longPressRecognizer) self.tapRecognizer.delegate = self urlTextField.addGestureRecognizer(self.tapRecognizer) // Prevent the field from compressing the toolbar buttons on the 4S in landscape. urlTextField.setContentCompressionResistancePriority(250, forAxis: UILayoutConstraintAxis.Horizontal) urlTextField.attributedPlaceholder = self.placeholder urlTextField.accessibilityIdentifier = "url" urlTextField.accessibilityActionsSource = self urlTextField.font = UIConstants.DefaultChromeFont return urlTextField }() private lazy var lockImageView: UIImageView = { let lockImageView = UIImageView(image: UIImage(named: "lock_verified.png")) lockImageView.hidden = true lockImageView.isAccessibilityElement = true lockImageView.contentMode = UIViewContentMode.Center lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure") return lockImageView }() private lazy var readerModeButton: ReaderModeButton = { let readerModeButton = ReaderModeButton(frame: CGRectZero) readerModeButton.hidden = true readerModeButton.addTarget(self, action: #selector(TabLocationView.SELtapReaderModeButton), forControlEvents: .TouchUpInside) readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(TabLocationView.SELlongPressReaderModeButton(_:)))) readerModeButton.isAccessibilityElement = true readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button") readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: #selector(TabLocationView.SELreaderModeCustomAction))] return readerModeButton }() override init(frame: CGRect) { super.init(frame: frame) longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(TabLocationView.SELlongPressLocation(_:))) tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TabLocationView.SELtapLocation(_:))) addSubview(urlTextField) addSubview(lockImageView) addSubview(readerModeButton) lockImageView.snp_makeConstraints { make in make.leading.centerY.equalTo(self) make.width.equalTo(self.lockImageView.intrinsicContentSize().width + CGFloat(TabLocationViewUX.LocationContentInset * 2)) } readerModeButton.snp_makeConstraints { make in make.trailing.centerY.equalTo(self) make.width.equalTo(self.readerModeButton.intrinsicContentSize().width + CGFloat(TabLocationViewUX.LocationContentInset * 2)) } } override var accessibilityElements: [AnyObject]! { get { return [lockImageView, urlTextField, readerModeButton].filter { !$0.hidden } } set { super.accessibilityElements = newValue } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { urlTextField.snp_remakeConstraints { make in make.top.bottom.equalTo(self) if lockImageView.hidden { make.leading.equalTo(self).offset(TabLocationViewUX.LocationContentInset) } else { make.leading.equalTo(self.lockImageView.snp_trailing) } if readerModeButton.hidden { make.trailing.equalTo(self).offset(-TabLocationViewUX.LocationContentInset) } else { make.trailing.equalTo(self.readerModeButton.snp_leading) } } super.updateConstraints() } func SELtapReaderModeButton() { delegate?.tabLocationViewDidTapReaderMode(self) } func SELlongPressReaderModeButton(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { delegate?.tabLocationViewDidLongPressReaderMode(self) } } func SELlongPressLocation(recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { delegate?.tabLocationViewDidLongPressLocation(self) } } func SELtapLocation(recognizer: UITapGestureRecognizer) { delegate?.tabLocationViewDidTapLocation(self) } func SELreaderModeCustomAction() -> Bool { return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false } private func updateTextWithURL() { if let httplessURL = url?.absoluteDisplayString(), let baseDomain = url?.baseDomain() { // Highlight the base domain of the current URL. let attributedString = NSMutableAttributedString(string: httplessURL) let nsRange = NSMakeRange(0, httplessURL.characters.count) attributedString.addAttribute(NSForegroundColorAttributeName, value: baseURLFontColor, range: nsRange) attributedString.colorSubstring(baseDomain, withColor: hostFontColor) attributedString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(double: TabLocationViewUX.BaseURLPitch), range: nsRange) attributedString.pitchSubstring(baseDomain, withPitch: TabLocationViewUX.HostPitch) urlTextField.attributedText = attributedString } else { // If we're unable to highlight the domain, just use the URL as is. if let host = url?.host { urlTextField.text = url?.absoluteString?.stringByReplacingOccurrencesOfString(host, withString: host.asciiHostToUTF8()) } else { urlTextField.text = url?.absoluteString } } } } extension TabLocationView: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { // If the longPressRecognizer is active, fail all other recognizers to avoid conflicts. return gestureRecognizer == longPressRecognizer } } extension TabLocationView: AccessibilityActionsSource { func accessibilityCustomActionsForView(view: UIView) -> [UIAccessibilityCustomAction]? { if view === urlTextField { return delegate?.tabLocationViewLocationAccessibilityActions(self) } return nil } } extension TabLocationView: Themeable { func applyTheme(themeName: String) { guard let theme = TabLocationViewUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } baseURLFontColor = theme.URLFontColor! hostFontColor = theme.hostFontColor! backgroundColor = theme.backgroundColor } } private class ReaderModeButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal) setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var _readerModeState: ReaderModeState = ReaderModeState.Unavailable var readerModeState: ReaderModeState { get { return _readerModeState } set (newReaderModeState) { _readerModeState = newReaderModeState switch _readerModeState { case .Available: self.enabled = true self.selected = false case .Unavailable: self.enabled = false self.selected = false case .Active: self.enabled = true self.selected = true } } } } private class DisplayTextField: UITextField { weak var accessibilityActionsSource: AccessibilityActionsSource? override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { get { return accessibilityActionsSource?.accessibilityCustomActionsForView(self) } set { super.accessibilityCustomActions = newValue } } private override func canBecomeFirstResponder() -> Bool { return false } }
mpl-2.0
7e701b7952e64e54d41257cff67e2fbe
39.884375
289
0.684935
6.017939
false
false
false
false
minikin/Algorithmics
Pods/Charts/Charts/Classes/Renderers/ScatterChartRenderer.swift
6
16151
// // ScatterChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ScatterChartRenderer: LineScatterCandleRadarChartRenderer { public weak var dataProvider: ScatterChartDataProvider? public init(dataProvider: ScatterChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let scatterData = dataProvider?.scatterData else { return } for (var i = 0; i < scatterData.dataSetCount; i++) { guard let set = scatterData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is IScatterChartDataSet) { fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet") } drawDataSet(context: context, dataSet: set as! IScatterChartDataSet) } } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawDataSet(context context: CGContext, dataSet: IScatterChartDataSet) { guard let dataProvider = dataProvider, animator = animator else { return } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius let shapeHoleSize = shapeHoleSizeHalf * 2.0 let shapeHoleColor = dataSet.scatterShapeHoleColor let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0 let shapeStrokeSizeHalf = shapeStrokeSize / 2.0 var point = CGPoint() let valueToPixelMatrix = trans.valueToPixelMatrix let shape = dataSet.scatterShape CGContextSaveGState(context) for (var j = 0, count = Int(min(ceil(CGFloat(entryCount) * animator.phaseX), CGFloat(entryCount))); j < count; j++) { guard let e = dataSet.entryForIndex(j) else { continue } point.x = CGFloat(e.xIndex) point.y = CGFloat(e.value) * phaseY point = CGPointApplyAffineTransform(point, valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(point.x)) { break } if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y)) { continue } if (shape == .Square) { if shapeHoleSize > 0.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextSetLineWidth(context, shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize CGContextStrokeRect(context, rect) if let shapeHoleColor = shapeHoleColor { CGContextSetFillColorWithColor(context, shapeHoleColor.CGColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize CGContextFillRect(context, rect) } } else { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillRect(context, rect) } } else if (shape == .Circle) { if shapeHoleSize > 0.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextSetLineWidth(context, shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize CGContextStrokeEllipseInRect(context, rect) if let shapeHoleColor = shapeHoleColor { CGContextSetFillColorWithColor(context, shapeHoleColor.CGColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize CGContextFillEllipseInRect(context, rect) } } else { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillEllipseInRect(context, rect) } } else if (shape == .Triangle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf) CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf) CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf) if shapeHoleSize > 0.0 { CGContextAddLineToPoint(context, point.x, point.y - shapeHalf) CGContextMoveToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x + shapeHalf - shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x, point.y - shapeHalf + shapeStrokeSize) CGContextAddLineToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) } CGContextClosePath(context) CGContextFillPath(context) if shapeHoleSize > 0.0 && shapeHoleColor != nil { CGContextSetFillColorWithColor(context, shapeHoleColor!.CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf + shapeStrokeSize) CGContextAddLineToPoint(context, point.x + shapeHalf - shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextClosePath(context) CGContextFillPath(context) } } else if (shape == .Cross) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .X) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x + shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x - shapeHalf _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .Custom) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) let customShape = dataSet.customScatterShape if customShape == nil { return } // transform the provided custom path CGContextSaveGState(context) CGContextTranslateCTM(context, point.x, point.y) CGContextBeginPath(context) CGContextAddPath(context, customShape) CGContextFillPath(context) CGContextRestoreGState(context) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, scatterData = dataProvider.scatterData, animator = animator else { return } // if values are drawn if (scatterData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX))) { guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY var pt = CGPoint() for (var i = 0; i < scatterData.dataSetCount; i++) { let dataSet = dataSets[i] if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let lineHeight = valueFont.lineHeight for (var j = 0, count = Int(ceil(CGFloat(entryCount) * phaseX)); j < count; j++) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the lines don't do shitty things outside bounds if ((!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))) { continue } let text = formatter.stringFromNumber(e.value) ChartUtils.drawText( context: context, text: text!, point: CGPoint( x: pt.x, y: pt.y - shapeSize - lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } } } public override func drawExtras(context context: CGContext) { } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, scatterData = dataProvider.scatterData, animator = animator else { return } let chartXMax = dataProvider.chartXMax CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { guard let set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as? IScatterChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX) { continue } let yVal = set.yValForXIndex(xIndex) if (yVal.isNaN) { continue } let y = CGFloat(yVal) * animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider.getTransformer(set.axisDependency) trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
mit
65f9369dccaa8e28f20b76c74c8c5a0b
38.783251
141
0.518296
6.386319
false
false
false
false
gezhixin/MoreThanDrawerMenumDemo
special/Mian/home/view/HomePageHeaderTableViewCell.swift
1
2073
// // HomePageHeaderTableViewCell.swift // special // // Created by 葛枝鑫 on 15/5/1. // Copyright (c) 2015年 葛枝鑫. All rights reserved. // import UIKit class HomePageHeaderTableViewCell: UITableViewCell { @IBOutlet weak var dayLabel: UILabel! @IBOutlet weak var yearAndMonLabel: UILabel! @IBOutlet weak var weakLabel: UILabel! var delegate: HomePageHeaderViewDelegate? static func createView() -> HomePageHeaderTableViewCell { let cell = NSBundle.mainBundle().loadNibNamed("HomePageHeaderTableViewCell", owner: nil, options: nil).first as! HomePageHeaderTableViewCell return cell } override func awakeFromNib() { super.awakeFromNib() self.setDate() self.layoutIfNeeded() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } //日前格式 func setDate() { var arrWeak = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] let date = NSDate() let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar) let timeZone = NSTimeZone(name: "Asia/Shanghai") let unitFlags: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Weekday] calendar?.timeZone = timeZone! let comps = calendar?.components(unitFlags, fromDate: date) let week = comps?.weekday let year = comps?.year let mon = comps?.month let day = comps?.day let strWeak = arrWeak[week! - 1] let strDay = day < 10 ? "0\(day!)" : "\(day!)" let strYearAndMon = "\(year!)年\(mon!)月" self.weakLabel.text = strWeak self.dayLabel.text = strDay self.yearAndMonLabel.text = strYearAndMon } } @objc protocol HomePageHeaderViewDelegate : NSObjectProtocol { optional func HomePageHeaderView(headerView:HomePageHeaderTableViewCell, menuBtnClicked: UIButton) }
mit
6bb11d8cab55e69854916888e03e5d4d
28.057971
147
0.64788
4.39693
false
false
false
false
con-beo-vang/Spendy
Spendy/View Controllers/AddTransactionViewController.swift
1
20656
// // AddViewController.swift // Spendy // // Created by Dave Vo on 9/16/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit import PhotoTweaks class AddTransactionViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var addImageView: UIImageView! var addButton: UIButton? var cancelButton: UIButton? var isCollaped = true var datePickerIsShown = false var noteCell: NoteCell? var amountCell: AmountCell? var categoryCell: SelectAccountOrCategoryCell? var accountCell: SelectAccountOrCategoryCell? var toAccountCell: SelectAccountOrCategoryCell? var dateCell: DateCell? var photoCell: PhotoCell? var selectedTransaction: Transaction? var currentAccount: Account! var imagePicker: UIImagePickerController! // remember the selected category under each transaction kind var backupCategories = [String : Category?]() var backupAccounts = [String : Account? ]() var validationErrors = [String]() // MARK: - Main functions override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() isCollaped = true addBarButton() setupAddImageView() imagePicker = UIImagePickerController() imagePicker.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if currentAccount == nil { currentAccount = Account.defaultAccount() } if let transaction = selectedTransaction { if transaction.isNew() { navigationItem.title = "Add Transaction" } else { navigationItem.title = "Edit Transaction" } } else { // TODO: add a convenience contructor to Transaction selectedTransaction = Transaction() selectedTransaction!.kind = CategoryType.Expense.rawValue selectedTransaction!.category = Category.defaultCategoryFor(.Expense) selectedTransaction!.fromAccount = currentAccount selectedTransaction!.date = NSDate() // TODO: replace with a good default amount // selectedTransaction!.amount = 10 isCollaped = true } tableView.reloadData() // Change button's color based on strong color Helper.sharedInstance.setIconLayer(addImageView) } func setupAddImageView() { addImageView.image = Helper.sharedInstance.createIcon("Bar-Tick") let tapGesture = UITapGestureRecognizer(target: self, action: "onAddImageTapped:") addImageView.addGestureRecognizer(tapGesture) } func onAddImageTapped(sender: UITapGestureRecognizer) { handleAddTransaction() } func updateFieldsToTransaction() -> Bool { validationErrors = [] if let transaction = self.selectedTransaction { transaction.update { t in t.note = self.noteCell?.noteText.text t.kind = CategoryType.allValueStrings[self.amountCell!.typeSegment.selectedSegmentIndex] t.amountDecimal = NSDecimalNumber(string: self.amountCell?.amountText.text) if t.amount == 0 { self.validationErrors.append("Please enter an amount") } // TODO: validate date is in the past if let date = self.dateCell?.datePicker.date { t.date = date print("setting date to transaction: \(date)") } } } if let transaction = selectedTransaction { if transaction.isTransfer() { if transaction.toAccount == nil { validationErrors.append("Please specifiy To Account:") } else if transaction.toAccount?.id == transaction.fromAccount?.id { validationErrors.append("From and To accounts must be different") } } } return validationErrors.isEmpty } // MARK: Button func addBarButton() { addButton = UIButton() Helper.sharedInstance.customizeBarButton(self, button: addButton!, imageName: "Bar-Tick", isLeft: false) addButton!.addTarget(self, action: "onAddButton:", forControlEvents: UIControlEvents.TouchUpInside) cancelButton = UIButton() Helper.sharedInstance.customizeBarButton(self, button: cancelButton!, imageName: "Bar-Cancel", isLeft: true) cancelButton!.addTarget(self, action: "onCancelButton:", forControlEvents: UIControlEvents.TouchUpInside) } func onAddButton(sender: UIButton!) { handleAddTransaction() } func handleAddTransaction() { // check if we can update fields // show errors if can't guard updateFieldsToTransaction() else { let nextError = validationErrors.first! let alertController = UIAlertController(title: nextError, message: nil, preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in // ... } alertController.addAction(OKAction) presentViewController(alertController, animated: true) {} return } guard let transaction = selectedTransaction else { print("Error: selectedTransaction is nil") return } print("[onAddButton] transaction: \(transaction)") // TODO: add transaction and update both fromAccount and toAccount stats // - save transaction to database // - view must know about the transaction in the parent account (fromAccount, and maybe toAccount if it's a transfer) transaction.save() print("posting notification TransactionAddedOrUpdated") NSNotificationCenter.defaultCenter().postNotificationName("TransactionAddedOrUpdated", object: nil, userInfo: ["account": transaction.fromAccount!]) if let toAccount = transaction.toAccount { NSNotificationCenter.defaultCenter().postNotificationName("TransactionAddedOrUpdated", object: nil, userInfo: ["account": toAccount]) } closeView() } func closeTabAndSwitchToHome() { // unhide the tabBar because we hid it for the Add tab self.tabBarController?.tabBar.hidden = false let rootVC = parentViewController?.parentViewController as? RootTabBarController // go to Accouns tab rootVC?.selectedIndex = 1 let accountsNVC = rootVC?.viewControllers?.at(1) as? UINavigationController let accountsVC = accountsNVC?.topViewController as? AccountsViewController accountsVC?.justAddTransactions = true accountsVC?.addedAccount = selectedTransaction?.fromAccount selectedTransaction = nil } func onCancelButton(sender: UIButton!) { closeView() } func closeView() { switch presentingViewController { case is AccountDetailViewController, is RootTabBarController: print("exiting modal from \(presentingViewController)") dismissViewControllerAnimated(true, completion: nil) default: guard navigationController != nil else { print("Error closing view: \(self)") return } // exit push navigationController!.popViewControllerAnimated(true) } closeTabAndSwitchToHome() } } // MARK: - Transfer between 2 views extension AddTransactionViewController: SelectAccountOrCategoryDelegate, PhotoViewControllerDelegate { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { updateFieldsToTransaction() // Dismiss all keyboard and datepicker view.endEditing(true) reloadDatePicker() let toController = segue.destinationViewController if toController is SelectAccountOrCategoryViewController { let vc = toController as! SelectAccountOrCategoryViewController let cell = sender as! SelectAccountOrCategoryCell vc.itemClass = cell.itemClass vc.itemTypeFilter = cell.itemTypeFilter vc.delegate = self if cell.itemClass == "Category" { vc.selectedItem = selectedTransaction!.category } else { if cell.itemTypeFilter == "ToAccount" { vc.selectedItem = selectedTransaction!.toAccount } else { vc.selectedItem = selectedTransaction!.fromAccount } } // TODO: delegate } else if toController is PhotoViewController { let photoCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 3)) as? PhotoCell if let photoCell = photoCell { if photoCell.photoView.image == nil { Helper.sharedInstance.showActionSheet(self, imagePicker: imagePicker) } else { let photoVC = toController as! PhotoViewController photoVC.selectedImage = photoCell.photoView.image photoVC.delegate = self } } } } func selectAccountOrCategoryViewController(selectAccountOrCategoryController: SelectAccountOrCategoryViewController, selectedItem item: AnyObject, selectedType type: String?) { if item is Account { if let type = type where type == "ToAccount" { selectedTransaction!.update { $0.toAccount = (item as! Account) } } else { selectedTransaction!.update { $0.fromAccount = (item as! Account) } } tableView.reloadData() } else if item is Category { selectedTransaction!.update {$0.category = (item as! Category) } tableView.reloadData() } else { print("Error: item is \(item)") } } func photoViewController(photoViewController: PhotoViewController, didUpdateImage image: UIImage) { let photoCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 3)) as? PhotoCell if let photoCell = photoCell { photoCell.photoView.image = image } } } // MARK: - Table View extension AddTransactionViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return isCollaped ? 3 : 4 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 2 case 1: if selectedTransaction != nil && selectedTransaction!.isTransfer() { // 3 rows: // Category (fixed as Transfer) // From Account // To Account return 3 } else { // 2 rows: // Category // Account return 2 } case 2: return 1 case 3: return 1 default: return 0 } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return ((indexPath.section == 2 && datePickerIsShown) ? 182 : 40) } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 30)) headerView.backgroundColor = UIColor(netHex: 0xDCDCDC) if section == 0 { let todayLabel = UILabel(frame: CGRect(x: 8, y: 2, width: UIScreen.mainScreen().bounds.width - 16, height: 30)) todayLabel.font = UIFont.systemFontOfSize(14) let today = NSDate() todayLabel.text = DateFormatter.fullStyle.stringFromDate(today) headerView.addSubview(todayLabel) } return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 2 ? 0 : 34 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let dummyCell = UITableViewCell() switch indexPath.section { case 0: switch indexPath.row { case 0: let cell = tableView.dequeueReusableCellWithIdentifier("NoteCell", forIndexPath: indexPath) as! NoteCell cell.noteText.text = selectedTransaction?.note let tapCell = UITapGestureRecognizer(target: self, action: "tapNoteCell:") cell.addGestureRecognizer(tapCell) cell.setSeparatorFullWidth() if noteCell == nil { noteCell = cell } return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier("AmountCell", forIndexPath: indexPath) as! AmountCell if !selectedTransaction!.isNew() { cell.amountText.text = selectedTransaction!.amountDecimal?.stringValue } cell.amountText.keyboardType = UIKeyboardType.DecimalPad cell.setSeparatorFullWidth() if amountCell == nil { amountCell = cell // Only add gesture recognizers once cell.typeSegment.addTarget(self, action: "typeSegmentChanged:", forControlEvents: UIControlEvents.ValueChanged) print("Added typeSegmentChanged gesture. Should only do once") let tapCell = UITapGestureRecognizer(target: self, action: "tapAmoutCell:") cell.addGestureRecognizer(tapCell) print("Added tapAmountCell gesture") } // TODO refactor into AmountCell guard let transaction = selectedTransaction, segmentIndex = CategoryType.allValueStrings.indexOf(transaction.kind!), segment = cell.typeSegment else { return cell } segment.selectedSegmentIndex = segmentIndex switch segmentIndex { case 0: segment.tintColor = Color.incomeColor case 1: segment.tintColor = Color.expenseColor case 2: segment.tintColor = Color.balanceColor default: print("Invalid segment index: \(segmentIndex)") } return cell default: break } break case 1: switch indexPath.row { case 0: let cell = tableView.dequeueReusableCellWithIdentifier("SelectAccountOrCategoryCell", forIndexPath: indexPath) as! SelectAccountOrCategoryCell cell.itemClass = "Category" cell.category = selectedTransaction!.category cell.setSeparatorFullWidth() if categoryCell == nil { categoryCell = cell } return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier("SelectAccountOrCategoryCell", forIndexPath: indexPath) as! SelectAccountOrCategoryCell cell.itemClass = "Account" print("kind: \(selectedTransaction!.kind)") if selectedTransaction!.isTransfer() { cell.fromAccount = selectedTransaction!.fromAccount } else { cell.account = selectedTransaction!.fromAccount } cell.setSeparatorFullWidth() if accountCell == nil { accountCell = cell } return cell case 2: // Only for Transfer category type guard let category = selectedTransaction!.category where category.isTransfer() else { break } let cell = tableView.dequeueReusableCellWithIdentifier("SelectAccountOrCategoryCell", forIndexPath: indexPath) as! SelectAccountOrCategoryCell cell.itemClass = "Account" cell.toAccount = selectedTransaction!.toAccount cell.setSeparatorFullWidth() if toAccountCell == nil { toAccountCell = cell } return cell default: break } break case 2: if isCollaped { let cell = tableView.dequeueReusableCellWithIdentifier("ViewMoreCell", forIndexPath: indexPath) as! ViewMoreCell cell.titleLabel.textColor = Color.moreDetailColor let tapCell = UITapGestureRecognizer(target: self, action: "tapMoreCell:") cell.addGestureRecognizer(tapCell) cell.setSeparatorFullWidth() return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("DateCell", forIndexPath: indexPath) as! DateCell cell.titleLabel.text = "Date" cell.delegate = self let date = selectedTransaction!.date ?? NSDate() cell.datePicker.date = date cell.dateLabel.text = DateFormatter.E_MMM_dd_yyyy.stringFromDate(date) let tapCell = UITapGestureRecognizer(target: self, action: "tapDateCell:") cell.addGestureRecognizer(tapCell) cell.datePicker.alpha = datePickerIsShown ? 1 : 0 cell.setSeparatorFullWidth() // override previous datecell with this datecell with datepicker dateCell = cell return cell } case 3: let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell", forIndexPath: indexPath) as! PhotoCell cell.setSeparatorFullWidth() if photoCell == nil { photoCell = cell } return cell default: break } return dummyCell } @IBAction func onAmountChanged(sender: UITextField) { sender.preventInputManyDots() } } // MARK: - Handle gestures extension AddTransactionViewController { func tapNoteCell(sender: UITapGestureRecognizer) { noteCell!.noteText.becomeFirstResponder() } func tapAmoutCell(sender: UITapGestureRecognizer) { amountCell!.amountText.becomeFirstResponder() } func tapMoreCell(sender: UITapGestureRecognizer) { isCollaped = false updateFieldsToTransaction() UIView.transitionWithView(tableView, duration:0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in self.tableView.reloadData() }, completion: nil) } func tapDateCell(sender: UITapGestureRecognizer) { view.endEditing(true) reloadDatePicker() } func typeSegmentChanged(sender: UISegmentedControl) { updateFieldsToTransaction() // back up category choice for each segment value // so that when we switch back, it can be resumed let newType = CategoryType.allValues[sender.selectedSegmentIndex] if let oldCategory = selectedTransaction!.category { backupCategories[oldCategory.type!] = oldCategory } // set new category selectedTransaction!.category = backupCategories[newType.rawValue] ?? Category.defaultCategoryFor(newType) if newType == .Transfer { // reset cached value selectedTransaction!.toAccount = backupAccounts["ToAccount"] ?? Account.nonDefaultAccount() } else { // back up, then nullify if let toAccount = selectedTransaction!.toAccount { backupAccounts["ToAccount"] = toAccount } selectedTransaction!.toAccount = nil } print("transaction: \(selectedTransaction?.description)") tableView.reloadData() } } // MARK: - UIImagePickerController extension AddTransactionViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { let photoTweaksViewController = PhotoTweaksViewController(image: pickedImage) photoTweaksViewController.delegate = self imagePicker.pushViewController(photoTweaksViewController, animated: true) } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } } // MARK: - Photo Tweaks extension AddTransactionViewController: PhotoTweaksViewControllerDelegate { func photoTweaksController(controller: PhotoTweaksViewController!, didFinishWithCroppedImage croppedImage: UIImage!) { // Get photo cell let photoCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 3)) as? PhotoCell if let photoCell = photoCell { photoCell.photoView.contentMode = .ScaleToFill photoCell.photoView.image = croppedImage } controller.navigationController?.dismissViewControllerAnimated(true, completion: nil) } func photoTweaksControllerDidCancel(controller: PhotoTweaksViewController!) { controller.navigationController?.dismissViewControllerAnimated(true, completion: nil) } } // MARK: - Handle date picker extension AddTransactionViewController: DateCellDelegate { func dateCell(dateCell: DateCell, selectedDate: NSDate) { selectedTransaction!.date = selectedDate reloadDatePicker() } func reloadDatePicker() { datePickerIsShown = !datePickerIsShown tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: UITableViewRowAnimation.Automatic) } }
mit
14ab82bd3cde87710b68458a2dc8fc62
30.392097
178
0.670362
5.314124
false
false
false
false
VirgilSecurity/virgil-sdk-keys-x
Source/Keyknox/Client/Models/KeyknoxValue.swift
2
3786
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Value stored on Keyknox service @objc(VSSKeyknoxValue) public class KeyknoxValue: NSObject { @objc public let root: String @objc public let path: String @objc public let key: String @objc public let owner: String @objc public let identities: [String] /// Meta info @objc public let meta: Data /// Value @objc public let value: Data /// Keyknox hash @objc public let keyknoxHash: Data internal convenience init(keyknoxData: KeyknoxDataV2, keyknoxHash: Data) { self.init(root: keyknoxData.root, path: keyknoxData.path, key: keyknoxData.key, owner: keyknoxData.owner, identities: keyknoxData.identities, meta: keyknoxData.meta, value: keyknoxData.value, keyknoxHash: keyknoxHash) } internal convenience init(keyknoxData: KeyknoxData, keyknoxHash: Data, identity: String) { self.init(root: KeyknoxClient.keyStorageRoot, path: KeyknoxClient.keyStoragePath, key: KeyknoxClient.keyStorageKey, owner: identity, identities: [identity], meta: keyknoxData.meta, value: keyknoxData.value, keyknoxHash: keyknoxHash) } internal init(root: String, path: String, key: String, owner: String, identities: [String], meta: Data, value: Data, keyknoxHash: Data) { self.root = root self.path = path self.key = key self.owner = owner self.identities = identities self.meta = meta self.value = value self.keyknoxHash = keyknoxHash super.init() } } /// Represent encrypted Keyknox value @objc(VSSEncryptedKeyknoxValue) public class EncryptedKeyknoxValue: KeyknoxValue { } /// Represent decrypted Keyknox value @objc(VSSDecryptedKeyknoxValue) public class DecryptedKeyknoxValue: KeyknoxValue { }
bsd-3-clause
bc2109ee79b36712fc0c4bd5feeb1b49
35.757282
94
0.655045
4.634027
false
false
false
false
frtlupsvn/Vietnam-To-Go
Pods/Former/Former/Commons/SectionFormer.swift
1
5970
// // SectionFormer.swift // Former-Demo // // Created by Ryo Aoyama on 7/23/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public final class SectionFormer { // MARK: Public public init(rowFormer: RowFormer...) { self.rowFormers = rowFormer } public init(rowFormers: [RowFormer] = []) { self.rowFormers = rowFormers } /// All RowFormers. Default is empty. public private(set) var rowFormers = [RowFormer]() /// ViewFormer of applying section header. Default is applying simply 10px spacing section header. public private(set) var headerViewFormer: ViewFormer? = ViewFormer(viewType: FormHeaderFooterView.self, instantiateType: .Class) /// ViewFormer of applying section footer. Default is nil. public private(set) var footerViewFormer: ViewFormer? /// Return all row count. public var numberOfRows: Int { return rowFormers.count } /// Returns the first element of RowFormers, or `nil` if `self.rowFormers` is empty. public var firstRowFormer: RowFormer? { return rowFormers.first } /// Returns the last element of RowFormers, or `nil` if `self.rowFormers` is empty. public var lastRowFormer: RowFormer? { return rowFormers.last } public subscript(index: Int) -> RowFormer { return rowFormers[index] } public subscript(range: Range<Int>) -> [RowFormer] { return Array<RowFormer>(rowFormers[range]) } /// Append RowFormer to last index. public func append(rowFormer rowFormer: RowFormer...) -> Self { add(rowFormers: rowFormer) return self } /// Add RowFormers to last index. public func add(rowFormers rowFormers: [RowFormer]) -> Self { self.rowFormers += rowFormers return self } /// Insert RowFormer to any index. public func insert(rowFormer rowFormer: RowFormer..., toIndex: Int) -> Self { let count = self.rowFormers.count if count == 0 || toIndex >= count { add(rowFormers: rowFormers) return self } self.rowFormers.insertContentsOf(rowFormers, at: toIndex) return self } /// Insert RowFormers to any index. public func insert(rowFormers rowFormers: [RowFormer], toIndex: Int) -> Self { let count = self.rowFormers.count if count == 0 || toIndex >= count { add(rowFormers: rowFormers) return self } self.rowFormers.insertContentsOf(rowFormers, at: toIndex) return self } /// Insert RowFormer to above other SectionFormer. public func insert(rowFormer rowFormer: RowFormer..., above: RowFormer) -> Self { for (row, rowFormer) in self.rowFormers.enumerate() { if rowFormer === above { insert(rowFormers: [rowFormer], toIndex: row) return self } } add(rowFormers: rowFormers) return self } /// Insert RowFormers to above other SectionFormer. public func insert(rowFormers rowFormers: [RowFormer], above: RowFormer) -> Self { for (row, rowFormer) in self.rowFormers.enumerate() { if rowFormer === above { insert(rowFormers: [rowFormer], toIndex: row) return self } } add(rowFormers: rowFormers) return self } /// Insert RowFormer to below other SectionFormer. public func insert(rowFormer rowFormer: RowFormer..., below: RowFormer) -> Self { for (row, rowFormer) in self.rowFormers.enumerate() { if rowFormer === below { insert(rowFormers: [rowFormer], toIndex: row + 1) return self } } add(rowFormers: rowFormers) return self } /// Insert RowFormers to below other SectionFormer. public func insert(rowFormers rowFormers: [RowFormer], below: RowFormer) -> Self { for (row, rowFormer) in self.rowFormers.enumerate() { if rowFormer === below { insert(rowFormers: [rowFormer], toIndex: row + 1) return self } } add(rowFormers: rowFormers) return self } /// Remove RowFormers from instances of RowFormer. public func remove(rowFormer rowFormer: RowFormer...) -> Self { var removedCount = 0 for (index, rowFormer) in self.rowFormers.enumerate() { if rowFormers.contains({ $0 === rowFormer }) { remove(index) if ++removedCount >= rowFormers.count { return self } } } return self } /// Remove RowFormers from instances of RowFormer. public func remove(rowFormers rowFormers: [RowFormer]) -> Self { var removedCount = 0 for (index, rowFormer) in self.rowFormers.enumerate() { if rowFormers.contains({ $0 === rowFormer }) { remove(index) if ++removedCount >= rowFormers.count { return self } } } return self } /// Remove RowFormer from index. public func remove(atIndex: Int) -> Self { rowFormers.removeAtIndex(atIndex) return self } /// Remove RowFormers from range. public func remove(range: Range<Int>) -> Self{ rowFormers.removeRange(range) return self } /// Set ViewFormer to apply section header. public func set(headerViewFormer viewFormer: ViewFormer?) -> Self { headerViewFormer = viewFormer return self } /// Set ViewFormer to apply section footer. public func set(footerViewFormer viewFormer: ViewFormer?) -> Self { footerViewFormer = viewFormer return self } }
mit
869a6c44166bc8e2e39474795f6ff209
30.755319
132
0.587703
4.920857
false
false
false
false
jfosterdavis/Charles
Charles/DataViewController+CoreGameLogic.swift
1
47951
// // DataViewController+CoreGameLogic.swift // Charles // // Created by Jacob Foster Davis on 5/29/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit import AVFoundation import CoreData extension DataViewController { /******************************************************/ /*******************///MARK: Core Game /******************************************************/ @IBAction func buttonPress(_ sender: UIButton) { //2. Play the current subphrase with the tone of the pressed button. //if the audio is already playing, don't do anything: // guard audioPlayer.isPlaying == false else { // return // } //don't do anything if character is not enabled guard characterInteractionEnabled else { return } var sendingButton: UIButton? //prepare the subphrase. if it is gone too far, reset if currentSubphraseIndex >= currentPhrase.subphrases!.count { currentSubphraseIndex = 0 } //find the button that was pressed for button in currentButtons { if sender == button { sendingButton = button } } guard sendingButton != nil else { //TODO: handle nil return } //prepare to speak let subphraseToSound = currentPhrase.subphrases![currentSubphraseIndex] ///******************************************************/ /*******************///MARK: Perk Implimentation: musicalVoices Synesthesia /******************************************************/ let applicableUnlockedMusicalVoicesPerks = getAllPerks(ofType: .musicalVoices, withStatus: .unlocked) if applicableUnlockedMusicalVoicesPerks.isEmpty { //no perks active //determine if there is a valid .m4a file to play, otherwise speak the word if subphraseToSound.audioFilePath != nil { //try to find file let url = URL(fileURLWithPath: subphraseToSound.audioFilePath!) do { try audioPlayer = AVAudioPlayer(contentsOf: url) audioPlayer.enableRate = true //if this is the first phrase in the series then reset the audio player if currentSubphraseIndex == 0 { resetAudioEngineAndPlayer() } // try audioPlayer = AVAudioPlayer(contentsOf: url) let audioFile = try AVAudioFile(forReading: url) changePitchEffect.pitch = currentPhrase.slots![currentButtons.index(of: sendingButton!)!].tone audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil) audioPlayerNode.scheduleFile(audioFile, at: nil, completionHandler: nil) try audioEngine.start() audioPlayerNode.play() //audioPlayer.play() } catch { //there was an error, so speak it instead speak(subphrase: currentPhrase.subphrases![currentSubphraseIndex]) } } else { speak(subphrase: currentPhrase.subphrases![currentSubphraseIndex]) } } else { //perks are active /******************************************************/ /*******************///MARK: PERK SYNESTHESIA MUSICALVOICES /******************************************************/ //get the most advanced of the perks (they do not stack) var highestPerk: Perk = applicableUnlockedMusicalVoicesPerks[0].0 var highestPerkLevel = 1 for (perk, _) in applicableUnlockedMusicalVoicesPerks { let thisLevel: Int switch perk { case let x where x === Perks.Synesthesia: //level 1 thisLevel = 1 case let x where x === Perks.Synesthesia2: //level 2 thisLevel = 2 case let x where x === Perks.Synesthesia3: //level 3 thisLevel = 3 default: //level 1 thisLevel = 1 } if thisLevel > highestPerkLevel { highestPerkLevel = thisLevel highestPerk = perk } } print("Highest Synesthesia level is \(highestPerkLevel). Name of perk is \(highestPerk.name)") //load the perk meta values (which is related to the level, some higher perks have more sound files and only top have the final sound file) let meta1 = highestPerk.meta1 //this should never be nil (it is an optional, but in Perks this should not be set to nil) let meta2 = highestPerk.meta2 //this could be nil let meta3 = highestPerk.meta3 //this could be nil let url1 = URL(fileURLWithPath: meta1 as! String) let url2: URL let urlFinal: URL if meta2 != nil { //if the second meta is nil, use the first meta, which should never be nil url2 = URL(fileURLWithPath: meta2 as! String) } else { url2 = URL(fileURLWithPath: meta1 as! String) } if meta3 != nil { //if the third meta is nil, the first sound is used as the last sound. urlFinal = URL(fileURLWithPath: meta3 as! String) } else { urlFinal = URL(fileURLWithPath: meta1 as! String) } let urls = [url1, url2] //select a random URL to play let selectedUrl: URL //if this is the last subphrase in the series, play the final if (currentSubphraseIndex + 1) >= currentPhrase.subphrases!.count { selectedUrl = urlFinal } else { selectedUrl = urls[Utilities.random(range: 0...(urls.count - 1))] } do { try audioPlayer = AVAudioPlayer(contentsOf: selectedUrl) audioPlayer.enableRate = true //if this is the first phrase in the series then reset the audio player if currentSubphraseIndex == 0 { resetAudioEngineAndPlayer() } // try audioPlayer = AVAudioPlayer(contentsOf: url) let audioFile = try AVAudioFile(forReading: selectedUrl) let rawTone = currentPhrase.slots![currentButtons.index(of: sendingButton!)!].tone var newTone = rawTone! //now reduce the tone to make it soothing unless this is level 1, which doesn't get this benefit as much if highestPerkLevel > 1 { newTone -= 1200 //if this is the second to last subphrase and if this is level 2 or higher, make pitch very low to give user a hint if (currentSubphraseIndex + 2) >= currentPhrase.subphrases!.count { if highestPerkLevel > 2 { newTone -= 2100 } else { //player is only level 2 perk so make this distinction very subtle newTone -= 1000 } } } else { newTone -= 500 } changePitchEffect.pitch = newTone //don't change the pitch of this is the final tone if selectedUrl == urlFinal { changePitchEffect.pitch = -100 } audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: synesthesiaReverb, format: nil) audioEngine.connect(synesthesiaReverb, to: synesthesiaDistortion, format: nil) audioEngine.connect(synesthesiaDistortion, to: audioEngine.outputNode, format: nil) audioPlayerNode.scheduleFile(audioFile, at: nil, completionHandler: nil) try audioEngine.start() audioPlayerNode.play() //you are about to do Synesthesia so give player visual feedback let intensity = abs(newTone)/2500.0 print("intensity is \(intensity)") perkSynesthesiaFireBackgroundBlinker(intensity: intensity) } catch { //there was an error, so speak it instead speak(subphrase: currentPhrase.subphrases![currentSubphraseIndex]) } /******************************************************/ /*******************///MARK: END PERK SYNESTHESIA MUSICALVOICES /******************************************************/ } var addThisColor: UIColor if let c = sendingButton!.backgroundColor { if c == UIColor.clear { addThisColor = UIColor.black } else { addThisColor = c } } else { addThisColor = UIColor.black } //check the orientation of the objectiveFeedbackView. If it is normal, add, if not, subtract the color if objectiveFeedbackView.orientationUp { //add the color of the button pressed to the color indicator objectiveFeedbackView.addColorToProgress(color: addThisColor) } else { //subtract the color of the button pressed to the color indicator objectiveFeedbackView.subtractColorToProgress(color: addThisColor) } /******************************************************/ /*******************///MARK: PERK INSIGHT VISUALIZECOLORVALUES /******************************************************/ //get the new color of the deviation part and set the sticks //if an increasedScore perk is active, add all bonuses and multiply that multiply the pointsJustScored let applicableVisualizeColroValuesPerks = getAllPerks(ofType: .visualizeColorValues, withStatus: .unlocked) if !applicableVisualizeColroValuesPerks.isEmpty { //calculate the percent of red, green, blue in the objective ring color // var colorRGBA = [CGFloat](repeating: 0.0, count: 4) let deviationColor = objectiveFeedbackView.calculateColorDeviation(color1: objectiveFeedbackView.objectiveRingColor, color2: objectiveFeedbackView.progressRingColor) let ciDeviationColor = CIColor(color: deviationColor) //.getRed(&colorRGBA[0], green: &colorRGBA[1], blue: &colorRGBA[2], alpha: &colorRGBA[3]) //check the level of the perk var highestPerkValue = 1 for perk in applicableVisualizeColroValuesPerks { let perkValue = perk.0.meta1 as! Int if perkValue > highestPerkValue { highestPerkValue = perkValue } } switch highestPerkValue { case 1: perkStickViewDeviation.drawSticks(redPercent: ciDeviationColor.red, greenPercent: ciDeviationColor.green, bluePercent: ciDeviationColor.blue, showColors: false) case 2: perkStickViewDeviation.drawSticks(redPercent: ciDeviationColor.red, greenPercent: ciDeviationColor.green, bluePercent: ciDeviationColor.blue) case 3: let deviation = CGFloat(calculateColorMatchPointsEarned().2) perkStickViewDeviation.drawSticks(redPercent: ciDeviationColor.red, greenPercent: ciDeviationColor.green, bluePercent: ciDeviationColor.blue, deviation: deviation) default: perkStickViewDeviation.drawSticks(redPercent: ciDeviationColor.red, greenPercent: ciDeviationColor.green, bluePercent: ciDeviationColor.blue, showColors: false) } } /******************************************************/ /*******************///MARK: END PERK INSIGHT VISUALIZECOLORVALUES /******************************************************/ //iterate the subphrase currentSubphraseIndex += 1 //reload another phrase if this was the last word if currentSubphraseIndex >= currentPhrase.subphrases!.count { currentSubphraseIndex = 0 //if the user doesn't ahve enough points to go after objectives, make the transition quicker var delay = 1000 if getCurrentScore() <= minimumScoreToUnlockObjective && objectiveFeedbackView.alpha < 1.0 { delay = 300 } var pointsJustScored = 0 //don't let the user do anything while we show them feedback and reload setAllUserInteraction(enabled: false) //if the user is working on an objective, give xp points if they met minimum score threshold for that level if objectiveFeedbackView.alpha > 0 { let scoreResults = calculateColorMatchPointsEarned() pointsJustScored = calculateBaseScore(phrase: currentPhrase) + scoreResults.0 /******************************************************/ /*******************///MARK: PERK PRECISIONADJUSTMENT /******************************************************/ //to adjust the precision, we give the player the benefit of a score that might not otherwise pass the threshold let applicablePrecisionAdjustmentPerks = getAllPerks(ofType: .precisionAdjustment, withStatus: .unlocked) var successThresholdPerkPrecisionAdjustmentModifier: Float = 0.0 if !applicablePrecisionAdjustmentPerks.isEmpty { //perks are unlocked. Add together the meta1s for perk in applicablePrecisionAdjustmentPerks { successThresholdPerkPrecisionAdjustmentModifier += Float(perk.0.meta1 as! Double) } } //in the checks in the next if statement, the modifier will be added. The modifier should be negative, which will reduce the score the player needs to achieve to pass //there should also be checks to give user feedback if they just got by the skin of their teeth /******************************************************/ /*******************///MARK: END PERK PRECISIONADJUSTMENT /******************************************************/ let level = getUserCurrentLevel() //compare to match performance if scoreResults.2 >= (level.successThreshold + successThresholdPerkPrecisionAdjustmentModifier) { /******************************************************/ /*******************///MARK: PERK PRECISIONADJUSTMENT /******************************************************/ //let the user know if they got by because of precision adjustment if scoreResults.2 < (level.successThreshold) { //user would have failed //fadeViewInThenOut(view: perkPrecisionAdjustmentUserFeedback, fadeOutAfterSeconds: 2) fadeViewInThenOut(view: perkPrecisionAdjustmentUserFeedbackImageView, fadeOutAfterSeconds: 2) } /******************************************************/ /*******************///MARK: END PERK PRECISIONADJUSTMENT /******************************************************/ /******************************************************/ /*******************///MARK: PERK INVESTMENT /******************************************************/ // //add to the points earned // var perkAddition = 0 // let applicablePerks = getAllPerks(ofType: .investment, withStatus: .unlocked) // // if !applicablePerks.isEmpty { // //there are perks // // for (perk, _) in applicablePerks { // //each perk adds to the reward // perkAddition += perk.meta1 as! Int // } // // //fire the perk feedback // fadeViewInThenOut(view: perkInvestmentScoreUserFeedback, fadeOutAfterSeconds: 1.8) // // pointsJustScored += perkAddition // // } /******************************************************/ /*******************///MARK: END PERK INVESTMENT /******************************************************/ /******************************************************/ /*******************///MARK: Perfect Score Bonus /******************************************************/ //if they got a perfect score, triple the points earned if scoreResults.2 == 1 { pointsJustScored = pointsJustScored * 3 } /******************************************************/ /*******************///MARK: PERK INCREASEDSCORE /******************************************************/ //if an increasedScore perk is active, add all bonuses and multiply that multiply the pointsJustScored let applicableIncreasedScorePerks = getAllPerks(ofType: .increasedScore, withStatus: .unlocked) if !applicableIncreasedScorePerks.isEmpty { var increasedScoreMultiplier = 0 for perk in applicableIncreasedScorePerks { //the multiplier is in meta1 increasedScoreMultiplier += perk.0.meta1 as! Int } pointsJustScored = pointsJustScored * increasedScoreMultiplier //just modified the score, so give user feedback perkIncreasedScoreUserFeedback.text = "\(increasedScoreMultiplier)X!" fadeViewInThenOut(view: perkIncreasedScoreUserFeedback, fadeOutAfterSeconds: 2) fadeViewInThenOut(view: perkIncreasedScoreUserFeedbackImageView, fadeOutAfterSeconds: 2) } /******************************************************/ /*******************///MARK: END PERK INCREASEDSCORE /******************************************************/ //check to see if an xp-related perk is active. ask the perk store /******************************************************/ /*******************///MARK: Perk Implimentation: increasedXP /******************************************************/ let applicablePerksAndUnlockedPerkObjects = getAllPerks(ofType: .increasedXP, withStatus: .unlocked) // let perkStore = self.storyboard!.instantiateViewController(withIdentifier: "PerkStore") as! PerkStoreCollectionViewController // let unlockedPerks = perkStore.getAllUnlockedPerks() // print("The following perks are unlocked: \(unlockedPerks)") // //go through all unlockable perks and get an array of all xp related ones // // let applicablePerkObjects: [Perk] = Perks.ValidPerks.filter{$0.type == PerkType.increasedXP} // // var foundUnlockedApplicablePerks = [Perk]() // // for perk in unlockedPerks { // //check to see if this perk.name is also in the applicable perks // for applicablePerk in applicablePerkObjects { // if perk.name == applicablePerk.name { // foundUnlockedApplicablePerks.append(applicablePerk) // } // } // } //now should have an array of perks that apply to this situation. //for now assume that if there are any just take the first one and apply it if applicablePerksAndUnlockedPerkObjects.isEmpty { //its empty so there are no applicable perks. Give the normal amount of XP. giveXP(level: level.level, score: pointsJustScored, successScore: scoreResults.2, time: 0, toggles: 0) } else { //there is a modifier. This is located in meta1 var mult = 1 //sum the value of all increasedXP perks for perk in applicablePerksAndUnlockedPerkObjects { if let multiplier = perk.0.meta1 as! Int? { mult += multiplier } } // award xp giveXP(value: 1 * mult, level: level.level, score: pointsJustScored, successScore: scoreResults.2, time: 0, toggles: 0) /******************************************************/ /*******************///MARK: PERK IncreasedXP /******************************************************/ //if the xp perk is active and they made positive progress, flash feedback fadeViewInThenOut(view: perkIncreasedXPUserFeedbackImageView, fadeOutAfterSeconds: 2) /******************************************************/ /*******************///MARK: END PERK INCREASEDXP /******************************************************/ } /******************************************************/ /*******************///MARK: END PERK INCREASEDXP /******************************************************/ //award points setCurrentScore(newScore: getCurrentScore() + pointsJustScored) if let scoreMessage = scoreResults.1 { presentJustScoredMessageFeedback(message: scoreMessage) } } else if scoreResults.2 <= (level.punishThreshold + successThresholdPerkPrecisionAdjustmentModifier) { //if the score was so low that use must lose XP //penalty points! //penalty is negative the amount you would have scored pointsJustScored = -1 * pointsJustScored //if they got a 0% score, triple the points lost if scoreResults.2 == 0 { pointsJustScored = pointsJustScored * 3 } setCurrentScore(newScore: getCurrentScore() + pointsJustScored) //only give negative XP if the sum of their XP is greater than zero. //This prevents them from going below level 1 //also, player's points (score) should be negative here. let playerXP = calculateUserXP() if playerXP > 0 { giveXP(value: -1, level: level.level, score: pointsJustScored, successScore: scoreResults.2, time: 0, toggles: 0) } //give them a message so they know how bad they did if let scoreMessage = scoreResults.1 { presentJustScoredMessageFeedback(message: scoreMessage, isGoodMessage: false) } } else { /******************************************************/ /*******************///MARK: PERK PRECISIONADJUSTMENT /******************************************************/ //let the user know if they got by because of precision adjustment if scoreResults.2 <= (level.punishThreshold) { //user would have failed //fadeViewInThenOut(view: perkPrecisionAdjustmentUserFeedback, fadeOutAfterSeconds: 2) fadeViewInThenOut(view: perkPrecisionAdjustmentUserFeedbackImageView, fadeOutAfterSeconds: 2) } /******************************************************/ /*******************///MARK: END PERK PRECISIONADJUSTMENT /******************************************************/ //no XP given here, but points still given /******************************************************/ /*******************///MARK: PERK INVESTMENT /******************************************************/ // //add to the points earned // var perkAddition = 0 // let applicablePerks = getAllPerks(ofType: .investment, withStatus: .unlocked) // // if !applicablePerks.isEmpty { // //there are perks // // for (perk, _) in applicablePerks { // //each perk adds to the reward // perkAddition += perk.meta1 as! Int // } // // //fire the perk feedback // fadeViewInThenOut(view: perkInvestmentScoreUserFeedback, fadeOutAfterSeconds: 1.8) // // pointsJustScored += perkAddition // // } /******************************************************/ /*******************///MARK: END PERK INVESTMENT /******************************************************/ /******************************************************/ /*******************///MARK: PERK INCREASEDSCORE /******************************************************/ //if an increasedScore perk is active, add all bonuses and multiply that multiply the pointsJustScored let applicableIncreasedScorePerks = getAllPerks(ofType: .increasedScore, withStatus: .unlocked) if !applicableIncreasedScorePerks.isEmpty { var increasedScoreMultiplier = 0 for perk in applicableIncreasedScorePerks { //the multiplier is in meta1 increasedScoreMultiplier += perk.0.meta1 as! Int } pointsJustScored = pointsJustScored * increasedScoreMultiplier //just modified the score, so give user feedback perkIncreasedScoreUserFeedback.text = "\(increasedScoreMultiplier)X!" fadeViewInThenOut(view: perkIncreasedScoreUserFeedback, fadeOutAfterSeconds: 2) fadeViewInThenOut(view: perkIncreasedScoreUserFeedbackImageView, fadeOutAfterSeconds: 2) } /******************************************************/ /*******************///MARK: END PERK INCREASEDSCORE /******************************************************/ //give an XP object of 0 to keep track of stats giveXP(value: 0, level: level.level, score: pointsJustScored, successScore: scoreResults.2, time: 0, toggles: 0) //award points setCurrentScore(newScore: getCurrentScore() + pointsJustScored) if let scoreMessage = scoreResults.1{ presentJustScoredMessageFeedback(message: scoreMessage) } } } else { //when not working on an objective, everyone is a winner! //give them some points for finishing a phrase pointsJustScored = calculateBaseScore(phrase: currentPhrase) /******************************************************/ /*******************///MARK: PERK INVESTMENT /******************************************************/ // //add to the points earned // var perkAddition = 0 // let applicablePerks = getAllPerks(ofType: .investment, withStatus: .unlocked) // // if !applicablePerks.isEmpty { // //there are perks // // for (perk, _) in applicablePerks { // //each perk adds to the reward // perkAddition += perk.meta1 as! Int // } // // //fire the perk feedback // fadeViewInThenOut(view: perkInvestmentScoreUserFeedback, fadeOutAfterSeconds: 1.8) // // pointsJustScored += perkAddition // // } /******************************************************/ /*******************///MARK: END PERK INVESTMENT /******************************************************/ setCurrentScore(newScore: getCurrentScore() + pointsJustScored) } //animate the justScored feedback presentJustScoredFeedback(justScored: pointsJustScored) //update the score refreshScore() //first check to see if player has won let userXP = calculateUserXP() let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP) let userCurrentProgress = userLevelAndProgress.1 let didPlayerProgressToGetHere = didPlayer(magnitudeDirection: .increase, in: .progress, byAchieving: userCurrentProgress) if isPlayerAtHighestLevelAndProgress() && didPlayerProgressToGetHere { //player has won so show the final sequence DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay * 2), execute: { self.showWinningSequence() }) } DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay), execute: { self.reloadGame() }) } } /******************************************************/ /*******************///MARK: Scoring /******************************************************/ ///updates the UI with the current score. Also controls alphas of the store buttons func refreshScore() { let currentScore = getCurrentScore() let newAlpha: CGFloat = CGFloat(Float(currentScore) / Float(minimumScoreToUnlockStore + 500)) var scoreAlpha = newAlpha //set the alpha of the label to be the equivalent of the score /1000 //alpha of the store icon will be such that 500 is the minimum score to start showing. Lowest priced item will be 500. if currentScore >= minimumScoreToUnlockStore + 500 { scoreAlpha = 1.0 //scoreLabel.alpha = scoreAlpha self.storeButton.fade(.inOrOut, resultAlpha: 1.0, withDuration: 0.3, delay: 0.6) } else if currentScore <= minimumScoreToUnlockObjective { //before the player can use objectives, the alpha of the store button is controled by the player's score let storeAlpha = 2*newAlpha - 1 //this makes store button visible at 500 and solid at 1000. y=mx+b //fade in or out the store //this should auto disable if it goes to 0, and vice versa self.storeButton.fade(.inOrOut, resultAlpha: storeAlpha, withDuration: 0.3, delay: 0.6) } //fade out and in the score self.scoreLabel.fade(.out, withDuration: 0.2, completion: { (finished:Bool) in //set score self.scoreLabel.text = String(describing: currentScore.formattedWithSeparator) self.scoreLabel.fade(.inOrOut, resultAlpha: scoreAlpha, withDuration: 0.3) }) //fading in and out the map. based on user's level let userLevel = getUserCurrentLevel() //map will fade in over 2 levels if currentScore <= minimumScoreToUnlockObjective { //don't show map if score is below minimum for objective //fade to zero //fade in the perk store self.mapButton.fade(.out, withDuration: 0.3, delay: 0.6) } else if userLevel.level >= Levels.ReturnToDarknessLevelFirst.level && userLevel.level <= Levels.ReturnToDarknessLevelLast.level { //user is in the return to darkness phase of the game, so don't show the map because they are losing their way let newAlpha:CGFloat = 0.0 self.mapButton.fade(.inOrOut, resultAlpha: newAlpha, withDuration: 0.3, delay: 0.6) } else if userLevel.level >= (minimumLevelToUnlockMap + 5) { let newAlpha:CGFloat = 1.0 self.mapButton.fade(.inOrOut, resultAlpha: newAlpha, withDuration: 0.3, delay: 0.6) } else if userLevel.level >= minimumLevelToUnlockMap && userLevel.level <= (minimumLevelToUnlockMap + 5) { //slowly introduce the map over 5 levels. Above this the function loadAndFadeInFeedbackObjective manages the perk store let newAlpha: CGFloat = CGFloat(Float(userLevel.level) / Float(userLevel.level + 5)) //fade in the map //this should automatically disable if it fades to 0 or enable if it is > 0 self.mapButton.fade(.inOrOut, resultAlpha: newAlpha, withDuration: 0.3, delay: 0.6) } else { //user is below the map button reveal self.mapButton.fade(.out, withDuration: 0.3, delay: 0.6) } //score housekeeping. //if the score is below the thresholds where the user would see an objective, make sure the timer penalty is low enough to allow them to recover. But once it is high enough, increase the penalty to make it more challenging once objectives are in play. //if the score is below the objective if getCurrentScore() < minimumScoreToUnlockObjective / 2 { //set the penalty lower pointsToLoseEachCycle = 10 } else if getCurrentScore() < minimumScoreToUnlockObjective { pointsToLoseEachCycle = 20 } else if getCurrentScore() < minimumScoreToUnlockObjective * 2 { pointsToLoseEachCycle = 30 } else if getCurrentScore() < minimumScoreToUnlockObjective * 6 { pointsToLoseEachCycle = 35 } else { //the player has found stride, and has good opportunities to earn points, so penalize taking too much time pointsToLoseEachCycle = 50 } } ///a fader for /// calculates the base score, which is 100 - the liklihood of the phrase just completed func calculateBaseScore(phrase: Phrase) -> Int { let baseReward = (100 - phrase.likelihood) * 8 // var perkAddition = 0 // /******************************************************/ // /*******************///MARK: PERK INVESTMENT // /******************************************************/ // let applicablePerks = getAllPerks(ofType: .investment, withStatus: .unlocked) // // if !applicablePerks.isEmpty { // //there are perks // // for (perk, _) in applicablePerks { // //each perk adds to the reward // perkAddition += perk.meta1 as! Int // } // // //fire the perk feedback // fadeViewInThenOut(view: perkInvestmentScoreUserFeedback, fadeOutAfterSeconds: 1.8) // // return baseReward + perkAddition // // } else { return baseReward //} /******************************************************/ /*******************///MARK: END PERK INVESTMENT /******************************************************/ } ///calculates the points earned from a given color, a color which represents the deviation between the goal and the progress func calculateColorMatchPointsEarned() -> (Int, String?, Float) { //really this is just the main color, but just in case that changes this way is more solid let deviationColor = objectiveFeedbackView.calculateColorDeviation(color1: objectiveFeedbackView.objectiveRingColor, color2: objectiveFeedbackView.progressRingColor) let magnitude: CGFloat = 22.0 // var deviationRGBA = [CGFloat](repeating: 0.0, count: 4) // // deviationColor.getRed(&deviationRGBA[0], green: &deviationRGBA[1], blue: &deviationRGBA[2], alpha: &deviationRGBA[3]) let ciDeviationColor = CIColor(color: deviationColor) //for each component of the ciDeviationColor, round to the nearest 0.00. This because there has been a lot of ugly math and conversions that whack the numbers out such that a perfect match let roundedCiRed = ciDeviationColor.red.rounded(toNearest: 0.01) let roundedCiGreen = ciDeviationColor.green.rounded(toNearest: 0.01) let roundedCiBlue = ciDeviationColor.blue.rounded(toNearest: 0.01) let redRaw = Int(magnitude - (roundedCiRed * magnitude)) let greenRaw = Int(magnitude - (roundedCiGreen * magnitude)) let blueRaw = Int(magnitude - (roundedCiBlue * magnitude)) let unadjustedScore = redRaw + greenRaw + blueRaw let multiplier: CGFloat = 4.0 var scoreToAward = CGFloat(unadjustedScore) * multiplier //ensure raw scores can't be negative if scoreToAward < 0 { scoreToAward = 0 } print("Awarding \(scoreToAward) points for matching") let maxScore = magnitude * 3.0 * multiplier var pointMessage: String? = nil //TODO: figure out how to make the insight level 3 perk match this string. let scorePercent = Int(scoreToAward/maxScore*100.0) //String(describing: "\(Int(deviation * 100))") this is what Insight 3 uses, using the .3 result from this return switch scorePercent { case 100: pointMessage = "perfect!" case let x where x >= 90: pointMessage = "\(scorePercent)% superb!" case let x where x >= 80: pointMessage = "\(scorePercent)% great!" default: pointMessage = "\(scorePercent)% match" } //give bonus for player's level let playerLevel = getUserCurrentLevel().level let levelAdjustedScoreToAward = scoreToAward + CGFloat(playerLevel * 4) return (Int(levelAdjustedScoreToAward), pointMessage, Float(Float(scorePercent)/100.0)) } /******************************************************/ /*******************///MARK: Core Data functions /******************************************************/ /** get the current score, if there is not a score record, make one at 0 */ func getCurrentScore() -> Int { guard let fc = frcDict[keyCurrentScore] else { return -1 } guard let currentScores = fc.fetchedObjects as? [CurrentScore] else { return -1 } if (currentScores.count) == 0 { print("No CurrentScore exists. Creating.") let newScore = CurrentScore(entity: NSEntityDescription.entity(forEntityName: "CurrentScore", in: stack.context)!, insertInto: fc.managedObjectContext) stack.save() return Int(newScore.value) } else { //print(currentScores[0].value) let score = Int(currentScores[0].value) //if didn't find at end of loop, must not be an entry, so level 0 return score } } /// sets the current score, returns the newly set score func setCurrentScore(newScore: Int) { guard let fc = frcDict[keyCurrentScore] else { fatalError("Could not get frcDict") } guard let currentScores = fc.fetchedObjects as? [CurrentScore] else { fatalError("Could not get array of currentScores") } if (currentScores.count) == 0 { print("No CurrentScore exists. Creating.") let currentScore = CurrentScore(entity: NSEntityDescription.entity(forEntityName: "CurrentScore", in: stack.context)!, insertInto: fc.managedObjectContext) currentScore.value = Int64(newScore) stack.save() return } else { switch newScore { //TODO: if the score is already 0 don't set it again. case let x where x < 0: currentScores[0].value = Int64(0) return default: //set score for the first element currentScores[0].value = Int64(newScore) //print("There are \(currentScores.count) score entries in the database.") return } } } /******************************************************/ /*******************///MARK: Timer /******************************************************/ @objc func updateTimer() { //reduce the score reduceScoreByPeriodicValue() } func reduceScoreByPeriodicValue() { let currentScore = getCurrentScore() if currentScore >= 0 { let penalty = pointsToLoseEachCycle var newScore = currentScore - penalty if newScore < 0 { newScore = 0 } if !(newScore == 0 && currentScore == 0) { setCurrentScore(newScore: newScore) refreshScore() } } } /******************************************************/ /*******************///MARK: Store Buttons /******************************************************/ //simple and quick way to fade someting in then back out after a given time in secods func fadeViewInThenOut(view: UIView, fadeOutAfterSeconds: TimeInterval) { //fade in view.fade(.in) let seconds = Int(fadeOutAfterSeconds) let milliseconds = Int((fadeOutAfterSeconds - Double(seconds)) * 1000) //fade out let deadline = DispatchTime.now() + DispatchTimeInterval.seconds(seconds) + DispatchTimeInterval.milliseconds(milliseconds) DispatchQueue.main.asyncAfter(deadline: deadline, execute: { view.fade(.out, delay: 0) }) } }
apache-2.0
60db2123d9c4bd2489399c690a4e9adf
45.917808
260
0.458916
5.897909
false
false
false
false
MateuszKarwat/Napi
NapiTests/TokenTests.swift
1
1015
// // Created by Mateusz Karwat on 08/07/16. // Copyright © 2016 Mateusz Karwat. All rights reserved. // import XCTest @testable import Napi class TokenTests: XCTestCase { enum TestingToken: String { case normal } func testEmptyValues() { let regex = try! NSRegularExpression(pattern: "TEST", options: []) let token = Token(type: TestingToken.normal, lexeme: "TEST", pattern: regex) XCTAssertTrue(token.values.isEmpty, "There should be no extra values") } func testOneValue() { let regex = try! NSRegularExpression(pattern: "T(ES)T", options: []) let token = Token(type: TestingToken.normal, lexeme: "TEST", pattern: regex) XCTAssertEqual(["ES"], token.values) } func testMultipleValues() { let regex = try! NSRegularExpression(pattern: "(TE)(ST)", options: []) let token = Token(type: TestingToken.normal, lexeme: "TEST", pattern: regex) XCTAssertEqual(["TE", "ST"], token.values) } }
mit
cc6c6e008caabfc97c63f70b3f8bec0f
27.166667
84
0.636095
4.121951
false
true
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Extensions/Colors.swift
1
858
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation // TODO: Colors should be declared in PlatformUIKit.UIColor+Application.swift @objc extension UIColor { // MARK: - Brand-specific Colors static let brandPrimary = #colorLiteral(red: 0, green: 0.2901960784, blue: 0.4862745098, alpha: 1) static let darkGray = #colorLiteral(red: 0.26, green: 0.26, blue: 0.26, alpha: 1) static let green = #colorLiteral(red: 0, green: 0.6549019608, blue: 0.4352941176, alpha: 1) static let red = #colorLiteral(red: 0.9490196078, green: 0.4235294118, blue: 0.3411764706, alpha: 1) // MARK: - App-specific Colors static let lightGray = #colorLiteral(red: 0.9607843137, green: 0.9647058824, blue: 0.9725490196, alpha: 1) static let navigationBarBackground = UIColor.NavigationBar.LightContent.background }
lgpl-3.0
c6cd60e16ab509bb6df9163ec151af05
34.708333
110
0.722287
3.585774
false
false
false
false
AnthonyMDev/AmazonS3RequestManager
Source/AmazonS3RequestSerializer.swift
1
10735
// // AmazonS3RequestSerializer.swift // AmazonS3RequestManager // // Created by Anthony Miller on 10/14/15. // Copyright © 2015 Anthony Miller. All rights reserved. // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif import Alamofire /** MARK: - AmazonS3RequestSerializer `AmazonS3RequestSerializer` serializes `NSURLRequest` objects for requests to the Amazon S3 service */ open class AmazonS3RequestSerializer { // MARK: - Instance Properties /** The Amazon S3 Bucket for the client */ open var bucket: String? /** The Amazon S3 region for the client. `AmazonS3Region.USStandard` by default. :note: Must not be `nil`. :see: `AmazonS3Region` for defined regions. */ open var region: Region = .USStandard /** The Amazon S3 Access Key ID used to generate authorization headers and pre-signed queries :dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key */ open var accessKey: String /** The Amazon S3 Secret used to generate authorization headers and pre-signed queries :dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key */ open var secret: String /** Whether to connect over HTTPS. `true` by default. */ open var useSSL: Bool = true /** The AWS STS session token. `nil` by default. */ open var sessionToken: String? // MARK: - Initialization /** Initalizes an `AmazonS3RequestSerializer` with the given Amazon S3 credentials. - parameter bucket: The Amazon S3 bucket for the client - parameter region: The Amazon S3 region for the client - parameter accessKey: The Amazon S3 access key ID for the client - parameter secret: The Amazon S3 secret for the client - returns: An `AmazonS3RequestSerializer` with the given Amazon S3 credentials */ public init(accessKey: String, secret: String, region: Region, bucket: String? = nil) { self.accessKey = accessKey self.secret = secret self.region = region self.bucket = bucket } /** MARK: - Amazon S3 Request Serialization This method serializes a request for the Amazon S3 service with the given method and path. :discussion: The `URLRequest`s returned from this method may be used with `Alamofire`, `NSURLSession` or any other network request manager. - Parameters: - method: The HTTP method for the request. For more information see `Alamofire.Method`. - path: The desired path, including the file name and extension, in the Amazon S3 Bucket. - subresource: The subresource to be added to the request's query. A subresource can be used to access options or properties of a resource. - acl: The optional access control list to set the acl headers for the request. For more information see `ACL`. - metaData: An optional dictionary of meta data that should be assigned to the object to be uploaded. - storageClass: The optional storage class to use for the object to upload. If none is specified, standard is used. For more information see `StorageClass`. - customParameters: An optional dictionary of custom parameters to be added to the url's query string. - returns: A `URLRequest`, serialized for use with the Amazon S3 service. */ open func amazonURLRequest(method: HTTPMethod, path: String? = nil, subresource: String? = nil, acl: ACL? = nil, metaData:[String : String]? = nil, storageClass: StorageClass = .standard, customParameters: [String : String]? = nil, customHeaders: [String : String]? = nil) -> URLRequest { let url = self.url(withPath: path, subresource: subresource, customParameters: customParameters) var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue setContentType(on: &urlRequest) acl?.setACLHeaders(on: &urlRequest) setStorageClassHeaders(storageClass, on: &urlRequest) setMetaDataHeaders(metaData, on: &urlRequest) setCustomHeaders(customHeaders, on: &urlRequest) setAuthorizationHeaders(on: &urlRequest) return urlRequest as URLRequest } /// This method returns the `URL` for the given path. /// /// - Note: This method only returns an unsigned `URL`. If the object at the generated `URL` requires authentication to access, the `amazonURLRequest(method:, path:)` function above should be used to create a signed `URLRequest`. /// /// - Parameters: /// - path: The desired path, including the file name and extension, in the Amazon S3 Bucket. /// - subresource: The subresource to be added to the url's query. A subresource can be used to access /// options or properties of a resource. /// - customParameters: An optional dictionary of custom parameters to be added to the url's query string. /// /// - Returns: A `URL` to access the given path on the Amazon S3 service. open func url(withPath path: String?, subresource: String? = nil, customParameters:[String : String]? = nil) -> URL { var url = endpointURL if let path = path { url = url.appendingPathComponent(path) } if let subresource = subresource { url = url.URLByAppendingS3Subresource(subresource) } if let customParameters = customParameters { for (key, value) in customParameters { url = url.URLByAppendingRequestParameter(key, value: value) } } return url } /** A readonly endpoint URL created for the specified bucket, region, and SSL use preference. `AmazonS3RequestManager` uses this as the baseURL for all requests. */ open var endpointURL: URL { var URLString = "" let scheme = self.useSSL ? "https" : "http" if bucket != nil { URLString = "\(scheme)://\(region.endpoint)/\(bucket!)" } else { URLString = "\(scheme)://\(region.endpoint)" } return URL(string: URLString)! } fileprivate func setContentType(on request: inout URLRequest) { let contentTypeString = MIMEType(for: request as URLRequest) ?? "application/octet-stream" request.setValue(contentTypeString, forHTTPHeaderField: "Content-Type") } fileprivate func MIMEType(for request: URLRequest) -> String? { if let fileExtension = request.url?.pathExtension , !fileExtension.isEmpty, let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil), let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTIRef.takeUnretainedValue(), kUTTagClassMIMEType) { UTIRef.release() let MIMEType = MIMETypeRef.takeUnretainedValue() MIMETypeRef.release() return MIMEType as String } return nil } fileprivate func setAuthorizationHeaders(on request: inout URLRequest) { request.cachePolicy = .reloadIgnoringLocalCacheData if sessionToken != nil { request.setValue(sessionToken!, forHTTPHeaderField: "x-amz-security-token") } let timestamp = currentTimeStamp() let signature = AmazonS3SignatureHelpers.awsSignature(for: request, timeStamp: timestamp, secret: secret) request.setValue(timestamp, forHTTPHeaderField: "Date") request.setValue("AWS \(accessKey):\(signature)", forHTTPHeaderField: "Authorization") } fileprivate func setStorageClassHeaders(_ storageClass: StorageClass, on request: inout URLRequest) { request.setValue(storageClass.rawValue, forHTTPHeaderField: "x-amz-storage-class") } fileprivate func setMetaDataHeaders(_ metaData:[String : String]?, on request: inout URLRequest) { guard let metaData = metaData else { return } var metadataHeaders:[String:String] = [:] for (key, value) in metaData { metadataHeaders["x-amz-meta-" + key] = value } setCustomHeaders(metadataHeaders, on: &request) } fileprivate func setCustomHeaders(_ headerFields:[String : String]?, on request: inout URLRequest) { guard let headerFields = headerFields else { return } for (key, value) in headerFields { request.setValue(value, forHTTPHeaderField: key) } } fileprivate func currentTimeStamp() -> String { return requestDateFormatter.string(from: Date()) } fileprivate lazy var requestDateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: "GMT") dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" dateFormatter.locale = Locale(identifier: "en_US_POSIX") return dateFormatter }() } private extension URL { func URLByAppendingS3Subresource(_ subresource: String) -> URL { if !subresource.isEmpty { let URLString = self.absoluteString + "?\(subresource)" return URL(string: URLString)! } return self } func URLByAppendingRequestParameter(_ key: String, value: String) -> URL { if key.isEmpty || value.isEmpty { return self } guard let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { return self } var URLString = self.absoluteString URLString = URLString + (URLString.range(of: "?") == nil ? "?" : "&") + key + "=" + encodedValue return URL(string: URLString)! } }
mit
1e4f2dc96da9c79dedcc47cb822539db
37.06383
233
0.613564
5.130975
false
false
false
false
janslow/qlab-from-csv
QLab From CSV/QLabFromCsv/RowParser.swift
1
4122
// // parser.swift // QLab From CSV // // Created by Jay Anslow on 20/12/2014. // Copyright (c) 2014 Jay Anslow. All rights reserved. // import Foundation class RowParser { func load(rows : [Dictionary<String, String>]) -> [Cue] { // Set up categories of sub-cues and the closures to create the sub-cues. let subCueCategories : Dictionary<String, ([String], Float) -> Cue> = [ "LX" : { (parts : [String], preWait : Float) -> Cue in var i = 0 let cue = LxGoCue(lxNumber: parts[i++], preWait: preWait) if i < parts.count && parts[i].hasPrefix("L") { let cueListString = parts[i++] cue.lxCueList = Int((cueListString.substringFromIndex(advance(cueListString.startIndex, 1)) as NSString).intValue) } return cue }, "Sound" : { (parts : [String], preWait : Float) -> Cue in return StartCue(targetNumber: "S" + parts[0], preWait: preWait) }, "Video" : { (parts : [String], preWait : Float) -> Cue in return StartCue(targetNumber: "V" + parts[0], preWait: preWait) } ] // Create a GroupCue from each row. var cues : [GroupCue] = rows.map({ (row : Dictionary<String, String>) -> GroupCue? in return self.convertRowToCue(row, subCueCategories: subCueCategories); }) .filter({ $0 != nil }) .map({ $0! }) // Sort the cues by cue number. return cues.map({ $0 as Cue }) } func convertRowToCue(row : Dictionary<String, String>, subCueCategories : Dictionary<String, ([String], Float) -> Cue>) -> GroupCue? { // Each row must have a QLab value. let cueNumber = row["QLab"] if cueNumber == nil { log.error("Row Parser: Cue must have a QLab number") log.debug("\(row)") return nil } // Comment and Page values are optional. let comment = row["Comment"] let page = row["Page"] // Create all the child cues by creating cues for each category. var children : [Cue] = [] for (categoryName, categoryCueCreator) in subCueCategories { // If there is a sub-cue value for the specified category, create the cues for that type. if let subCueString = row[categoryName] { children += createSubCues(subCueString, cueCreator: categoryCueCreator) } } // Construct and return the GroupCue return GroupCue(cueNumber: cueNumber!, comment: comment, page: page, children: children) } func createSubCues(cueString : String, cueCreator : ([String], Float) -> Cue) -> [Cue] { // Split the sub-cue string by commas. var cueStrings: [String] = cueString.componentsSeparatedByString(",") // For each sub-cue string... var cues : [Cue] = cueStrings.map({ // ...Trim the whitespace... $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }).filter({ // ...Ignore any empty strings... !$0.isEmpty }).map({ (s : String) -> Cue in // ...Split the string into parts... var parts : [String] = s.componentsSeparatedByString("/") // ...Extract the pre-wait time... var preWait : Float = 0.0 if parts.count > 1 { let preWaitString = parts[parts.count - 1] if preWaitString.hasPrefix("d") { preWait = (preWaitString.substringFromIndex(advance(preWaitString.startIndex, 1)) as NSString).floatValue parts = Array(parts[0...parts.count - 2]) } } // ...Create and return the cue. return cueCreator(parts, preWait) }) return cues } }
mit
18d7665182ddfa2683239bc16d756516
41.947917
138
0.527171
4.352693
false
false
false
false
naokits/bluemix-swift-demo-ios
Pods/BMSAnalytics/Source/Logger/BMSLogger.swift
1
25501
/* *     Copyright 2016 IBM Corp. *     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 BMSCore // Send methods public extension Logger { internal static var currentlySendingLoggerLogs = false internal static var currentlySendingAnalyticsLogs = false /** Send the accumulated logs to the Bluemix server. Logger logs can only be sent if the BMSClient was initialized via the `initializeWithBluemixAppRoute()` method. - parameter completionHandler: Optional callback containing the results of the send request */ public static func send(completionHandler userCallback: BmsCompletionHandler? = nil) { guard !currentlySendingLoggerLogs else { BMSLogger.internalLogger.info("Ignoring Logger.send() until the previous send request finishes.") return } currentlySendingLoggerLogs = true let logSendCallback: BmsCompletionHandler = { (response: Response?, error: NSError?) in currentlySendingLoggerLogs = false if error == nil && response?.statusCode == 201 { BMSLogger.internalLogger.debug("Client logs successfully sent to the server.") BMSLogger.deleteFile(Constants.File.Logger.outboundLogs) // Remove the uncaught exception flag since the logs containing the exception(s) have just been sent to the server NSUserDefaults.standardUserDefaults().setBool(false, forKey: Constants.uncaughtException) } else { BMSLogger.internalLogger.error("Request to send client logs has failed.") } userCallback?(response, error) } // Use a serial queue to ensure that the same logs do not get sent more than once dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { () -> Void in do { // Gather the logs and put them in a JSON object let logsToSend: String? = try BMSLogger.getLogs(fileName: Constants.File.Logger.logs, overflowFileName: Constants.File.Logger.overflowLogs, bufferFileName: Constants.File.Logger.outboundLogs) var logPayloadData = try NSJSONSerialization.dataWithJSONObject([], options: []) if let logPayload = logsToSend { let logPayloadJson = [Constants.outboundLogPayload: logPayload] logPayloadData = try NSJSONSerialization.dataWithJSONObject(logPayloadJson, options: []) } else { BMSLogger.internalLogger.info("There are no logs to send.") } // Send the request, even if there are no logs to send (to keep track of device info) if let request: BaseRequest = BMSLogger.buildLogSendRequest(logSendCallback) { request.sendData(logPayloadData, completionHandler: logSendCallback) } } catch let error as NSError { logSendCallback(nil, error) } } } // Same as the other send() method but for analytics internal static func sendAnalytics(completionHandler userCallback: BmsCompletionHandler? = nil) { guard !currentlySendingAnalyticsLogs else { Analytics.logger.info("Ignoring Analytics.send() until the previous send request finishes.") return } currentlySendingAnalyticsLogs = true // Internal completion handler - wraps around the user supplied completion handler (if supplied) let analyticsSendCallback: BmsCompletionHandler = { (response: Response?, error: NSError?) in currentlySendingAnalyticsLogs = false if error == nil && response?.statusCode == 201 { Analytics.logger.debug("Analytics data successfully sent to the server.") BMSLogger.deleteFile(Constants.File.Analytics.outboundLogs) } else { Analytics.logger.error("Request to send analytics data to the server has failed.") } userCallback?(response, error) } // Use a serial queue to ensure that the same analytics data do not get sent more than once dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { () -> Void in do { // Gather the logs and put them in a JSON object let logsToSend: String? = try BMSLogger.getLogs(fileName: Constants.File.Analytics.logs, overflowFileName: Constants.File.Analytics.overflowLogs, bufferFileName: Constants.File.Analytics.outboundLogs) var logPayloadData = try NSJSONSerialization.dataWithJSONObject([], options: []) if let logPayload = logsToSend { let logPayloadJson = [Constants.outboundLogPayload: logPayload] logPayloadData = try NSJSONSerialization.dataWithJSONObject(logPayloadJson, options: []) } else { Analytics.logger.info("There are no analytics data to send.") } // Send the request, even if there are no logs to send (to keep track of device info) if let request: BaseRequest = BMSLogger.buildLogSendRequest(analyticsSendCallback) { request.sendData(logPayloadData, completionHandler: analyticsSendCallback) } } catch let error as NSError { analyticsSendCallback(nil, error) } } } } // MARK: - /** `BMSLogger` provides the internal implementation of the BMSAnalyticsSpec `Logger` API. */ public class BMSLogger: LoggerDelegate { // MARK: Properties (internal) // Internal instrumentation for troubleshooting issues in BMSCore internal static let internalLogger = Logger.logger(forName: Constants.Package.logger) // MARK: Class constants (internal) // By default, the dateFormater will convert to the local time zone, but we want to send the date based on UTC // so that logs from all clients in all timezones are normalized to the same GMT timezone. internal static let dateFormatter: NSDateFormatter = BMSLogger.generateDateFormatter() private static func generateDateFormatter() -> NSDateFormatter { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone(name: "GMT") formatter.dateFormat = "dd-MM-yyyy HH:mm:ss:SSS" return formatter } // Path to the log files on the client device internal static let logsDocumentPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] + "/" internal static let fileManager = NSFileManager.defaultManager() // MARK: - Uncaught exceptions /// True if the app crashed recently due to an uncaught exception. /// This property will be set back to `false` if the logs are sent to the server. public var isUncaughtExceptionDetected: Bool { get { return NSUserDefaults.standardUserDefaults().boolForKey(Constants.uncaughtException) } set { NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: Constants.uncaughtException) } } // If the user set their own uncaught exception handler earlier, it gets stored here internal static let existingUncaughtExceptionHandler = NSGetUncaughtExceptionHandler() // This flag prevents infinite loops of uncaught exceptions internal static var exceptionHasBeenCalled = false internal static func startCapturingUncaughtExceptions() { NSSetUncaughtExceptionHandler { (caughtException: NSException) -> Void in if (!BMSLogger.exceptionHasBeenCalled) { // Persist a flag so that when the app starts back up, we can see if an exception occurred in the last session BMSLogger.exceptionHasBeenCalled = true BMSLogger.logException(caughtException) BMSAnalytics.logSessionEnd() BMSLogger.existingUncaughtExceptionHandler?(caughtException) } } } internal static func logException(exception: NSException) { let logger = Logger.logger(forName: Constants.Package.logger) var exceptionString = "Uncaught Exception: \(exception.name)." if let reason = exception.reason { exceptionString += " Reason: \(reason)." } logger.fatal(exceptionString) } // MARK: - Writing logs to file // We use serial queues to prevent race conditions when multiple threads try to read/modify the same file internal static let loggerFileIOQueue: dispatch_queue_t = dispatch_queue_create("com.ibm.mobilefirstplatform.clientsdk.swift.BMSCore.Logger.loggerFileIOQueue", DISPATCH_QUEUE_SERIAL) internal static let analyticsFileIOQueue: dispatch_queue_t = dispatch_queue_create("com.ibm.mobilefirstplatform.clientsdk.swift.BMSCore.Logger.analyticsFileIOQueue", DISPATCH_QUEUE_SERIAL) // This is the master function that handles all of the logging, including level checking, printing to console, and writing to file // All other log functions below this one are helpers for this function public func logMessageToFile(message: String, level: LogLevel, loggerName: String, calledFile: String, calledFunction: String, calledLineNumber: Int, additionalMetadata: [String: AnyObject]? = nil) { let group :dispatch_group_t = dispatch_group_create() // Writing to file if level == LogLevel.Analytics { guard Analytics.enabled else { return } } else { guard Logger.logStoreEnabled else { return } } // Get file names and the dispatch queue needed to access those files let (logFile, logOverflowFile, fileDispatchQueue) = BMSLogger.getFilesForLogLevel(level) dispatch_group_async(group, fileDispatchQueue) { () -> Void in // Check if the log file is larger than the maxLogStoreSize. If so, move the log file to the "overflow" file, and start logging to a new log file. If an overflow file already exists, those logs get overwritten. if BMSLogger.fileLogIsFull(logFile) { do { try BMSLogger.moveOldLogsToOverflowFile(logFile, overflowFile: logOverflowFile) } catch let error { let logFileName = BMSLogger.extractFileNameFromPath(logFile) print("Log file \(logFileName) is full but the old logs could not be removed. Try sending the logs. Error: \(error)") return } } let timeStampString = BMSLogger.dateFormatter.stringFromDate(NSDate()) var logAsJsonString = BMSLogger.convertLogToJson(message, level: level, loggerName: loggerName, timeStamp: timeStampString, additionalMetadata: additionalMetadata) guard logAsJsonString != nil else { let errorMessage = "Failed to write logs to file. This is likely because the analytics metadata could not be parsed." Logger.printLogToConsole(errorMessage, loggerName:loggerName, level: .Error, calledFunction: __FUNCTION__, calledFile: __FILE__, calledLineNumber: __LINE__) return } logAsJsonString! += "," // Logs must be comma-separated BMSLogger.writeToFile(logFile, logMessage: logAsJsonString!, loggerName: loggerName) } // The wait is necessary to prevent race conditions - Only one operation can occur on this queue at a time dispatch_group_wait(group, DISPATCH_TIME_FOREVER) } // Get the full path to the log file and overflow file, and get the dispatch queue that they need to be operated on. internal static func getFilesForLogLevel(level: LogLevel) -> (String, String, dispatch_queue_t) { var logFile: String = BMSLogger.logsDocumentPath var logOverflowFile: String = BMSLogger.logsDocumentPath var fileDispatchQueue: dispatch_queue_t if level == LogLevel.Analytics { logFile += Constants.File.Analytics.logs logOverflowFile += Constants.File.Analytics.overflowLogs fileDispatchQueue = BMSLogger.analyticsFileIOQueue } else { logFile += Constants.File.Logger.logs logOverflowFile += Constants.File.Logger.overflowLogs fileDispatchQueue = BMSLogger.loggerFileIOQueue } return (logFile, logOverflowFile, fileDispatchQueue) } // Check if the log file size exceeds the limit set by the Logger.maxLogStoreSize property // Logs are actually distributed evenly between a "normal" log file and an "overflow" file, but we only care if the "normal" log file is full (half of the total maxLogStoreSize) internal static func fileLogIsFull(logFileName: String) -> Bool { if (BMSLogger.fileManager.fileExistsAtPath(logFileName)) { do { let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(logFileName) if let currentLogFileSize = attr?.fileSize() { return currentLogFileSize > Logger.maxLogStoreSize / 2 // Divide by 2 since the total log storage gets shared between the log file and the overflow file } } catch let error { let logFile = BMSLogger.extractFileNameFromPath(logFileName) print("Cannot determine the size of file:\(logFile) due to error: \(error). In case the file size is greater than the specified max log storage size, logs will not be written to file.") } } return false } // When the log file is full, the old logs are moved to the overflow file to make room for new logs internal static func moveOldLogsToOverflowFile(logFile: String, overflowFile: String) throws { if BMSLogger.fileManager.fileExistsAtPath(overflowFile) && BMSLogger.fileManager.isDeletableFileAtPath(overflowFile) { try BMSLogger.fileManager.removeItemAtPath(overflowFile) } try BMSLogger.fileManager.moveItemAtPath(logFile, toPath: overflowFile) } // Convert log message and metadata into JSON format. This is the actual string that gets written to the log files. internal static func convertLogToJson(logMessage: String, level: LogLevel, loggerName: String, timeStamp: String, additionalMetadata: [String: AnyObject]?) -> String? { var logMetadata: [String: AnyObject] = [:] logMetadata[Constants.Metadata.Logger.timestamp] = timeStamp logMetadata[Constants.Metadata.Logger.level] = level.stringValue logMetadata[Constants.Metadata.Logger.package] = loggerName logMetadata[Constants.Metadata.Logger.message] = logMessage if additionalMetadata != nil { logMetadata[Constants.Metadata.Logger.metadata] = additionalMetadata! // Typically only available if the Logger.analytics method was called } let logData: NSData do { logData = try NSJSONSerialization.dataWithJSONObject(logMetadata, options: []) } catch { return nil } return String(data: logData, encoding: NSUTF8StringEncoding) } // Append log message to the end of the log file internal static func writeToFile(file: String, logMessage: String, loggerName: String) { if !BMSLogger.fileManager.fileExistsAtPath(file) { BMSLogger.fileManager.createFileAtPath(file, contents: nil, attributes: nil) } let fileHandle = NSFileHandle(forWritingAtPath: file) let data = logMessage.dataUsingEncoding(NSUTF8StringEncoding) if fileHandle != nil && data != nil { fileHandle!.seekToEndOfFile() fileHandle!.writeData(data!) fileHandle!.closeFile() } else { let errorMessage = "Cannot write to file: \(file)." Logger.printLogToConsole(errorMessage, loggerName: loggerName, level: LogLevel.Error, calledFunction: __FUNCTION__, calledFile: __FILE__, calledLineNumber: __LINE__) } } // When logging messages to the user, make sure to only mention the log file name, not the full path since it may contain sensitive data unique to the device. internal static func extractFileNameFromPath(filePath: String) -> String { var logFileName = Constants.File.unknown let logFileNameRange = filePath.rangeOfString("/", options:NSStringCompareOptions.BackwardsSearch) if let fileNameStartIndex = logFileNameRange?.startIndex.successor() { if fileNameStartIndex < filePath.endIndex { logFileName = filePath[fileNameStartIndex..<filePath.endIndex] } } return logFileName } // MARK: - Sending logs // Build the Request object that will be used to send the logs to the server internal static func buildLogSendRequest(callback: BmsCompletionHandler) -> BaseRequest? { let bmsClient = BMSClient.sharedInstance var headers: [String: String] = ["Content-Type": "text/plain"] var logUploadUrl = "" // Check that the BMSClient class has been initialized before building the upload URL // Bluemix request // Only the region is required to communicate with the Analytics service. App route and GUID are not required. if bmsClient.bluemixRegion != nil && bmsClient.bluemixRegion != "" { guard BMSAnalytics.apiKey != nil && BMSAnalytics.apiKey != "" else { returnInitializationError("Analytics", missingValue: "apiKey", callback: callback) return nil } headers[Constants.analyticsApiKey] = BMSAnalytics.apiKey! logUploadUrl = "https://" + Constants.AnalyticsServer.hostName + bmsClient.bluemixRegion! + Constants.AnalyticsServer.uploadPath // Request class is specific to Bluemix (since it uses Bluemix authorization managers) return Request(url: logUploadUrl, headers: headers, queryParameters: nil, method: HttpMethod.POST) } else { BMSLogger.internalLogger.error("Failed to send logs because the client was not yet initialized. Make sure that the BMSClient class has been initialized.") return nil } } // If this is reached, the user most likely failed to initialize BMSClient or Analytics internal static func returnInitializationError(uninitializedClass: String, missingValue: String, callback: BmsCompletionHandler) { BMSLogger.internalLogger.error("No value found for the \(uninitializedClass) \(missingValue) property.") let errorMessage = "Must initialize \(uninitializedClass) before sending logs to the server." var errorCode: Int switch uninitializedClass { case "Analytics": errorCode = BMSAnalyticsError.AnalyticsNotInitialized.rawValue case "BMSClient": errorCode = BMSCoreError.ClientNotInitialized.rawValue default: errorCode = -1 } let error = NSError(domain: BMSAnalyticsError.domain, code: errorCode, userInfo: [NSLocalizedDescriptionKey: errorMessage]) callback(nil, error) } // Read the logs from file, move them to the "send" buffer file, and return the logs internal static func getLogs(fileName fileName: String, overflowFileName: String, bufferFileName: String) throws -> String? { let logFile = BMSLogger.logsDocumentPath + fileName // Original log file let overflowLogFile = BMSLogger.logsDocumentPath + overflowFileName // Extra file in case original log file got full let bufferLogFile = BMSLogger.logsDocumentPath + bufferFileName // Temporary file for sending logs // First check if the "*.log.send" buffer file already contains logs. This will be the case if the previous attempt to send logs failed. if BMSLogger.fileManager.isReadableFileAtPath(bufferLogFile) { return try readLogsFromFile(bufferLogFile) } else if BMSLogger.fileManager.isReadableFileAtPath(logFile) { // Merge the logs from the normal log file and the overflow log file (if necessary) if BMSLogger.fileManager.isReadableFileAtPath(overflowLogFile) { let fileContents = try NSString(contentsOfFile: overflowLogFile, encoding: NSUTF8StringEncoding) as String BMSLogger.writeToFile(logFile, logMessage: fileContents, loggerName: BMSLogger.internalLogger.name) } // Since the buffer log is empty, we move the log file to the buffer file in preparation of sending the logs. When new logs are recorded, a new log file gets created to replace it. try BMSLogger.fileManager.moveItemAtPath(logFile, toPath: bufferLogFile) return try readLogsFromFile(bufferLogFile) } else { BMSLogger.internalLogger.error("Cannot send data to server. Unable to read file: \(fileName).") return nil } } // We should only be sending logs from a buffer file, which is a copy of the normal log file. This way, if the logs fail to get sent to the server, we can hold onto them until the send succeeds, while continuing to log to the normal log file. internal static func readLogsFromFile(bufferLogFile: String) throws -> String? { let analyticsOutboundLogs: String = BMSLogger.logsDocumentPath + Constants.File.Analytics.outboundLogs let loggerOutboundLogs: String = BMSLogger.logsDocumentPath + Constants.File.Logger.outboundLogs var fileContents: String? do { // Before sending the logs, we need to read them from the file. This is done in a serial dispatch queue to prevent conflicts if the log file is simulatenously being written to. switch bufferLogFile { case analyticsOutboundLogs: try dispatch_sync_throwable(BMSLogger.analyticsFileIOQueue, block: { () -> () in fileContents = try NSString(contentsOfFile: bufferLogFile, encoding: NSUTF8StringEncoding) as String }) case loggerOutboundLogs: try dispatch_sync_throwable(BMSLogger.loggerFileIOQueue, block: { () -> () in fileContents = try NSString(contentsOfFile: bufferLogFile, encoding: NSUTF8StringEncoding) as String }) default: BMSLogger.internalLogger.error("Cannot send data to server. Unrecognized file: \(bufferLogFile).") } } return fileContents } // For deleting files where only the file name is supplied, not the full path internal static func deleteFile(fileName: String) { let pathToFile = BMSLogger.logsDocumentPath + fileName if BMSLogger.fileManager.fileExistsAtPath(pathToFile) && BMSLogger.fileManager.isDeletableFileAtPath(pathToFile) { do { try BMSLogger.fileManager.removeItemAtPath(pathToFile) } catch let error { BMSLogger.internalLogger.error("Failed to delete log file \(fileName) after sending. Error: \(error)") } } } } // MARK: - Helper // Custom dispatch_sync that can incorporate throwable statements internal func dispatch_sync_throwable(queue: dispatch_queue_t, block: () throws -> ()) throws { var error: ErrorType? dispatch_sync(queue) { do { try block() } catch let caughtError { error = caughtError } } if error != nil { throw error! } }
mit
111389597fcde00fc33c4e694bb3b5a9
44.565295
246
0.641592
5.296527
false
false
false
false
devinroth/SwiftOSC
Framework/SwiftOSC/Communication/OSCClient.swift
1
886
import Foundation @objc open class OSCClient: NSObject { open var address: String { didSet { _ = client.close() client = UDPClient(addr: address, port: port) } } open var port: Int { didSet { _ = client.close() client = UDPClient(addr: address, port: port) } } var client: UDPClient public init(address: String, port: Int){ self.address = address self.port = port client = UDPClient(addr: address, port: port) client.enableBroadcast() } open func send(_ element: OSCElement){ let data = element.data if data.count > 9216 { print("OSCPacket is too large. Must be smaller than 9200 bytes") } else { _ = client.send(data:data) } } deinit { _ = client.close() } }
mit
574e55d0028a6c4cfab222b4a7296f80
24.314286
76
0.525959
4.12093
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/ForumFloorLordCell.swift
1
1597
// // ForumFloorLordCell.swift // DingshanSwift // // Created by song jufeng on 15/9/23. // Copyright © 2015年 song jufeng. All rights reserved. // import Foundation class ForumFloorLordCell : UICollectionReusableView{ var attrStrLabel:TTTAttributedLabel? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame aRect: CGRect) { super.init(frame: aRect); self.backgroundColor = UIColor.orangeColor().colorWithAlphaComponent(0.2) attrStrLabel = TTTAttributedLabel(frame: CGRectZero) attrStrLabel?.backgroundColor = UIColor.cyanColor().colorWithAlphaComponent(0.2) attrStrLabel?.font = kForumFloorCellContentFont attrStrLabel?.text = "..." attrStrLabel?.numberOfLines = 0; self.addSubview(attrStrLabel!) } func clearData() { // print("\(self).clearData") attrStrLabel?.setText("") } func loadCellData(data:AnyObject) { if let d = data as? ForumTopicData{ attrStrLabel?.attributedText = d.contentAttrString // debugPrint("---------loadCellData.attrStrLabel = \(attrStrLabel?.attributedText?.string)") } } override func layoutSubviews() { super.layoutSubviews() attrStrLabel?.frame = CGRect(x: kForumFloorEdgeWidth, y: 12, width: kForumLordFloorContentWidth, height: self.frame.size.height); debugPrint("---------ForumFloorLordCell.layoutSubviews.attrStrLabel.frame = \(attrStrLabel?.frame)") self.setNeedsDisplay() } }
mit
2c7e9d14023fd786b62918b01b0cc088
32.229167
137
0.654956
4.528409
false
false
false
false
tache/SwifterSwift
Sources/Extensions/SwiftStdlib/SignedIntegerExtensions.swift
1
1999
// // SignedIntegerExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/15/17. // Copyright © 2017 SwifterSwift // // MARK: - Properties public extension SignedInteger { /// SwifterSwift: Absolute value of integer number. public var abs: Self { return Swift.abs(self) } /// SwifterSwift: Check if integer is positive. public var isPositive: Bool { return self > 0 } /// SwifterSwift: Check if integer is negative. public var isNegative: Bool { return self < 0 } /// SwifterSwift: Check if integer is even. public var isEven: Bool { return (self % 2) == 0 } /// SwifterSwift: Check if integer is odd. public var isOdd: Bool { return (self % 2) != 0 } /// SwifterSwift: Array of digits of integer value. public var digits: [Self] { let intsArray = description.flatMap({Int(String($0))}) return intsArray.map({Self($0)}) } /// SwifterSwift: Number of digits of integer value. public var digitsCount: Int { return description.flatMap({Int(String($0))}).count } /// SwifterSwift: String of format (XXh XXm) from seconds Int. public var timeString: String { guard self > 0 else { return "0 sec" } if self < 60 { return "\(self) sec" } if self < 3600 { return "\(self / 60) min" } let hours = self / 3600 let mins = (self % 3600) / 60 if hours != 0 && mins == 0 { return "\(hours)h" } return "\(hours)h \(mins)m" } } // MARK: - Methods public extension SignedInteger { /// SwifterSwift: Greatest common divisor of integer value and n. /// /// - Parameter n: integer value to find gcd with. /// - Returns: greatest common divisor of self and n. public func gcd(of n: Self) -> Self { return n == 0 ? self : n.gcd(of: self % n) } /// SwifterSwift: Least common multiple of integer and n. /// /// - Parameter n: integer value to find lcm with. /// - Returns: least common multiple of self and n. public func lcm(of n: Self) -> Self { return (self * n).abs / gcd(of: n) } }
mit
9e62f9da257805ce70ad6bb4ce819fcc
21.449438
66
0.64014
3.27541
false
false
false
false
silence0201/Swift-Study
Swift4/Swift4新特性.playground/Pages/Associated type constraints.xcplaygroundpage/Contents.swift
1
1704
/*: [首页](Table%20of%20contents) • [上一页](@previous) • [下一页](@next) ## 协议相关类型的约束 [SE-0142][SE-0142]: 协议的相关类型可以用`where`语句约束. 看似一小步,却是类型系统表达能力的一大步,让标准库可以大幅简化. 喜大普奔的是, `Sequence` 和 `Collection` 在Swift 4中用上这个就更直观了. [SE-0142]: https://github.com/apple/swift-evolution/blob/master/proposals/0142-associated-types-constraints.md "Swift Evolution Proposal SE-0142: Permit where clauses to constrain associated types" ### `Sequence.Element` `Sequence` 现在有了自己的相关类型 `Element` . 原先Swift 3中到处露脸的 `Iterator.Element` , 现在瘦身成`Element`: */ extension Sequence where Element: Numeric { var 求和: Element { var 结果: Element = 0 for 单个元素 in self { 结果 += 单个元素 } return 结果 } } [1,2,3,4].求和 /*: ### 当扩展 `Sequence` 和 `Collection` 时所需约束更少 */ // 在Swift 3时代, 这种扩展需要很多的约束: //extension Collection where Iterator.Element: Equatable, // SubSequence: Sequence, // SubSequence.Iterator.Element == Iterator.Element // // 而在Swift 4, 编译器已经提前知道了上述3个约束中的2个, 因为可以用相关类型的where语句来表达它们. extension Collection where Element: Equatable { func 头尾镜像(_ n: Int) -> Bool { let 头 = prefix(n) let 尾 = suffix(n).reversed() return 头.elementsEqual(尾) } } [1,2,3,4,2,1].头尾镜像(2) /*: [首页](Table%20of%20contents) • [上一页](@previous) • [下一页](@next) */
mit
c690262ef3a020a444474c9bb4bd23cb
27.711111
198
0.659443
2.708595
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/NavigationItem.swift
3
6438
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit /// A memory reference to the NavigationItem instance. private var NavigationItemKey: UInt8 = 0 private var NavigationItemContext: UInt8 = 0 public class NavigationItem: NSObject { /// Should center the contentView. open var contentViewAlignment = ContentViewAlignment.center { didSet { navigationBar?.layoutSubviews() } } /// Back Button. public private(set) lazy var backButton: IconButton = IconButton() /// Content View. public private(set) lazy var contentView = UIView() /// Title label. public private(set) lazy var titleLabel = UILabel() /// Detail label. public private(set) lazy var detailLabel = UILabel() /// Left items. public var leftViews = [UIView]() { didSet { for v in oldValue { v.removeFromSuperview() } navigationBar?.layoutSubviews() } } /// Right items. public var rightViews = [UIView]() { didSet { for v in oldValue { v.removeFromSuperview() } navigationBar?.layoutSubviews() } } /// Center items. public var centerViews: [UIView] { get { return contentView.grid.views } set(value) { contentView.grid.views = value } } public var navigationBar: NavigationBar? { return contentView.superview?.superview as? NavigationBar } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard "titleLabel.textAlignment" == keyPath else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } contentViewAlignment = .center == titleLabel.textAlignment ? .center : .full } deinit { removeObserver(self, forKeyPath: "titleLabel.textAlignment") } /// Initializer. public override init() { super.init() prepareTitleLabel() prepareDetailLabel() } /// Reloads the subviews for the NavigationBar. internal func reload() { navigationBar?.layoutSubviews() } /// Prepares the titleLabel. private func prepareTitleLabel() { titleLabel.textAlignment = .center titleLabel.contentScaleFactor = Screen.scale titleLabel.font = RobotoFont.medium(with: 17) titleLabel.textColor = Color.darkText.primary addObserver(self, forKeyPath: "titleLabel.textAlignment", options: [], context: &NavigationItemContext) } /// Prepares the detailLabel. private func prepareDetailLabel() { detailLabel.textAlignment = .center titleLabel.contentScaleFactor = Screen.scale detailLabel.font = RobotoFont.regular(with: 12) detailLabel.textColor = Color.darkText.secondary } } extension UINavigationItem { /// NavigationItem reference. public internal(set) var navigationItem: NavigationItem { get { return AssociatedObject(base: self, key: &NavigationItemKey) { return NavigationItem() } } set(value) { AssociateObject(base: self, key: &NavigationItemKey, value: value) } } /// Should center the contentView. public var contentViewAlignment: ContentViewAlignment { get { return navigationItem.contentViewAlignment } set(value) { navigationItem.contentViewAlignment = value } } /// Content View. public var contentView: UIView { return navigationItem.contentView } /// Back Button. public var backButton: IconButton { return navigationItem.backButton } /// Title text. @nonobjc public var title: String? { get { return titleLabel.text } set(value) { titleLabel.text = value navigationItem.reload() } } /// Title Label. public var titleLabel: UILabel { return navigationItem.titleLabel } /// Detail text. public var detail: String? { get { return detailLabel.text } set(value) { detailLabel.text = value navigationItem.reload() } } /// Detail Label. public var detailLabel: UILabel { return navigationItem.detailLabel } /// Left side UIViews. public var leftViews: [UIView] { get { return navigationItem.leftViews } set(value) { navigationItem.leftViews = value } } /// Right side UIViews. public var rightViews: [UIView] { get { return navigationItem.rightViews } set(value) { navigationItem.rightViews = value } } /// Center UIViews. open var centerViews: [UIView] { get { return navigationItem.centerViews } set(value) { navigationItem.centerViews = value } } }
agpl-3.0
a4c1a80c5fe94700a79d2f4b13207b2f
27.236842
156
0.666511
4.588738
false
false
false
false
stripe/stripe-ios
StripePayments/StripePayments/API Bindings/Models/Sources/Types/STPSourceKlarnaDetails.swift
1
1725
// // STPSourceKlarnaDetails.swift // StripePayments // // Created by David Estes on 11/19/19. // Copyright © 2019 Stripe, Inc. All rights reserved. // import Foundation /// Details of a Klarna source. public class STPSourceKlarnaDetails: NSObject, STPAPIResponseDecodable { /// The Klarna-specific client token. This may be used with the Klarna SDK. /// - seealso: https://developers.klarna.com/documentation/in-app/ios/steps-klarna-payments-native/#initialization @objc public private(set) var clientToken: String? /// The ISO-3166 2-letter country code of the customer's location. @objc public private(set) var purchaseCountry: String? private(set) public var allResponseFields: [AnyHashable: Any] = [:] // MARK: - Description /// :nodoc: @objc public override var description: String { let props = [ String(format: "%@: %p", NSStringFromClass(STPSourceKlarnaDetails.self), self), "clientToken = \(clientToken ?? "")", "purchaseCountry = \(purchaseCountry ?? "")", ] return "<\(props.joined(separator: "; "))>" } // MARK: - STPAPIResponseDecodable override required init() { super.init() } @objc public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { guard let response = response else { return nil } let dict = response.stp_dictionaryByRemovingNulls() let details = self.init() details.clientToken = dict.stp_string(forKey: "client_token") details.purchaseCountry = dict.stp_string(forKey: "purchase_country") details.allResponseFields = response return details } }
mit
c26f621dfdbac840daeb5421bb817302
33.48
118
0.650232
4.184466
false
false
false
false
fxm90/GradientProgressBar
GradientProgressBar/Tests/SnapshotTests/GradientProgressBarSnapshotTestCase.swift
1
4924
// // GradientProgressBarSnapshotTestCase.swift // ExampleSnapshotTests // // Created by Felix Mau on 07.11.19. // Copyright © 2019 Felix Mau. All rights reserved. // import SnapshotTesting import XCTest @testable import GradientProgressBar final class GradientProgressBarSnapshotTestCase: XCTestCase { // MARK: - Config private enum Config { /// The frame we use for rendering the `GradientProgressBar`. This will also be the image size for our snapshot. static let frame = CGRect(x: 0.0, y: 0.0, width: 375.0, height: 4.0) /// The custom colors we use on this test-case. /// Source: https://color.adobe.com/Pink-Flamingo-color-theme-10343714/ static let gradientColors = [ #colorLiteral(red: 0.9490196078, green: 0.3215686275, blue: 0.431372549, alpha: 1), #colorLiteral(red: 0.9450980392, green: 0.4784313725, blue: 0.5921568627, alpha: 1), #colorLiteral(red: 0.9529411765, green: 0.737254902, blue: 0.7843137255, alpha: 1), #colorLiteral(red: 0.4274509804, green: 0.8666666667, blue: 0.9490196078, alpha: 1), #colorLiteral(red: 0.7568627451, green: 0.9411764706, blue: 0.9568627451, alpha: 1), ] static let lightTraitCollection = UITraitCollection(userInterfaceStyle: .light) static let darkTraitCollection = UITraitCollection(userInterfaceStyle: .dark) } // MARK: - Test `.light` user interface style func test_gradientProgressBar_withProgressZero_andLightTraitCollection() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) // When gradientProgressBar.progress = 0.0 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.lightTraitCollection)) } func test_gradientProgressBar_withProgress50Percent_andLightTraitCollection() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) // When gradientProgressBar.progress = 0.5 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.lightTraitCollection)) } func test_gradientProgressBar_withProgress100Percent_andLightTraitCollection() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) // When gradientProgressBar.progress = 1.0 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.lightTraitCollection)) } // MARK: - Test `.dark` user interface style func test_gradientProgressBar_withProgressZero_andDarkTraitCollection() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) // When gradientProgressBar.progress = 0.0 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.darkTraitCollection)) } func test_gradientProgressBar_withProgress50Percent_andDarkTraitCollection() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) // When gradientProgressBar.progress = 0.5 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.darkTraitCollection)) } func test_gradientProgressBar_withProgress100Percent_andDarkTraitCollection() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) // When gradientProgressBar.progress = 1.0 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.darkTraitCollection)) } // MARK: - Test custom colors func test_gradientProgressBar_withProgressZero_andCustomColors() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) gradientProgressBar.gradientColors = Config.gradientColors // When gradientProgressBar.progress = 0.0 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.lightTraitCollection)) } func test_gradientProgressBar_withProgress50Percent_andCustomColors() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) gradientProgressBar.gradientColors = Config.gradientColors // When gradientProgressBar.progress = 0.5 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.lightTraitCollection)) } func test_gradientProgressBar_withProgress100Percent_andCustomColors() { // Given let gradientProgressBar = GradientProgressBar(frame: Config.frame) gradientProgressBar.gradientColors = Config.gradientColors // When gradientProgressBar.progress = 1.0 // Then assertSnapshot(matching: gradientProgressBar, as: .image(traits: Config.lightTraitCollection)) } }
mit
8108f5b975d44a85835e304e83cdf8e4
34.417266
434
0.692464
4.62688
false
true
false
false
MTTHWBSH/Gaggle
Gaggle/Views/PostTableViewCell.swift
1
2559
// // PostTableViewCell.swift // Gaggle // // Created by Matthew Bush on 4/8/16. // Copyright © 2016 Matthew Bush. All rights reserved. // import UIKit import Parse class PostTableViewCell: UITableViewCell { @IBOutlet weak var userButton: SecondaryTextButton! @IBOutlet weak var timeLabel: SecondaryLabel! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var postDetailsView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var wrapperView: UIView! var userButtonTapped: ((Void) -> Void)? var detailsShown = false override func awakeFromNib() { super.awakeFromNib() styleView() setupView() } override func prepareForReuse() { super.prepareForReuse() if detailsShown { hideDetails(duration: 0.0) } userButton.setTitle(nil, for: UIControlState()) timeLabel.attributedText = nil postImageView?.image = UIImage(named: "PhotoPlaceholder") titleLabel.text = nil subtitleLabel.text = nil } func styleView() { backgroundColor = Style.lightGrayColor postDetailsView.backgroundColor = Style.randomBrandColor(withOpacity: 0.85) separatorInset = UIEdgeInsets.zero layoutMargins = UIEdgeInsets.zero timeLabel.clipsToBounds = false titleLabel.font = Style.regularFontWithSize(32.0) subtitleLabel.font = Style.regularFontWithSize(32.0) postDetailsView.alpha = 0.0 } func setupView() { wrapperView.isUserInteractionEnabled = true let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(detailsTapped)) wrapperView.addGestureRecognizer(gestureRecognizer) } func detailsTapped() { let label = detailsShown ? "Hide Details" : "Show Details" Analytics.logEvent("Post", action: "Image Tapped", Label: label, key: "") detailsShown ? hideDetails(duration: 0.6) : showDetails(duration: 0.6) } func hideDetails(duration: Double) { detailsShown = false Animation.fadeOut(postDetailsView, duration: duration) } func showDetails(duration: Double) { detailsShown = true Animation.fadeIn(postDetailsView, duration: duration) } @IBAction func userButtonPressed(_ sender: AnyObject) { Analytics.logEvent("Post", action: "User Button", Label: "User Button Pressed", key: "") userButtonTapped?() } }
gpl-2.0
b4201c212f54c612b86a5c3f0d42a4e1
30.975
102
0.664191
4.835539
false
false
false
false
argent-os/argent-ios
app-ios/AuthViewController.swift
1
10265
// // AuthViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 2/9/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import UIKit import LTMorphingLabel import Foundation import TransitionTreasury import TransitionAnimation import FBSDKLoginKit import Spring class AuthViewController: UIPageViewController, UIPageViewControllerDelegate, LTMorphingLabelDelegate, ModalTransitionDelegate { private var i = -1 private var textArray2 = [ "Welcome to " + APP_NAME, APP_NAME + "'e hoş geldiniz", "Bienvenue à " + APP_NAME, "歡迎銀色", "Bienvenidos a " + APP_NAME, "アージェントすることを歓迎", "Добро пожаловать в Серебряном", "Willkommen in " + APP_NAME, "은빛에 오신 것을 환영합니다", "Benvenuto a " + APP_NAME ] internal var tr_presentTransition: TRViewControllerTransitionDelegate? let lbl = SpringLabel() let lblDetail = SpringLabel() let lblSubtext = LTMorphingLabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100.0)) let imageView = SpringImageView() private var text: String { i = i >= textArray2.count - 1 ? 0 : i + 1 return textArray2[i] } // func changeText(sender: AnyObject) { // lblSubtext.text = text // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func skipOnboarding(sender: AnyObject) { NSNotificationCenter.defaultCenter().postNotificationName("kDismissOnboardingNotification", object: self) } override func viewDidLoad() { super.viewDidLoad() // Border radius on uiview configureView() } func configureView() { // Test Facebook // let fbLoginButton = FBSDKLoginButton() // fbLoginButton.loginBehavior = .SystemAccount // fbLoginButton.center = self.view.center // self.view.addSubview(fbLoginButton) // Set up paging dataSource = self delegate = self setViewControllers([getStepOne()], direction: .Forward, animated: false, completion: nil) view.backgroundColor = UIColor.whiteColor() // screen width and height: let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height // UI let loginButton = UIButton(frame: CGRect(x: 15, y: screenHeight-60-28, width: screenWidth-30, height: 60.0)) loginButton.setBackgroundColor(UIColor.whiteColor(), forState: .Normal) loginButton.setBackgroundColor(UIColor.whiteColor(), forState: .Highlighted) loginButton.tintColor = UIColor.darkBlue() loginButton.setTitleColor(UIColor.darkBlue(), forState: .Normal) loginButton.setTitleColor(UIColor.whiteColor(), forState: .Highlighted) loginButton.titleLabel?.font = UIFont(name: "SFUIText-Regular", size: 15)! loginButton.setAttributedTitle(adjustAttributedString("Login", spacing: 1, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.darkBlue(), lineSpacing: 0.0, alignment: .Center), forState: .Normal) loginButton.setAttributedTitle(adjustAttributedString("Login", spacing: 1, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.lightBlue(), lineSpacing: 0.0, alignment: .Center), forState: .Highlighted) loginButton.layer.cornerRadius = 3 loginButton.layer.borderWidth = 0 loginButton.layer.borderColor = UIColor.darkBlue().CGColor loginButton.layer.masksToBounds = true loginButton.addTarget(self, action: #selector(AuthViewController.login(_:)), forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(loginButton) let signupButton = UIButton(frame: CGRect(x: 15, y: screenHeight-60-88, width: screenWidth-30, height: 54.0)) signupButton.setBackgroundColor(UIColor.pastelBlue(), forState: .Normal) signupButton.setBackgroundColor(UIColor.pastelBlue().darkerColor(), forState: .Highlighted) signupButton.setAttributedTitle(adjustAttributedString("Get Started", spacing: 1, fontName: "SFUIText-Regular", fontSize: 15, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Center), forState: .Normal) signupButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) signupButton.setTitleColor(UIColor.whiteColor().lighterColor(), forState: .Highlighted) signupButton.layer.cornerRadius = 5 signupButton.layer.borderWidth = 1 signupButton.layer.borderColor = UIColor.pastelBlue().CGColor signupButton.layer.masksToBounds = true signupButton.addTarget(self, action: #selector(AuthViewController.signup(_:)), forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(signupButton) // // Set range of string length to exactly 8, the number of characters // lbl.frame = CGRect(x: 0, y: screenHeight*0.33, width: screenWidth, height: 40) // lbl.font = UIFont(name: "SFUIText-Regular", size: 23) // lbl.tag = 7578 // lbl.textAlignment = NSTextAlignment.Center // lbl.textColor = UIColor.darkBlue() // lbl.adjustAttributedString(APP_NAME.uppercaseString, spacing: 8, fontName: "SFUIDisplay-Thin", fontSize: 17, fontColor: UIColor.darkBlue()) // view.addSubview(lbl) // // _ = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(AuthViewController.changeText(_:)), userInfo: nil, repeats: true) } //Changing Status Bar override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func prefersStatusBarHidden() -> Bool { return true } // Set the ID in the storyboard in order to enable transition! func signup(sender:AnyObject!) { let viewController:UINavigationController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SignupNavigationController") as! UINavigationController self.presentViewController(viewController, animated: true, completion: nil) } // Set the ID in the storyboard in order to enable transition! func login(sender:AnyObject!) { let model = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController self.presentViewController(model, animated: true, completion: nil) } // MARK: - Modal tt delegate func modalViewControllerDismiss(callbackData data: AnyObject? = nil) { tr_dismissViewController(completion: { print("Dismiss finished.") }) } override func viewDidAppear(animated: Bool) { } } extension AuthViewController { func morphingDidStart(label: LTMorphingLabel) { } func morphingDidComplete(label: LTMorphingLabel) { } func morphingOnProgress(label: LTMorphingLabel, progress: Float) { } } extension AuthViewController { func getStepOne() -> AuthViewControllerStepOne { return storyboard!.instantiateViewControllerWithIdentifier("authStepOne") as! AuthViewControllerStepOne } func getStepTwo() -> AuthViewControllerStepTwo { return storyboard!.instantiateViewControllerWithIdentifier("authStepTwo") as! AuthViewControllerStepTwo } func getStepThree() -> AuthViewControllerStepThree { return storyboard!.instantiateViewControllerWithIdentifier("authStepThree") as! AuthViewControllerStepThree } func getStepFour() -> AuthViewControllerStepFour { return storyboard!.instantiateViewControllerWithIdentifier("authStepFour") as! AuthViewControllerStepFour } } extension AuthViewController: UIPageViewControllerDataSource { func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { if viewController.isKindOfClass(AuthViewControllerStepFour) { return getStepThree() } else if viewController.isKindOfClass(AuthViewControllerStepThree) { return getStepTwo() } else if viewController.isKindOfClass(AuthViewControllerStepTwo) { return getStepOne() } else if viewController.isKindOfClass(AuthViewControllerStepOne) { return nil } else if viewController.isKindOfClass(AuthViewController) { return nil } else { return nil } } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { if viewController.isKindOfClass(AuthViewController) { return getStepOne() } else if viewController.isKindOfClass(AuthViewControllerStepOne) { return getStepTwo() } else if viewController.isKindOfClass(AuthViewControllerStepTwo) { return getStepThree() } else if viewController.isKindOfClass(AuthViewControllerStepThree) { return getStepFour() } else if viewController.isKindOfClass(AuthViewControllerStepThree) { return nil } else { return nil } } func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return 4 } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 } } extension AuthViewController { override func viewWillDisappear(animated: Bool) { lblDetail.animation = "fadeInUp" lblDetail.duration = 3 lblDetail.animateTo() lbl.animation = "fadeInUp" lbl.duration = 1 lbl.animateTo() imageView.animation = "fadeInUp" imageView.duration = 1 imageView.animateTo() } }
mit
c1bb6efd4ba08eb248973106b59bf250
37.851145
224
0.680291
5.158642
false
false
false
false
mono0926/firebase-verifier
Sources/User.swift
1
1884
// // VerifiedResult.swift // Bits // // Created by mono on 2017/08/03. // import Foundation import JWT public struct Firebase { public let identities: [String: [String]] public let signInProvider: String init(json: JSON) { identities = json["identities"]!.object! .reduce([String: [String]]()) { sum, e in var sum = sum sum[e.key] = e.value.array!.map { $0.string! } return sum } signInProvider = json["sign_in_provider"]!.string! } public init(identities: [String: [String]], signInProvider: String) { self.identities = identities self.signInProvider = signInProvider } } public struct User { public let id: String public let authTime: Date public let issuedAtTime: Date public let expirationTime: Date public let email: String? public let emailVerified: Bool? public let firebase: Firebase public init(id: String, authTime: Date, issuedAtTime: Date, expirationTime: Date, email: String? = nil, emailVerified: Bool? = nil, firebase: Firebase = Firebase(identities: [:], signInProvider: "")) { self.id = id self.authTime = authTime self.issuedAtTime = issuedAtTime self.expirationTime = expirationTime self.email = email self.emailVerified = emailVerified self.firebase = firebase } public init(jwt: JWT) { self.init(id: jwt.userId!, authTime: jwt.authTime!, issuedAtTime: jwt.issuedAtTime!, expirationTime: jwt.expirationTime!, email: jwt.email, emailVerified: jwt.emailVerified, firebase: Firebase(json: jwt.payload["firebase"]!)) } }
mit
ee23713e6edc4946ab2b02a5b3701701
27.984615
85
0.571125
4.528846
false
false
false
false
Maquert/AppleWatchApp
AppleWatchApp/Class/Presenter/CounterPresenter.swift
1
1054
import UIKit /// This presenter manages the display of a counter. class CounterPresenter: UIViewController { // MARK: Attributes private var count: Int = 10 { didSet { counter.text = String(count) steeper.value = Double(count) } } @IBOutlet weak var counter: UILabel! { didSet { counter.text = String(count) } } @IBOutlet weak var steeper: UIStepper! { didSet { steeper.value = Double(count) } } // MARK: Init override func viewDidLoad() { super.viewDidLoad() NotificationsManager.subscribeToStatusChanges(object: self, selector: #selector(statusChanged)) } func statusChanged(notification: NSNotification) { guard let count = notification.object as? CountType else { return } self.count = count } // MARK: Events @IBAction func steeperValueChanged(_ sender: UIStepper) { self.count = Int(sender.value) } }
gpl-3.0
d397932724b380b32643491ef2656dfd
19.666667
103
0.57685
4.857143
false
false
false
false
qvacua/vimr
NvimView/Support/DrawerDev/MyView.swift
1
5683
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa // let cells = ["👨‍👨‍👧‍👧", "", "a"] // let cells = ["👶🏽", "", "a"] // let cells = ["ü", "a͆", "a̪"] // let cells = ["a", "b" , "c"] // let cells = ["<", "-", "-", "\u{1F600}", "", " ", "b", "c"] class MyView: NSView { required init?(coder decoder: NSCoder) { super.init(coder: decoder) self.setupUgrid() } override func draw(_: NSRect) { guard let context = NSGraphicsContext.current?.cgContext else { return } let cellSize = FontUtils.cellSize(of: fira, linespacing: 1, characterspacing: 1) /* let string = "a\u{034B}" let attrStr = NSAttributedString(string: string, attributes: [.font: fira]) let ctLine = CTLineCreateWithAttributedString(attrStr) let ctRun = (CTLineGetGlyphRuns(ctLine) as! Array<CTRun>)[0] let glyphCount = CTRunGetGlyphCount(ctRun) var glyphs = Array(repeating: CGGlyph(), count: glyphCount) var positions = Array(repeating: CGPoint(), count: glyphCount) var advances = Array(repeating: CGSize(), count: glyphCount) CTRunGetGlyphs(ctRun, .zero, &glyphs) CTRunGetPositions(ctRun, .zero, &positions) CTRunGetAdvances(ctRun, .zero, &advances) let attrs = CTRunGetAttributes(ctRun) as! [NSAttributedStringKey: Any] let font = attrs[NSAttributedStringKey.font] as! NSFont for i in (0..<positions.count) { positions[i].x += 20 positions[i].y += 10 } print(glyphs) print(positions) print(advances) CTFontDrawGlyphs(font, glyphs, positions, glyphCount, context) */ /* // let glyphs: [CGGlyph] = [1614, 1494, 1104, 133] let glyphs: [CGGlyph] = [1614, 1614, 1063] let positions = (0..<3).compactMap { CGPoint(x: CGFloat($0) * cellSize.width, y: 10) } CTFontDrawGlyphs( fira, glyphs, positions, 3, context ) */ let runs = (0..<5).map { row in AttributesRun( location: CGPoint(x: 0, y: CGFloat(row) * cellSize.height), cells: self.ugrid.cells[row][0..<10], attrs: CellAttributes( fontTrait: [], foreground: NSColor.textColor.int, background: NSColor.textBackgroundColor.int, special: 0xFF0000, reverse: false ) ) } let defaultAttrs = CellAttributes( fontTrait: [], foreground: NSColor.textColor.int, background: NSColor.textBackgroundColor.int, special: 0xFF0000, reverse: false ) self.runDrawer.usesLigatures = true runs.forEach { _ in self.runDrawer.draw( runs, defaultAttributes: defaultAttrs, offset: .zero, in: context ) } self.draw(cellGridIn: context, cellSize: cellSize) } private let ugrid = UGrid() private let runDrawer = AttributesRunDrawer( baseFont: fira, linespacing: 1, characterspacing: 1, usesLigatures: true ) private func draw(cellGridIn context: CGContext, cellSize: CGSize) { context.saveGState() defer { context.restoreGState() } let color = NSColor.magenta.cgColor context.setFillColor(color) var lines = [ CGRect(x: 0, y: 0, width: 1, height: self.bounds.height), CGRect( x: self.bounds.width - 1, y: 0, width: 1, height: self.bounds.height ), CGRect(x: 0, y: 0, width: self.bounds.width, height: 1), CGRect( x: 0, y: self.bounds.height - 1, width: self.bounds.width, height: 1 ), ] let rowCount = Int(ceil(self.bounds.height / cellSize.height)) let columnCount = Int(ceil(self.bounds.width / cellSize.width)) for row in 0..<rowCount { for col in 0..<columnCount { lines.append(contentsOf: [ CGRect( x: CGFloat(col) * cellSize.width, y: CGFloat(row) * cellSize.height, width: 1, height: self.bounds.height ), CGRect( x: CGFloat(col) * cellSize.width, y: CGFloat(row) * cellSize.height, width: self.bounds.width, height: 1 ), ]) } } lines.forEach { $0.fill() } } private func setupUgrid() { self.ugrid.resize(Size(width: 10, height: 10)) self.ugrid.update( row: 0, startCol: 0, endCol: 10, clearCol: 10, clearAttr: 0, chunk: [ "하", "", "태", "", "원", "", " ", "a\u{1DC1}", "a\u{032A}", "a\u{034B}", ], attrIds: Array(repeating: 0, count: 10) ) self.ugrid.update( row: 2, startCol: 0, endCol: 10, clearCol: 10, clearAttr: 0, chunk: [">", "=", " ", "-", "-", ">", " ", "<", "=", ">"], attrIds: Array(repeating: 0, count: 10) ) self.ugrid.update( row: 1, startCol: 0, endCol: 10, clearCol: 10, clearAttr: 0, chunk: ["ἐ", "τ", "έ", "ἔ", "-", ">", " ", "<", "=", ">"], attrIds: Array(repeating: 0, count: 10) ) self.ugrid.update( row: 3, startCol: 0, endCol: 10, clearCol: 10, clearAttr: 0, chunk: (0..<10).compactMap { String($0) }, attrIds: Array(repeating: 0, count: 10) ) self.ugrid.update( row: 4, startCol: 0, endCol: 8, clearCol: 8, clearAttr: 0, chunk: ["क", "ख", "ग", "घ", "ड़", "-", ">", "ड़"], attrIds: Array(repeating: 0, count: 8) ) } } private let fira = NSFont(name: "FiraCodeRoman-Regular", size: 36)!
mit
3628c5d917e7c24a5aa197eb4c19c67f
26.076923
84
0.544567
3.557802
false
false
false
false
davejlin/treehouse
swift/swift2/voice-memo-saving-data-to-cloud/VoiceMemo/Memo.swift
1
1216
// // Memo.swift // VoiceMemo // // Created by Screencast on 9/1/16. // Copyright © 2016 Treehouse Island, Inc. All rights reserved. // import Foundation import CloudKit struct Memo { static let entityName = "\(Memo.self)" let id: CKRecordID? let title: String let fileURLString: String } extension Memo { var fileURL: NSURL { return NSURL(fileURLWithPath: fileURLString) } } extension Memo { var persistableRecord: CKRecord { let record = CKRecord(recordType: Memo.entityName) record.setValue(title, forKey: "title") let asset = CKAsset(fileURL: fileURL) record.setValue(asset, forKey: "recording") return record } } extension Memo { init?(record: CKRecord) { guard let title = record.valueForKey("title") as? String, let asset = record.valueForKey("recording") as? CKAsset else { return nil } self.id = record.recordID self.title = title self.fileURLString = asset.fileURL.absoluteString } } extension Memo { var track: NSData? { return NSData(contentsOfURL: fileURL) } }
unlicense
785b905036b1d5278c274f0881e3efd6
13.817073
74
0.6
4.293286
false
false
false
false
zhou9734/Warm
Warm/Classes/Me/Controller/DetailViewController.swift
1
1554
// // DetailViewController.swift // Warm // // Created by zhoucj on 16/9/19. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit class DetailViewController: UIViewController { var titleName: String?{ didSet{ title = titleName } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Color_GlobalBackground view.addSubview(imageView) view.addSubview(msgLbl) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = false var textAttrs: [String : AnyObject] = Dictionary() textAttrs[NSForegroundColorAttributeName] = UIColor.blackColor() textAttrs[NSFontAttributeName] = UIFont.systemFontOfSize(17) navigationController?.navigationBar.titleTextAttributes = textAttrs } private lazy var imageView: UIImageView = { let iv = UIImageView() iv.image = UIImage(named: "nocontent_133x76_") iv.frame = CGRect(x: (ScreenWidth - 133.0)/2, y: (ScreenHeight - 76.0)/2, width: 133.0, height: 76.0) return iv }() private lazy var msgLbl: UILabel = { let lbl = UILabel() lbl.text = "没有数据" lbl.textAlignment = .Center lbl.textColor = UIColor.grayColor() lbl.font = UIFont.systemFontOfSize(15) lbl.frame = CGRect(x: (ScreenWidth - 100.0)/2, y: (ScreenHeight - 76.0)/2 + 86, width: 100.0, height: 20.0) return lbl }() }
mit
ee92012d1b1382b9ccc00822f14d93a9
32.543478
115
0.635774
4.33427
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/Extensions/UIImage+Exporters.swift
1
5665
import Foundation import ImageIO import MobileCoreServices extension UIImage { // MARK: - Error Handling enum ErrorCode: Int { case failedToWrite = 1 } fileprivate func errorForCode(_ errorCode: ErrorCode, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "UIImage+ImageIOExtensions", code: errorCode.rawValue, userInfo: userInfo) return error } /** Writes an image to a url location with the designated type format and EXIF metadata - Parameters: - url: file url to where the asset should be exported, this must be writable location - type: the UTI format to use when exporting the asset - compressionQuality: defines the compression quality of the export. This is only relevant for type formats that support a quality parameter. Ex: jpeg - metadata: the image metadata to save to file. */ func writeToURL(_ url: URL, type: String, compressionQuality: Float = 0.9, metadata: [String: AnyObject]? = nil) throws { let properties: [String: AnyObject] = [kCGImageDestinationLossyCompressionQuality as String: compressionQuality as AnyObject] var finalMetadata = metadata if metadata == nil { finalMetadata = [kCGImagePropertyOrientation as String: Int(metadataOrientation.rawValue) as AnyObject] } guard let destination = CGImageDestinationCreateWithURL(url as CFURL, type as CFString, 1, nil), let imageRef = self.cgImage else { throw errorForCode(.failedToWrite, failureReason: NSLocalizedString("Unable to write image to file", comment: "Error reason to display when the writing of a image to a file fails") ) } CGImageDestinationSetProperties(destination, properties as CFDictionary?) CGImageDestinationAddImage(destination, imageRef, finalMetadata as CFDictionary?) if !CGImageDestinationFinalize(destination) { throw errorForCode(.failedToWrite, failureReason: NSLocalizedString("Unable to write image to file", comment: "Error reason to display when the writing of a image to a file fails") ) } } /** Writes an image to a url location using the JPEG format. - Parameters: - url: file url to where the asset should be exported, this must be writable location */ func writeJPEGToURL(_ url: URL) throws { let data = UIImageJPEGRepresentation(self, 0.9) try data?.write(to: url, options: NSData.WritingOptions()) } // Converts the imageOrientation from the image to the CGImagePropertyOrientation to use in the file metadata. var metadataOrientation: CGImagePropertyOrientation { get { switch imageOrientation { case .up: return CGImagePropertyOrientation.up case .down: return CGImagePropertyOrientation.down case .left: return CGImagePropertyOrientation.left case .right: return CGImagePropertyOrientation.right case .upMirrored: return CGImagePropertyOrientation.upMirrored case .downMirrored: return CGImagePropertyOrientation.downMirrored case .leftMirrored: return CGImagePropertyOrientation.leftMirrored case .rightMirrored: return CGImagePropertyOrientation.rightMirrored } } } } extension UIImage: ExportableAsset { func exportToURL(_ url: URL, targetUTI: String, maximumResolution: CGSize, stripGeoLocation: Bool, synchronous: Bool, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { var finalImage = self if maximumResolution.width <= self.size.width || maximumResolution.height <= self.size.height { finalImage = self.resizedImage(with: .scaleAspectFit, bounds: maximumResolution, interpolationQuality: .high) } do { try finalImage.writeToURL(url, type: targetUTI, compressionQuality: 0.9, metadata: nil) successHandler(finalImage.size) } catch let error as NSError { errorHandler(error) } } func exportThumbnailToURL(_ url: URL, targetSize: CGSize, synchronous: Bool, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { let thumbnail = self.resizedImage(with: .scaleAspectFit, bounds: targetSize, interpolationQuality: .high) do { try self.writeToURL(url, type: defaultThumbnailUTI as String, compressionQuality: 0.9, metadata: nil) successHandler((thumbnail?.size)!) } catch let error as NSError { errorHandler(error) } } func exportOriginalImage(_ toURL: URL, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { do { try self.writeToURL(toURL, type: originalUTI()!, compressionQuality: 1.0, metadata: nil) successHandler(self.size) } catch let error as NSError { errorHandler(error) } } func originalUTI() -> String? { return kUTTypeJPEG as String } var assetMediaType: MediaType { get { return .image } } var defaultThumbnailUTI: String { get { return kUTTypeJPEG as String } } }
gpl-2.0
df7f7c33445c50f07badf25633badc08
40.350365
165
0.642542
5.452358
false
false
false
false
masteranca/RxFlow
RxFlow/Target.swift
1
6282
// // Target.swift // RxFlow // // Created by Anders Carlsson on 22/02/16. // Copyright © 2016 CoreDev. All rights reserved. // import Foundation import SwiftyJSON import RxSwift //// Default UTF8StringParser public let UTF8StringParser: (NSData) throws -> (String) = { data in guard let result = String(data: data, encoding: NSUTF8StringEncoding) else { throw FlowError.ParseError(nil) } return result } //// SwiftyJSON parser public let SwiftyJSONParser: (NSData) -> (JSON) = { data in return JSON(data: data) } //MARK: HTTP Methods private enum HTTPMethod: String { case GET, PUT, POST, DELETE } public final class Target { private static let background = ConcurrentDispatchQueueScheduler.init(globalConcurrentQueueQOS: .Background) public typealias Headers = [String: String] private let url: String private var session: NSURLSession private let retries: Int private let delay: Double private lazy var parameters: Array<NSURLQueryItem> = [] private lazy var headers: [String: String] = [:] init(url: String, session: NSURLSession, retries: Int, delay: Double) { self.url = url self.session = session self.retries = retries self.delay = delay } // MARK: Value collector methods public func header(name: String, value: String) -> Target { headers[name] = value return self } public func headers(headers: [String: String]) -> Target { for (name, value) in headers { self.headers[name] = value } return self } public func parameter(name: String, value: String) -> Target { parameters.append(NSURLQueryItem(name: name, value: value)) return self } public func parameters(parameters: [String: String]) -> Target { for (name, value) in parameters { self.parameters.append(NSURLQueryItem(name: name, value: value)) } return self } // TODO: // - add request body serializer support // MARK: RX request methods public func get() -> Observable < (JSON, [String: String]) > { return get(SwiftyJSONParser) } public func get<T>(parser: (NSData) throws -> T) -> Observable < (T, Headers) > { return parse(requestForMethod(.GET), parser: parser) } public func post(data: NSData) -> Observable < (String, Headers) > { return post(data, parser: UTF8StringParser) } public func post<T>(data: NSData, parser: NSData throws -> T) -> Observable < (T, Headers) > { return parse(requestForMethod(.POST, body: data), parser: parser) } public func put<T>(data: NSData, parser: (NSData) throws -> T) -> Observable < (T, Headers) > { return parse(requestForMethod(.PUT, body: data), parser: parser) } public func put(data: NSData) -> Observable < (String, Headers) > { return put(data, parser: UTF8StringParser) } public func delete<T>(parser: (NSData) throws -> T) -> Observable < (T, Headers) > { return parse(requestForMethod(.DELETE), parser: parser) } public func delete() -> Observable < (String, Headers) > { return delete(UTF8StringParser) } // MARK: Private private func parse<T>(request: NSURLRequest, parser: (NSData) throws -> T) -> Observable < (T, Headers) > { return self.request(request).observeOn(Target.background).map { data, http in return (try parser(data), http.headers()) } } private func request(request: NSURLRequest) -> Observable < (NSData, NSHTTPURLResponse) > { let observable = Observable < (NSData, NSHTTPURLResponse) > .create { observer in let task = self.session.dataTaskWithRequest(request) { data, response, error in // Communication Error guard let response = response, data = data else { observer.onError(FlowError.CommunicationError(error)) return } // Non Http Response Error guard let http = response as? NSHTTPURLResponse else { observer.onError(FlowError.NonHttpResponse(response)) return } // Unsupported Status Code Error guard http.isSuccessResponse() else { observer.onError(FlowError.UnsupportedStatusCode(http)) return } observer.onNext(data, http) observer.onCompleted() } task.resume() return AnonymousDisposable { task.cancel() } } // Only add retry handler if it is requested return retries == 0 ? observable : observable.retryWhen(retryHandler) } // See: http://blog.danlew.net/2016/01/25/rxjavas-repeatwhen-and-retrywhen-explained/ private func retryHandler(errors: Observable<ErrorType>) -> Observable<Int> { var attemptsLeft = self.retries return errors.flatMap { (error) -> Observable<Int> in if attemptsLeft <= 0 { return Observable.error(FlowError.RetryFailed(error, self.retries, attemptsLeft)) } switch error { case FlowError.CommunicationError(_), FlowError.UnsupportedStatusCode(_): NSThread.sleepForTimeInterval(self.delay) attemptsLeft -= 1 return Observable.just(0) default: return Observable.error(error) } } } private func requestForMethod(method: HTTPMethod, body: NSData? = nil) -> NSURLRequest { let urlComponent = NSURLComponents(string: url)! urlComponent.queryItems = parameters let request = NSMutableURLRequest(URL: urlComponent.URL!) request.allHTTPHeaderFields = headers request.HTTPMethod = method.rawValue request.HTTPBody = body return request } }
mit
9db6bd0a31739e96c0029b4d01a5e25d
31.549223
118
0.584779
4.801988
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/ErrorTextFieldValidator.swift
1
9728
/* * Copyright (C) 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Original Inspiration & Author * Copyright (C) 2018 Orkhan Alikhanov <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Motion /** Validator plugin for ErrorTextField and subclasses. Can be accessed via `textField.validator` ### Example ```swift field.validator .notEmpty(message: "Choose username") .min(length: 3, message: "Minimum 3 characters") .noWhitespaces(message: "Username cannot contain spaces") .username(message: "Unallowed characters in username") } ``` */ open class ErrorTextFieldValidator { /// A typealias for validation closure. public typealias ValidationClosure = (_ text: String) -> Bool /// Validation closures and their error messages. open var closures: [(code: ValidationClosure, message: String)] = [] /// A reference to the textField. open weak var textField: ErrorTextField? /// Behavior for auto-validation. open var autoValidationType: AutoValidationType = .default /** A flag indicating if error message is shown at least once. Used for `AutoValidationType.default`. */ open var isErrorShownOnce = false /** Initializes validator. - Parameter textField: An ErrorTextField to validate. */ public init(textField: ErrorTextField) { self.textField = textField prepare() } /** Prepares the validator instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { textField?.addTarget(self, action: #selector(autoValidate), for: .editingChanged) } /** Validates textField based on `autoValidationType`. This method is called when textField.text changes. */ @objc private func autoValidate() { guard let textField = textField else { return } switch autoValidationType { case .none: break case .custom(let closure): closure(textField) case .default: guard isErrorShownOnce else { return } textField.isValid() case .always: textField.isValid() } } /** Validates textField.text against criteria defined in `closures` and shows relevant error message on failure. - Parameter isDeferred: Defer showing error message. - Returns: Boolean indicating if validation passed. */ @discardableResult open func isValid(isDeferred: Bool) -> Bool { guard let textField = textField else { return false } for block in closures { if !block.code(textField.text ?? "") { if !isDeferred { textField.error = block.message textField.isErrorRevealed = true isErrorShownOnce = true } return false } } if !isDeferred { textField.isErrorRevealed = false } return true } /** Adds provided closure and its error message to the validation chain. - Parameter message: A message to be shown when validation fails. - Parameter code: Closure to run for validation. - Returns: Validator itself to allow chaining. */ @discardableResult open func validate(message: String, when code: @escaping ValidationClosure) -> Self { closures.append((code, message)) return self } /** Types for determining behaviour of auto-validation which is run when textField.text changes. */ public enum AutoValidationType { /// Turn off. case none /// Run validation only if error is shown once. case `default` /// Always run validation. case always /** Custom auto-validation logic passed as closure which accepts ErrorTextField. Closure is called when `textField.text` changes. */ case custom((ErrorTextField) -> Void) } } /// Memory key pointer for `validator`. private var AssociatedInstanceKey: UInt8 = 0 extension ErrorTextField { /// A reference to validator. open var validator: ErrorTextFieldValidator { get { return AssociatedObject.get(base: self, key: &AssociatedInstanceKey) { return ErrorTextFieldValidator(textField: self) } } set(value) { AssociatedObject.set(base: self, key: &AssociatedInstanceKey, value: value) } } /** Validates textField.text against criteria defined in `closures` and shows relevant error message on failure. - Parameter isDeferred: Defer showing error message. Default is false. - Returns: Boolean indicating if validation passed. */ @discardableResult open func isValid(isDeferred: Bool = false) -> Bool { return validator.isValid(isDeferred: isDeferred) } } public extension ErrorTextFieldValidator { /** Validate that field contains correct email address. - Parameter message: A message to show for incorrect emails. - Returns: Validator itself to allow chaining. */ @discardableResult func email(message: String) -> Self { return regex(message: message, pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}") } /** Validate that field contains allowed usernames characters. - Parameter message: A message to show for disallowed usernames. - Returns: Validator itself to allow chaining. */ @discardableResult func username(message: String) -> Self { return regex(message: message, pattern: "^[a-zA-Z0-9]+([_\\s\\-\\.\\']?[a-zA-Z0-9])*$") } /** Validate that field text matches provided regex pattern. - Parameter message: A message to show for unmatched texts. - Parameter pattern: A regex pattern to match. - Returns: Validator itself to allow chaining. */ @discardableResult func regex(message: String, pattern: String) -> Self { return validate(message: message) { let pred = NSPredicate(format: "SELF MATCHES %@", pattern) return pred.evaluate(with: $0) } } /** Validate that field text has minimum `length`. - Parameter length: Minimum allowed text length. - Parameter message: A message to show when requirement is not met. - Parameter trimmingSet: A trimming CharacterSet for trimming text before validation. - Returns: Validator itself to allow chaining. */ @discardableResult func min(length: Int, message: String, trimmingSet: CharacterSet? = .whitespacesAndNewlines) -> Self { let trimmingSet = trimmingSet ?? .init() return validate(message: message) { $0.trimmingCharacters(in: trimmingSet).count >= length } } /** Validate that field text has maximum `length`. - Parameter length: Minimum allowed text length. - Parameter message: A message to show when requirement is not met. - Parameter trimmingSet: A trimming CharacterSet for trimming text before validation. - Returns: Validator itself to allow chaining. */ @discardableResult func max(length: Int, message: String, trimmingSet: CharacterSet? = .whitespacesAndNewlines) -> Self { let trimmingSet = trimmingSet ?? .init() return validate(message: message) { $0.trimmingCharacters(in: trimmingSet).count <= length } } /** Validate that field text is not empty. - Parameter message: A message to show when requirement is not met. - Parameter trimmingSet: A trimming CharacterSet for trimming text before validation. - Returns: Validator itself to allow chaining. */ @discardableResult func notEmpty(message: String, trimmingSet: CharacterSet? = .whitespacesAndNewlines) -> Self { let trimmingSet = trimmingSet ?? .init() return validate(message: message) { $0.trimmingCharacters(in: trimmingSet).isEmpty == false } } /** Validate that field text contains no whitespaces. - Parameter message: A message to show when requirement is not met. - Parameter trimmingSet: A trimming CharacterSet for trimming text before validation. - Returns: Validator itself to allow chaining. */ @discardableResult func noWhitespaces(message: String) -> Self { return validate(message: message) { $0.rangeOfCharacter(from: .whitespaces) == nil } } }
bsd-3-clause
eb11ad14794b4ab60555a3fd79de8529
32.89547
104
0.701789
4.610427
false
false
false
false
hooman/swift
stdlib/public/core/UTF8.swift
3
12370
//===--- UTF8.swift -------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Unicode { @frozen public enum UTF8: Sendable { case _swift3Buffer(Unicode.UTF8.ForwardParser) } } extension Unicode.UTF8 { /// Returns the number of code units required to encode the given Unicode /// scalar. /// /// Because a Unicode scalar value can require up to 21 bits to store its /// value, some Unicode scalars are represented in UTF-8 by a sequence of up /// to 4 code units. The first code unit is designated a *lead* byte and the /// rest are *continuation* bytes. /// /// let anA: Unicode.Scalar = "A" /// print(anA.value) /// // Prints "65" /// print(UTF8.width(anA)) /// // Prints "1" /// /// let anApple: Unicode.Scalar = "🍎" /// print(anApple.value) /// // Prints "127822" /// print(UTF8.width(anApple)) /// // Prints "4" /// /// - Parameter x: A Unicode scalar value. /// - Returns: The width of `x` when encoded in UTF-8, from `1` to `4`. @_alwaysEmitIntoClient public static func width(_ x: Unicode.Scalar) -> Int { switch x.value { case 0..<0x80: return 1 case 0x80..<0x0800: return 2 case 0x0800..<0x1_0000: return 3 default: return 4 } } } extension Unicode.UTF8: _UnicodeEncoding { public typealias CodeUnit = UInt8 public typealias EncodedScalar = _ValidUTF8Buffer @inlinable public static var encodedReplacementCharacter: EncodedScalar { return EncodedScalar.encodedReplacementCharacter } @inline(__always) @inlinable public static func _isScalar(_ x: CodeUnit) -> Bool { return isASCII(x) } /// Returns whether the given code unit represents an ASCII scalar @_alwaysEmitIntoClient @inline(__always) public static func isASCII(_ x: CodeUnit) -> Bool { return x & 0b1000_0000 == 0 } @inline(__always) @inlinable public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { switch source.count { case 1: return Unicode.Scalar(_unchecked: source._biasedBits &- 0x01) case 2: let bits = source._biasedBits &- 0x0101 var value = (bits & 0b0_______________________11_1111__0000_0000) &>> 8 value |= (bits & 0b0________________________________0001_1111) &<< 6 return Unicode.Scalar(_unchecked: value) case 3: let bits = source._biasedBits &- 0x010101 var value = (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 16 value |= (bits & 0b0_______________________11_1111__0000_0000) &>> 2 value |= (bits & 0b0________________________________0000_1111) &<< 12 return Unicode.Scalar(_unchecked: value) default: _internalInvariant(source.count == 4) let bits = source._biasedBits &- 0x01010101 var value = (bits & 0b0_11_1111__0000_0000__0000_0000__0000_0000) &>> 24 value |= (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 10 value |= (bits & 0b0_______________________11_1111__0000_0000) &<< 4 value |= (bits & 0b0________________________________0000_0111) &<< 18 return Unicode.Scalar(_unchecked: value) } } @inline(__always) @inlinable public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { var c = source.value if _fastPath(c < (1&<<7)) { return EncodedScalar(_containing: UInt8(c)) } var o = c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<5)) { return EncodedScalar(_biasedBits: (o | c) &+ 0b0__1000_0001__1100_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<4)) { return EncodedScalar( _biasedBits: (o | c) &+ 0b0__1000_0001__1000_0001__1110_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 return EncodedScalar( _biasedBits: (o | c ) &+ 0b0__1000_0001__1000_0001__1000_0001__1111_0001) } @inlinable @inline(__always) public static func transcode<FromEncoding: _UnicodeEncoding>( _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type ) -> EncodedScalar? { if _fastPath(FromEncoding.self == UTF16.self) { let c = _identityCast(content, to: UTF16.EncodedScalar.self) var u0 = UInt16(truncatingIfNeeded: c._storage) if _fastPath(u0 < 0x80) { return EncodedScalar(_containing: UInt8(truncatingIfNeeded: u0)) } var r = UInt32(u0 & 0b0__11_1111) r &<<= 8 u0 &>>= 6 if _fastPath(u0 < (1&<<5)) { return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1100_0001) } r |= UInt32(u0 & 0b0__11_1111) r &<<= 8 if _fastPath(u0 & (0xF800 &>> 6) != (0xD800 &>> 6)) { u0 &>>= 6 return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1000_0001__1110_0001) } } else if _fastPath(FromEncoding.self == UTF8.self) { return _identityCast(content, to: UTF8.EncodedScalar.self) } return encode(FromEncoding.decode(content)) } @frozen public struct ForwardParser: Sendable { public typealias _Buffer = _UIntBuffer<UInt8> @inline(__always) @inlinable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } @frozen public struct ReverseParser: Sendable { public typealias _Buffer = _UIntBuffer<UInt8> @inline(__always) @inlinable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } } extension UTF8.ReverseParser: Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @inlinable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1110_0000__1100_0000 == 0b0__1100_0000__1000_0000 { // 2-byte sequence. Top 4 bits of decoded result must be nonzero let top4Bits = _buffer._storage & 0b0__0001_1110__0000_0000 if _fastPath(top4Bits != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1111_0000__1100_0000__1100_0000 == 0b0__1110_0000__1000_0000__1000_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000__0000_0000 if _fastPath( top5Bits != 0 && top5Bits != 0b0__1101__0010_0000__0000_0000) { return (true, 3*8) } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000__1000_0000 { // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000__0000_0000 if _fastPath( top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that ends with the LSB of /// buffer. @inline(never) @usableFromInline internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1111_0000__1100_0000 == 0b0__1110_0000__1000_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000 if top5Bits != 0 && top5Bits != 0b0__1101__0010_0000 { return 2 } } else if _buffer._storage & 0b1111_1000__1100_0000 == 0b1111_0000__1000_0000 { // 2-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000 { return 2 } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000 { // 3-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000 { return 3 } } return 1 } @inline(__always) @inlinable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(truncatingIfNeeded: _buffer._storage.byteSwapped) let shift = 32 &- bitCount return Encoding.EncodedScalar(_biasedBits: (x &+ 0x01010101) &>> shift) } } extension Unicode.UTF8.ForwardParser: Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @inlinable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1100_0000__1110_0000 == 0b0__1000_0000__1100_0000 { // 2-byte sequence. At least one of the top 4 bits of the decoded result // must be nonzero. if _fastPath(_buffer._storage & 0b0_0001_1110 != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1111_0000 == 0b0__1000_0000__1000_0000__1110_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0___0010_0000__0000_1111 if _fastPath(top5Bits != 0 && top5Bits != 0b0___0010_0000__0000_1101) { return (true, 3*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1100_0000__1111_1000 == 0b0__1000_0000__1000_0000__1000_0000__1111_0000 { // 4-byte sequence. The top 5 bits of the decoded result must be nonzero // and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if _fastPath( top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that starts with the LSB of /// buffer. @inline(never) @usableFromInline internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if _buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 { return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } @inlinable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(_buffer._storage) &+ 0x01010101 return _ValidUTF8Buffer(_biasedBits: x & ._lowBits(bitCount)) } }
apache-2.0
4f45b26acd3d19c7b3baeee5e448554d
36.819572
83
0.575807
3.688339
false
false
false
false
icetime17/CSSwiftExtension
Sources/UIKit+CSExtension/UIApplication+CSExtension.swift
1
1968
// // UIApplication+CSExtension.swift // CSSwiftExtension // // Created by Chris Hu on 16/12/25. // Copyright © 2016年 com.icetime17. All rights reserved. // import UIKit // MARK: - UIApplication public extension CSSwift where Base: UIApplication { // cs.appDelegate: current AppDelegate var appDelegate: UIApplicationDelegate { return UIApplication.shared.delegate! } // cs.currentViewController: current UIViewController var currentViewController: UIViewController { let window = self.appDelegate.window var viewController = window!!.rootViewController while ((viewController?.presentedViewController) != nil) { viewController = viewController?.presentedViewController if ((viewController?.isKind(of: UINavigationController.classForCoder())) == true) { viewController = (viewController as! UINavigationController).visibleViewController } else if ((viewController?.isKind(of: UITabBarController.classForCoder())) == true) { viewController = (viewController as! UITabBarController).selectedViewController } } return viewController! } } // MARK: - App Version Related public extension CSSwift where Base: UIApplication { // cs.appVersion: current App Version var appVersion: String { let infoDict = Bundle.main.infoDictionary! as Dictionary<String, AnyObject> return infoDict["CFBundleShortVersionString"] as! String } } // MARK: - snapShot public extension CSSwift where Base: UIApplication { func snapShot(_ inView: UIView) -> UIImage { UIGraphicsBeginImageContext(inView.bounds.size) inView.layer.render(in: UIGraphicsGetCurrentContext()!) let snapShot: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return snapShot } }
mit
468537384dfd46ad646a9e4edde4a8d2
28.772727
98
0.672774
5.712209
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Tools/Category/UIBUtton+Extension.swift
1
3221
// // UIBUtton+Extension.swift // chart2 // // Created by i-Techsys.com on 16/12/7. // Copyright © 2016年 i-Techsys. All rights reserved. // import UIKit extension UIButton { /// 遍历构造函数 convenience init(imageName:String, bgImageName:String){ self.init() // 1.设置按钮的属性 // 1.1图片 setImage(UIImage(named: imageName), for: .normal) setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) // 1.2背景 setBackgroundImage(UIImage(named: bgImageName), for: .normal) setBackgroundImage(UIImage(named: bgImageName + "_highlighted"), for: .highlighted) // 2.设置尺寸 sizeToFit() } convenience init(imageName:String, target:AnyObject, action:Selector) { self.init() // 1.设置按钮的属性 setImage(UIImage(named: imageName), for: .normal) setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } convenience init(image:UIImage?,highlightedImage: UIImage?,title: String?, target:AnyObject, action:Selector) { self.init(title: title ?? "", target: target, action: action) // 1.设置按钮的属性 setImage(image, for: .normal) if highlightedImage != nil { setImage(highlightedImage, for: .selected) } // showsTouchWhenHighlighted = true titleLabel?.font = UIFont.systemFont(ofSize: 17) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } convenience init(title:String, target:AnyObject, action:Selector) { self.init() setTitle(title, for: UIControl.State.normal) sizeToFit() addTarget(target, action: action, for: .touchUpInside) } convenience init(imageName:String, title: String, target:AnyObject, action:Selector) { self.init() // 1.设置按钮的属性 setImage(UIImage(named: imageName), for: .normal) // setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) setTitle(title, for: UIControl.State.normal) showsTouchWhenHighlighted = true titleLabel?.font = UIFont.systemFont(ofSize: 17) setTitleColor(UIColor.darkGray, for: UIControl.State.normal) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } convenience init(image: UIImage, title: String, target:AnyObject, action:Selector) { self.init() // 1.设置按钮的属性 setImage(image, for: .normal) // setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) setTitle(title, for: UIControl.State.normal) showsTouchWhenHighlighted = true titleLabel?.font = UIFont.systemFont(ofSize: 17) setTitleColor(UIColor.darkGray, for: UIControl.State.normal) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } }
mit
88ef22c225b64a9fc86b9a935add7cbe
32.376344
115
0.60857
4.396601
false
false
false
false
Aaron-zheng/yugioh
yugioh/BattleView.swift
1
2960
// // BattleView.swift // yugioh // // Created by Aaron on 31/12/2018. // Copyright © 2018 sightcorner. All rights reserved. // import Foundation import UIKit class BattleView: UIView { private var deckService = DeckService() private var result: [DeckEntity] = [] private var original: [String] = [] private var imgArray: [UIImageView] = [] @IBOutlet var contentView: UIView! @IBOutlet weak var button: UIButton! override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { Bundle.main.loadNibNamed("BattleView", owner: self, options: nil) self.addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] let img = UIImage(named: "ic_view_carousel_white")?.withRenderingMode(.alwaysTemplate) button.setImage(img, for: .normal) button.tintColor = UIColor.white button.layer.cornerRadius = 25 button.backgroundColor = redColor self.contentView.backgroundColor = greyColor } func initialCard() { for each in imgArray { each.removeFromSuperview() } original = [] imgArray = [] result = deckService.list()["0"]! for each in result { for _ in 0 ..< each.number { original.append(each.id) } } } @IBAction func clickButtonHandler(_ sender: UIButton) { if original.count <= 0 { return } let randomIndex = Int(arc4random_uniform(UInt32(original.count))) let val: String = original[randomIndex] original.remove(at: randomIndex) let imgView = UIImageView(frame: CGRect(x: 64 + (40 - original.count) * 4, y: Int(self.frame.height - 160), width: 50, height: 72)) // let imgView = UIImageView(frame: CGRect(x: 150, y: 40, width: 50, height: 72)) setImage(card: imgView, id: val) var panGesture = UIPanGestureRecognizer() panGesture = UIPanGestureRecognizer(target: self, action: #selector(BattleView.draggedView(_:))) imgView.isUserInteractionEnabled = true imgView.addGestureRecognizer(panGesture) self.addSubview(imgView) imgArray.append(imgView) } @objc func draggedView(_ sender:UIPanGestureRecognizer){ let viewDrag = sender.view! self.bringSubviewToFront(viewDrag) let translation = sender.translation(in: self) viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y) sender.setTranslation(CGPoint.zero, in: self) } }
agpl-3.0
48caacaebd0a8056a7cfac3a454bcbe6
28.888889
139
0.596485
4.59472
false
false
false
false
wondervictor/Doooge
My Doooge/Transition.swift
1
2438
// // Transition.swift // Doooge // // Created by VicChan on 2016/11/22. // Copyright © 2016年 VicChan. All rights reserved. // import UIKit class Transition: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.2 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let destView = transitionContext.view(forKey: .to)! let fromView = transitionContext.view(forKey: .from)! let bounds = fromView.bounds let startFrame = bounds.offsetBy(dx: 2 * bounds.width, dy: 0) destView.frame = startFrame transitionContext.containerView.addSubview(destView) let endFromViewFrame = bounds.offsetBy(dx: -bounds.width, dy: 0) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options:.curveLinear, animations: { fromView.frame = endFromViewFrame destView.frame = bounds }){ (finished) in if finished { transitionContext.completeTransition(true) } } } } class BackTransition: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let destView = transitionContext.view(forKey: .to)! let fromView = transitionContext.view(forKey: .from)! let bounds = fromView.bounds let endFrame = bounds.offsetBy(dx: 2 * bounds.width, dy: 0) destView.frame = bounds.offsetBy(dx: -bounds.width, dy: 0) transitionContext.containerView.addSubview(destView) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options:.curveLinear, animations: { destView.frame = bounds fromView.frame = endFrame }){ (finished) in if finished { transitionContext.completeTransition(true) } } } }
apache-2.0
abdba4b46d68b709ac5849a040d5a516
31.905405
186
0.651745
5.387168
false
false
false
false
blackspotbear/MMDViewer
MMDViewer/PMXUpdater.swift
1
655
import Foundation import CoreGraphics class PMXUpdater: Updater { var playing = true var angularVelocity = CGPoint(x: 0, y: 0) let pmxObj: PMXObject init(pmxObj: PMXObject) { self.pmxObj = pmxObj } func update(_ dt: CFTimeInterval, renderer: Renderer, node: Node) { if dt > 0 { pmxObj.rotationX += Float(angularVelocity.y * CGFloat(dt)) pmxObj.rotationY += Float(angularVelocity.x * CGFloat(dt)) angularVelocity.x *= 0.95 angularVelocity.y *= 0.95 } if playing { pmxObj.updateCounter() } pmxObj.calc(renderer) } }
mit
17db62017a92454fdafad94edd6c9bd2
23.259259
71
0.581679
3.993902
false
false
false
false
damicreabox/Coconut
Sources/Coconut/Gtk/LayoutBuilder.swift
1
2485
// // LayoutBuilder.swift // Sample-coconut // // Created by Dami on 10/11/2016. // // import Foundation import CGtk public class LayoutBuilder { public var container: View? = nil private var views = [View]() private var constraints = [LayoutConstraint]() public func add(views: [View]) { for view in views { self.views.append(view) } } public func add(constraints: [LayoutConstraint]) { for constraint in constraints { self.constraints.append(constraint) } } private func createFixedLayout(container: View) -> UnsafeMutablePointer<GtkWidget>? { // Create fixed container let widget = gtk_fixed_new() // Aprse views for view in self.views { // Redraw if let subWidget = view.redraw(widget: widget!) { // Covert point let origin = convertPoint(point: view.frame.origin, frame: container.frame) let fixed = toFixed(widget: widget) // Atache element gtk_fixed_put (fixed, subWidget, 0, 0) gtk_fixed_move(fixed, subWidget, Int32(origin.x), Int32(origin.y)) } } return widget } private func createConstraintsLayout(container: View) -> UnsafeMutablePointer<GtkWidget>? { /* Here we construct the container that is going pack our buttons */ let widget = gtk_grid_new () // Parse views var index : Int32 = 0 for view in self.views { // Redraw if let subWidget = view.redraw(widget: widget!) { // Atache element gtk_grid_attach (toGrid(widget: widget), subWidget, 1, index, 2, 1) } // Add index index = index + 1 } return widget } public func build() -> UnsafeMutablePointer<GtkWidget>? { guard let container = container else { return nil } // Test constraints let constraints = self.constraints if (constraints.isEmpty) { return createFixedLayout(container: container) } else { return createConstraintsLayout(container: container) } } }
apache-2.0
c6b9fdfa2b6469cefffbabc2c24ea4fc
25.43617
95
0.514688
5.020202
false
false
false
false
LeLuckyVint/MessageKit
Sources/Views/Cells/TextMessageCell.swift
1
3120
/* MIT License Copyright (c) 2017 MessageKit 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 open class TextMessageCell: MessageCollectionViewCell<MessageLabel> { open override class func reuseIdentifier() -> String { return "messagekit.cell.text" } // MARK: - Properties open override weak var delegate: MessageCellDelegate? { didSet { messageContentView.delegate = delegate } } override var messageTapGesture: UITapGestureRecognizer? { didSet { messageTapGesture?.delegate = messageContentView } } // MARK: - Methods open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) guard let attributes = layoutAttributes as? MessagesCollectionViewLayoutAttributes else { return } messageContentView.textInsets = attributes.messageLabelInsets messageContentView.font = attributes.messageLabelFont } open override func prepareForReuse() { super.prepareForReuse() messageContentView.attributedText = nil messageContentView.text = nil } open override func configure(with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) { super.configure(with: message, at: indexPath, and: messagesCollectionView) if let displayDelegate = messagesCollectionView.messagesDisplayDelegate as? TextMessageDisplayDelegate { let textColor = displayDelegate.textColor(for: message, at: indexPath, in: messagesCollectionView) let detectors = displayDelegate.enabledDetectors(for: message, at: indexPath, in: messagesCollectionView) messageContentView.textColor = textColor messageContentView.enabledDetectors = detectors } switch message.data { case .text(let text), .emoji(let text): messageContentView.text = text case .attributedText(let text): messageContentView.attributedText = text default: break } } }
mit
e115a3a6e6d01d9fe5e53856e21ff0d3
38
138
0.724679
5.388601
false
false
false
false
johndpope/Cerberus
Cerberus/Classes/MainViewController.swift
1
5167
import UIKit import EventKit import EventKitUI import Timepiece class MainViewController: UIViewController, EKCalendarChooserDelegate { weak var timelineCollectionViewController: TimelineCollectionViewController? weak var eventsCollectionViewController: EventsCollectionViewController? var calendarChooser: EKCalendarChooser! private var kvoContextForTimelineCollectionViewController = "kvoContextForTimelineCollectionViewController" private var kvoContextForEventsCollectionViewController = "kvoContextForEventsCollectionViewController" private let contentOffsetKeyPath = "contentOffset" deinit { self.timelineCollectionViewController?.removeObserver(self, forKeyPath: contentOffsetKeyPath) self.eventsCollectionViewController?.removeObserver(self, forKeyPath: contentOffsetKeyPath) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segue.destinationViewController { case let timelineCollectionViewController as TimelineCollectionViewController: self.timelineCollectionViewController = timelineCollectionViewController self.timelineCollectionViewController?.collectionView?.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .New, context: &kvoContextForTimelineCollectionViewController) case let eventsCollectionViewController as EventsCollectionViewController: self.eventsCollectionViewController = eventsCollectionViewController self.eventsCollectionViewController?.collectionView?.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .New, context: &kvoContextForEventsCollectionViewController) default: break } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.setBackgroundImage(UIImage(named: "background"), forBarMetrics: UIBarMetrics.Default) navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(24)] updateNavigationBarTitle() NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationSignificantTimeChange:", name: UIApplicationSignificantTimeChangeNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if self.calendarChooser == nil { presentCalendarChooser() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Private private func updateNavigationBarTitle() { let now = NSDate() title = now.stringFromFormat("EEEE, MMMM d, yyyy") } private func presentCalendarChooser() { self.calendarChooser = EKCalendarChooser( selectionStyle: EKCalendarChooserSelectionStyleSingle, displayStyle: EKCalendarChooserDisplayAllCalendars, entityType: EKEntityTypeEvent, eventStore: EKEventStore() ) self.calendarChooser.delegate = self let navigationController = UINavigationController(rootViewController: self.calendarChooser) self.presentViewController(navigationController, animated: true, completion: nil) } // MARK: EKCalendarChooserDelegate func calendarChooserSelectionDidChange(calendarChooser: EKCalendarChooser!) { var calendars: [EKCalendar] = [] if let selectedCalendarsSet = calendarChooser.selectedCalendars as? Set<EKCalendar> { calendars = Array(selectedCalendarsSet) } NSNotificationCenter.defaultCenter().postNotificationName(NotifictionNames.CalendarModelDidChooseCalendarNotification.rawValue, object: calendars) self.dismissViewControllerAnimated(true, completion: nil) } // MARK: UIApplicationNotification func applicationSignificantTimeChange(notification: NSNotification) { updateNavigationBarTitle() } // MARK: Key Value Observing override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { var anotherCollectionViewController: UICollectionViewController? switch context { case &kvoContextForEventsCollectionViewController: anotherCollectionViewController = self.timelineCollectionViewController case &kvoContextForTimelineCollectionViewController: anotherCollectionViewController = self.eventsCollectionViewController default: return } if keyPath != contentOffsetKeyPath { return } if let anotherCollectionView = anotherCollectionViewController?.collectionView { if let point = change["new"] as? NSValue { let y = point.CGPointValue().y if anotherCollectionView.contentOffset.y != y { anotherCollectionView.contentOffset.y = y } } } } }
mit
7ba64ef48a705995485eb840222201ac
39.692913
190
0.730792
6.52399
false
false
false
false
josherick/DailySpend
DailySpend/ExpenseView.swift
1
21816
// // ExpenseView.swift // DailySpend // // Created by Josh Sherick on 6/29/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import UIKit class ExpenseView: UIView { var scrollView: UIScrollView = UIScrollView() var amountLabel = UIButton(type: .custom) var descriptionLabel = UIButton(type: .custom) var dateLabel = UIButton(type: .custom) var notesLabel = UIButton(type: .custom) var imageLabel = UIButton(type: .custom) var amountField = BorderedTextField() var descriptionField = BorderedTextField() var dateField = BorderedTextField() var notesField = BorderedTextField() var imageSelector: ImageSelectorView = ImageSelectorView() var delegate: ExpenseViewDelegate! var dataSource: ExpenseViewDataSource! var keyboardHeight: CGFloat? var editing = false var dismissButton: UIButton? override func layoutSubviews() { super.layoutSubviews() updateSubviewFrames() } init(optionalCoder: NSCoder? = nil, optionalFrame: CGRect? = nil) { if let coder = optionalCoder { super.init(coder: coder)! } else if let frame = optionalFrame { super.init(frame: frame) } else { super.init() } // Scroll view is only for scrolling when the keyboard is on screen. scrollView.bounces = false let lightFont = UIFont(name: "HelveticaNeue-Light", size: 24.0) let normalFont = UIFont(name: "HelveticaNeue", size: 24.0) let borderColor = UIColor(red255: 181, green: 186 , blue: 194) let borderWidth: CGFloat = 1.0 func setup(button: UIButton, _ text: String, touchUpInside: (() -> ())? = nil) { button.setTitle(text, for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.titleLabel?.font = normalFont if touchUpInside != nil { button.add(for: .touchUpInside, touchUpInside!) } } func setup(field: BorderedTextField, _ tag: Int, text: String? = nil, placeholder: String? = nil) { field.tag = tag field.text = text if text != nil { field.textColor = self.tintColor } field.textAlignment = .right field.placeholder = placeholder field.font = lightFont field.clipsToBounds = false //field.addBottomBorder(color: borderColor, width: borderWidth) field.delegate = self } // Set up visuals of all fields and labels. setup(button: amountLabel, "Amount") { self.uiElementInteraction() self.amountField.becomeFirstResponder() } setup(field: amountField, 1, placeholder: "$0.00") amountField.keyboardType = .numberPad amountField.addTarget(self, action: #selector(amountChanged(_:)), for: .editingChanged) setup(button: descriptionLabel, "Description") { self.uiElementInteraction() self.descriptionField.becomeFirstResponder() } setup(field: descriptionField, 2, placeholder: "Description") descriptionField.addTarget(self, action: #selector(descriptionChanged(_:)), for: .editingChanged) setup(button: dateLabel, "Date") { self.uiElementInteraction() self.showDatePicker() } setup(field: dateField, 3, text: "Today") setup(button: notesLabel, "Notes") { self.uiElementInteraction() self.showNotes() } setup(field: notesField, 4, text: "View/Edit") setup(button: imageLabel, "Receipt") imageSelector.selectorDelegate = self // Add all subviews to scroll view. scrollView.addSubviews([amountLabel, descriptionLabel, dateLabel, notesLabel, imageLabel, amountField, descriptionField, dateField, notesField, imageSelector]) self.addSubview(scrollView) updateSubviewFrames() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name:NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) } required convenience init(coder: NSCoder) { self.init(optionalCoder: coder) } override convenience init(frame: CGRect) { self.init(optionalFrame: frame) } func updateSubviewFrames() { let sideMargin: CGFloat = 16.0 let innerHorizontalMargin: CGFloat = 10.0 let innerVerticalMargin: CGFloat = 26.0 let newWidth = bounds.size.width func setFrameForButton(_ button: UIButton, previousButton: UIButton?) { let attr = [NSAttributedStringKey.font: button.titleLabel!.font!] let size = button.titleLabel!.text!.size(withAttributes: attr) button.frame = CGRect( x: sideMargin, y: previousButton == nil ? sideMargin : previousButton!.frame.bottomEdge + innerVerticalMargin, width: size.width, height: button.intrinsicContentSize.height ) } func setFramesForPair(button: UIButton, field: UITextField, previousButton: UIButton?) { setFrameForButton(button, previousButton: previousButton) field.frame = CGRect( x: button.frame.rightEdge + innerHorizontalMargin, y: button.frame.topEdge, width: newWidth - button.frame.rightEdge - sideMargin - innerHorizontalMargin, height: button.frame.size.height ) } scrollView.frame = bounds setFramesForPair(button: amountLabel, field: amountField, previousButton: nil) setFramesForPair(button: descriptionLabel, field: descriptionField, previousButton: amountLabel) setFramesForPair(button: dateLabel, field: dateField, previousButton: descriptionLabel) setFramesForPair(button: notesLabel, field: notesField, previousButton: dateLabel) setFrameForButton(imageLabel, previousButton: notesLabel) let imageSelectorHeight: CGFloat = 94.0 let oldFrame = imageSelector.frame let newFrame = CGRect( x: imageLabel.frame.rightEdge + innerHorizontalMargin, y: imageLabel.center.y - (imageSelectorHeight / 2), width: newWidth - imageLabel.frame.rightEdge - sideMargin - innerHorizontalMargin, height: imageSelectorHeight ) if oldFrame != newFrame { imageSelector.frame = newFrame if oldFrame.size.width != newFrame.size.width { imageSelector.recreateButtons() } } scrollView.contentSize = CGSize(width: newWidth, height: imageSelector.frame.bottomEdge) } func updateFieldValues() { // Populate text fields with expense data from dataSource if let amount = dataSource.amount { let amt = String.formatAsCurrency(amount: amount) self.amountField.text = amt } else { self.amountField.text = nil } descriptionField.text = dataSource.shortDescription self.descriptionChanged(descriptionField) dateField.text = humanReadableDate(dataSource.calDay) self.imageSelector.removeAllImages() if let containers = dataSource.imageContainers { // Add all images to image selector. for imageContainer in containers { self.imageSelector.addImage(image: imageContainer.image, imageName: imageContainer.imageName, imageType: imageContainer.imageType) } } // Scroll imageSelector to far right let selectorContentWidth = self.imageSelector.contentSize.width let selectorFrameWidth = self.imageSelector.frame.size.width self.imageSelector.contentOffset = CGPoint(x: selectorContentWidth - selectorFrameWidth, y: 0) } @objc func save() { if dataSource.amount == nil || dataSource.amount!.doubleValue <= 0 || dataSource.shortDescription!.count == 0 { let message = "Please enter values for amount and description." let alert = UIAlertController(title: "Invalid Fields", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) delegate.present(alert, animated: true, completion: nil, sender: self) return } if let expense = dataSource.save() { editing = false resignTextFieldsAsFirstResponder() dismissButton?.removeFromSuperview() delegate.popRightBBI(sender: self) delegate.popLeftBBI(sender: self) delegate.didEndEditing(sender: self, expense: expense) return } // There was an error. let message = "There was an error saving your expense. " + "If this occurs again, please contact support explaining what happened." let alert = UIAlertController(title: "Error Adding Expense", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil)) delegate?.present(alert, animated: true, completion: nil, sender: self) } @objc func cancel() { resignTextFieldsAsFirstResponder() dismissButton?.removeFromSuperview() delegate.popRightBBI(sender: self) delegate.popLeftBBI(sender: self) delegate.didEndEditing(sender: self, expense: nil) editing = false } func uiElementInteraction() { if !editing { editing = true delegate.didBeginEditing(sender: self) // Add save and cancel bar button items. let saveButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(save)) let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel)) delegate.pushRightBBI(saveButton, sender: self) delegate.pushLeftBBI(cancelButton, sender: self) // Make sure that "today" is set to today. dataSource.setDayToToday() updateFieldValues() } } func humanReadableDate(_ day: CalendarDay) -> String { if day == CalendarDay() { return "Today" } else if day == CalendarDay().subtract(days: 1) { return "Yesterday" } else { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .none return day.string(formatter: dateFormatter) } } // Possibly need @escaping here and not making the function an optional // if there are issues? func insertDismissButton(removeOnPress: Bool = true, under: UIView? = nil, dismiss handler: (() -> Void)?) { dismissButton?.removeFromSuperview() dismissButton = UIButton(frame: scrollView.bounds) dismissButton!.backgroundColor = UIColor.clear dismissButton!.add(for: .touchUpInside) { if removeOnPress == true { self.dismissButton!.removeFromSuperview() } handler?() } scrollView.insertSubview(dismissButton!, belowSubview: under ?? amountField) } @objc func keyboardWillChangeFrame(notification: NSNotification) { let key = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] if let frame = (key as? NSValue)?.cgRectValue { keyboardHeight = frame.size.height } } } extension ExpenseView: ImageSelectorDelegate { func present(_ vc: UIViewController, animated: Bool, completion: (() -> Void)?, sender: Any?) { delegate.present(vc, animated: true, completion: completion, sender: sender) } func addedImage(_ image: UIImage, imageName: String, imageType: String?) { let container = ImageContainer(image: image, imageName: imageName, imageType: imageType, saved: false) dataSource.addImage(container: container) } func removedImage(index: Int) { dataSource.removeImage(index: index) } func tappedButton() { uiElementInteraction() } } extension ExpenseView: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { uiElementInteraction() switch textField.tag { case 1...2: // amountField or descriptionField insertDismissButton { textField.resignFirstResponder() } return true case 3: // dateField resignTextFieldsAsFirstResponder() showDatePicker() return false case 4: // notesField resignTextFieldsAsFirstResponder() showNotes() return false default: return true } } func resignTextFieldsAsFirstResponder() { amountField.resignFirstResponder() descriptionField.resignFirstResponder() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func showDatePicker() { let datePicker = UIDatePicker() datePicker.timeZone = CalendarDay.gmtTimeZone datePicker.backgroundColor = UIColor.white datePicker.minimumDate = nil datePicker.maximumDate = Date() datePicker.setDate(dataSource.calDay.gmtDate, animated: false) datePicker.datePickerMode = .date datePicker.frame = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: datePicker.intrinsicContentSize.height) datePicker.add(for: .valueChanged) { // Grab the selected date from the date picker. self.dataSource.calDay = CalendarDay(dateInGMTDay: datePicker.date) self.dateField.text = self.humanReadableDate(self.dataSource.calDay) } addSubview(datePicker) func animateDismiss() { // Animate slide down. UIView.animate(withDuration: 0.2, animations: { self.delegate.popRightBBI(sender: self) self.delegate.popLeftBBI(sender: self) let pickerHeight = datePicker.frame.height datePicker.frame = datePicker.frame.offsetBy(dx: 0, dy: pickerHeight) self.dismissButton!.frame = self.bounds self.dismissButton!.backgroundColor = UIColor.clear }, completion: { (finished: Bool) in datePicker.removeFromSuperview() self.dismissButton?.removeFromSuperview() }) } insertDismissButton(removeOnPress: false, under: datePicker, dismiss: animateDismiss) // Wrap cancel and save buttons with a dismiss call to dismiss the date // picker. let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel) { animateDismiss() self.cancel() } let saveButton = UIBarButtonItem(barButtonSystemItem: .save) { animateDismiss() self.save() } delegate.pushLeftBBI(cancelButton, sender: self) delegate.pushRightBBI(saveButton, sender: self) // Animate slide up. UIView.animate(withDuration: 0.2) { let pickerHeight = datePicker.frame.height datePicker.frame = datePicker.frame.offsetBy(dx: 0, dy: -pickerHeight) let h = self.bounds.size.height - datePicker.frame.size.height let w = self.bounds.width let bgColor = UIColor(red255: 0, green: 0, blue: 0, alpha: 0.1) self.dismissButton!.backgroundColor = bgColor self.dismissButton!.frame = CGRect(x: 0, y: 0, width: w, height: h) } } func showNotes() { let notesView = UITextView() notesView.text = dataSource.notes notesView.isEditable = true notesView.font = UIFont.systemFont(ofSize: 24) let grey = UIColor(red255: 245, green: 245, blue: 245) notesView.backgroundColor = grey notesView.frame = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height) scrollView.addSubview(notesView) func animateDismiss() { UIView.animate(withDuration: 0.25, animations: { let f = notesView.frame.offsetBy(dx: 0, dy: self.bounds.size.height) notesView.frame = f }, completion: { (completed: Bool) in notesView.removeFromSuperview() self.delegate.popLeftBBI(sender: self) self.delegate.popRightBBI(sender: self) }) } let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel) { notesView.resignFirstResponder() animateDismiss() } let doneButton = UIBarButtonItem(barButtonSystemItem: .done) { self.dataSource.notes = notesView.text notesView.resignFirstResponder() animateDismiss() } delegate.pushLeftBBI(cancelButton, sender: self) delegate.pushRightBBI(doneButton, sender: self) UIView.animate(withDuration: 0.25, animations: { let h = self.bounds.size.height - (self.keyboardHeight ?? 216) notesView.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: h) }) notesView.becomeFirstResponder() } @objc func amountChanged(_ sender: UITextField) { let amount = sender.text!.parseValidAmount(maxLength: 8) self.dataSource.amount = Decimal(amount) sender.text = String.formatAsCurrency(amount: amount) } @objc func descriptionChanged(_ sender: UITextField) { self.dataSource.shortDescription = sender.text! descriptionField.resizeFontToFit(desiredFontSize: 24, minFontSize: 17) } } protocol ExpenseViewDelegate: class { /* * Called after editing has begun. * e.g. the user interacted with an element within the ExpenseView. */ func didBeginEditing(sender: ExpenseView) /* * Called after editing has finished. * e.g. the user pressed the save or cancel button. * shouldDismiss is true if the parent view should dimiss, false otherwise. */ func didEndEditing(sender: ExpenseView, expense: Expense?) /* * Asks the delegate to present a view controller. */ func present(_ vc: UIViewController, animated: Bool, completion: (() -> Void)?, sender: Any?) /* * Asks the delegate to set the right bar button item of the navigation * item. * The delgate is responsible for maintaining a stack of bar button items * to swap out when push and pop are called. */ func pushRightBBI(_ bbi: UIBarButtonItem, sender: Any?) func popRightBBI(sender: Any?) /* * Asks the delegate to set the left bar button item of the navigation * item. * The delgate is responsible for maintaining a stack of bar button items * to swap out when push and pop are called. */ func pushLeftBBI(_ bbi: UIBarButtonItem, sender: Any?) func popLeftBBI(sender: Any?) /* * Asks the delegate to disable or enable the right bar button item. */ func disableRightBBI(sender: Any?) func enableRightBBI(sender: Any?) /* * Asks the delegate to disable or enable the left bar button item. */ func disableLeftBBI(sender: Any?) func enableLeftBBI(sender: Any?) }
mit
74206095c655e46fe988edf145378dd6
36.226962
97
0.571442
5.382433
false
false
false
false
kierangraham/SwiftCoAP
SwiftCoAP_Library/SCMessage.swift
3
30516
// // SCMessage.swift // SwiftCoAP // // Created by Wojtek Kordylewski on 22.04.15. // Copyright (c) 2015 Wojtek Kordylewski. All rights reserved. // import UIKit //MARK: //MARK: SC Type Enumeration: Represents the CoAP types enum SCType: Int { case Confirmable, NonConfirmable, Acknowledgement, Reset func shortString() -> String { switch self { case .Confirmable: return "CON" case .NonConfirmable: return "NON" case .Acknowledgement: return "ACK" case .Reset: return "RST" } } static func fromShortString(string: String) -> SCType? { switch string.uppercaseString { case "CON": return .Confirmable case "NON": return .NonConfirmable case "ACK": return .Acknowledgement case "RST": return .Reset default: return nil } } } //MARK: //MARK: SC Option Enumeration: Represents the CoAP options enum SCOption: Int { case IfMatch = 1 case UriHost = 3 case Etag = 4 case IfNoneMatch = 5 case Observe = 6 case UriPort = 7 case LocationPath = 8 case UriPath = 11 case ContentFormat = 12 case MaxAge = 14 case UriQuery = 15 case Accept = 17 case LocationQuery = 20 case Block2 = 23 case Block1 = 27 case Size2 = 28 case ProxyUri = 35 case ProxyScheme = 39 case Size1 = 60 static let allValues = [IfMatch, UriHost, Etag, IfNoneMatch, Observe, UriPort, LocationPath, UriPath, ContentFormat, MaxAge, UriQuery, Accept, LocationQuery, Block2, Block1, Size2, ProxyUri, ProxyScheme, Size1] enum Format { case Empty, Opaque, UInt, String } func toString() -> String { switch self { case .IfMatch: return "If_Match" case .UriHost: return "URI_Host" case .Etag: return "ETAG" case .IfNoneMatch: return "If_None_Match" case .Observe: return "Observe" case .UriPort: return "URI_Port" case .LocationPath: return "Location_Path" case .UriPath: return "URI_Path" case .ContentFormat: return "Content_Format" case .MaxAge: return "Max_Age" case .UriQuery: return "URI_Query" case .Accept: return "Accept" case .LocationQuery: return "Location_Query" case .Block2: return "Block2" case .Block1: return "Block1" case .Size2: return "Size2" case .ProxyUri: return "Proxy_URI" case .ProxyScheme: return "Proxy_Scheme" case .Size1: return "Size1" } } static func isNumberCritical(optionNo: Int) -> Bool { return optionNo % 2 == 1 } func isCritical() -> Bool { return SCOption.isNumberCritical(self.rawValue) } static func isNumberUnsafe(optionNo: Int) -> Bool { return optionNo & 0b10 == 0b10 } func isUnsafe() -> Bool { return SCOption.isNumberUnsafe(self.rawValue) } static func isNumberNoCacheKey(optionNo: Int) -> Bool { return optionNo & 0b11110 == 0b11100 } func isNoCacheKey() -> Bool { return SCOption.isNumberNoCacheKey(self.rawValue) } static func isNumberRepeatable(optionNo: Int) -> Bool { switch optionNo { case SCOption.IfMatch.rawValue, SCOption.Etag.rawValue, SCOption.LocationPath.rawValue, SCOption.UriPath.rawValue, SCOption.UriQuery.rawValue, SCOption.LocationQuery.rawValue: return true default: return false } } func isRepeatable() -> Bool { return SCOption.isNumberRepeatable(self.rawValue) } func format() -> Format { switch self { case .IfNoneMatch: return .Empty case .IfMatch, .Etag: return .Opaque case .UriHost, .LocationPath, .UriPath, .UriQuery, .LocationQuery, .ProxyUri, .ProxyScheme: return .String default: return .UInt } } } //MARK: //MARK: SC Code Sample Enumeration: Provides the most common CoAP codes as raw values enum SCCodeSample: Int { case Empty = 0 case Get = 1 case Post = 2 case Put = 3 case Delete = 4 case Created = 65 case Deleted = 66 case Valid = 67 case Changed = 68 case Content = 69 case Continue = 95 case BadRequest = 128 case Unauthorized = 129 case BadOption = 130 case Forbidden = 131 case NotFound = 132 case MethodNotAllowed = 133 case NotAcceptable = 134 case RequestEntityIncomplete = 136 case PreconditionFailed = 140 case RequestEntityTooLarge = 141 case UnsupportedContentFormat = 143 case InternalServerError = 160 case NotImplemented = 161 case BadGateway = 162 case ServiceUnavailable = 163 case GatewayTimeout = 164 case ProxyingNotSupported = 165 func codeValue() -> SCCodeValue! { return SCCodeValue.fromCodeSample(self) } func toString() -> String { switch self { case .Empty: return "Empty" case .Get: return "Get" case .Post: return "Post" case .Put: return "Put" case .Delete: return "Delete" case .Created: return "Created" case .Deleted: return "Deleted" case .Valid: return "Valid" case .Changed: return "Changed" case .Content: return "Content" case .Continue: return "Continue" case .BadRequest: return "Bad Request" case .Unauthorized: return "Unauthorized" case .BadOption: return "Bad Option" case .Forbidden: return "Forbidden" case .NotFound: return "Not Found" case .MethodNotAllowed: return "Method Not Allowed" case .NotAcceptable: return "Not Acceptable" case .RequestEntityIncomplete: return "Request Entity Incomplete" case .PreconditionFailed: return "Precondition Failed" case .RequestEntityTooLarge: return "Request Entity Too Large" case .UnsupportedContentFormat: return "Unsupported Content Format" case .InternalServerError: return "Internal Server Error" case .NotImplemented: return "Not Implemented" case .BadGateway: return "Bad Gateway" case .ServiceUnavailable: return "Service Unavailable" case .GatewayTimeout: return "Gateway Timeout" case .ProxyingNotSupported: return "Proxying Not Supported" } } static func stringFromCodeValue(codeValue: SCCodeValue) -> String? { return codeValue.toCodeSample()?.toString() } } //MARK: //MARK: SC Content Format Enumeration enum SCContentFormat: UInt { case Plain = 0 case LinkFormat = 40 case XML = 41 case OctetStream = 42 case EXI = 47 case JSON = 50 case CBOR = 60 func needsStringConversion() -> Bool { switch self { case .OctetStream, .EXI, .CBOR: return true default: return false } } } //MARK: //MARK: SC Code Value struct: Represents the CoAP code. You can easily apply the CoAP code syntax c.dd (e.g. SCCodeValue(classValue: 0, detailValue: 01) equals 0.01) struct SCCodeValue: Equatable { let classValue: UInt8 let detailValue: UInt8 init(rawValue: UInt8) { let firstBits: UInt8 = rawValue >> 5 let lastBits: UInt8 = rawValue & 0b00011111 self.classValue = firstBits self.detailValue = lastBits } //classValue must not be larger than 7; detailValue must not be larger than 31 init?(classValue: UInt8, detailValue: UInt8) { if classValue > 0b111 || detailValue > 0b11111 { return nil } self.classValue = classValue self.detailValue = detailValue } func toRawValue() -> UInt8 { return classValue << 5 + detailValue } func toCodeSample() -> SCCodeSample? { if let code = SCCodeSample(rawValue: Int(toRawValue())) { return code } return nil } static func fromCodeSample(code: SCCodeSample) -> SCCodeValue { return SCCodeValue(rawValue: UInt8(code.rawValue)) } func toString() -> String { return String(format: "%i.%02d", classValue, detailValue) } func requestString() -> String? { switch self { case SCCodeValue(classValue: 0, detailValue: 01)!: return "GET" case SCCodeValue(classValue: 0, detailValue: 02)!: return "POST" case SCCodeValue(classValue: 0, detailValue: 03)!: return "PUT" case SCCodeValue(classValue: 0, detailValue: 04)!: return "DELETE" default: return nil } } } func ==(lhs: SCCodeValue, rhs: SCCodeValue) -> Bool { return lhs.classValue == rhs.classValue && lhs.detailValue == rhs.detailValue } //MARK: //MARK: UInt Extension public extension UInt { func toByteArray() -> [UInt8] { var byteLength = UInt(ceil(log2(Double(self + 1)) / 8)) var byteArray = [UInt8]() for var i: UInt = 0; i < byteLength; i++ { byteArray.append(UInt8(((self) >> ((byteLength - i - 1) * 8)) & 0xFF)) } return byteArray } static func fromData(data: NSData) -> UInt { var valueBytes = [UInt8](count: data.length, repeatedValue: 0) data.getBytes(&valueBytes, length: data.length) var actualValue: UInt = 0 for var i = 0; i < valueBytes.count; i++ { actualValue += UInt(valueBytes[i]) << ((UInt(valueBytes.count) - UInt(i + 1)) * 8) } return actualValue } } //MARK: //MARK: Resource Implementation, used for SCServer class SCResourceModel: NSObject { let name: String // Name of the resource let allowedRoutes: UInt // Bitmask of allowed routes (see SCAllowedRoutes enum) var maxAgeValue: UInt! // If not nil, every response will contain the provided MaxAge value private(set) var etag: NSData! // If not nil, every response to a GET request will contain the provided eTag. The etag is generated automatically whenever you update the dataRepresentation of the resource var dataRepresentation: NSData! { didSet { if var hashInt = dataRepresentation?.hashValue { etag = NSData(bytes: &hashInt, length: sizeof(Int)) } } }// The current data representation of the resource. Needs to stay up to date var observable = false // If true, a response will contain the Observe option, and endpoints will be able to register as observers in SCServer. Call updateRegisteredObserversForResource(self), anytime your dataRepresentation changes. //Desigated initializer init(name: String, allowedRoutes: UInt) { self.name = name self.allowedRoutes = allowedRoutes } //The Methods for Data reception for allowed routes. SCServer will call the appropriate message upon the reception of a reqeuest. Override the respective methods, which match your allowedRoutes. //SCServer passes a queryDictionary containing the URI query content (e.g ["user_id": "23"]) and all options contained in the respective request. The POST and PUT methods provide the message's payload as well. //Refer to the example resources in the SwiftCoAPServerExample project for implementation examples. //This method lets you decide whether the current GET request shall be processed asynchronously, i.e. if true will be returned, an empty ACK will be sent, and you can provide the actual response by calling the servers "didCompleteAsynchronousRequestForOriginalMessage(...)". Note: "dataForGet" will not be called additionally if you return true. func willHandleDataAsynchronouslyForGet(#queryDictionary: [String : String], options: [Int : [NSData]], originalMessage: SCMessage) -> Bool { return false } //The following methods require data for the given routes GET, POST, PUT, DELETE and must be overriden if needed. If you return nil, the server will respond with a "Method not allowed" error code (Make sure that you have set the allowed routes in the "allowedRoutes" bitmask property). //You have to return a tuple with a statuscode, optional payload, optional content format for your provided payload and (in case of POST and PUT) an optional locationURI. func dataForGet(#queryDictionary: [String : String], options: [Int : [NSData]]) -> (statusCode: SCCodeValue, payloadData: NSData?, contentFormat: SCContentFormat!)? { return nil } func dataForPost(#queryDictionary: [String : String], options: [Int : [NSData]], requestData: NSData?) -> (statusCode: SCCodeValue, payloadData: NSData?, contentFormat: SCContentFormat!, locationUri: String!)? { return nil } func dataForPut(#queryDictionary: [String : String], options: [Int : [NSData]], requestData: NSData?) -> (statusCode: SCCodeValue, payloadData: NSData?, contentFormat: SCContentFormat!, locationUri: String!)? { return nil } func dataForDelete(#queryDictionary: [String : String], options: [Int : [NSData]]) -> (statusCode: SCCodeValue, payloadData: NSData?, contentFormat: SCContentFormat!)? { return nil } } //MARK: //MARK: SC Message IMPLEMENTATION class SCMessage: NSObject { //MARK: Constants and Properties //CONSTANTS static let kCoapVersion = 0b01 static let kProxyCoAPTypeKey = "COAP_TYPE" static let kCoapErrorDomain = "SwiftCoapErrorDomain" static let kAckTimeout = 2.0 static let kAckRandomFactor = 1.5 static let kMaxRetransmit = 4 static let kMaxTransmitWait = 93.0 let kDefaultMaxAgeValue: UInt = 60 let kOptionOneByteExtraValue: UInt8 = 13 let kOptionTwoBytesExtraValue: UInt8 = 14 //INTERNAL PROPERTIES (allowed to modify) var code: SCCodeValue = SCCodeValue(classValue: 0, detailValue: 0)! //Code value is Empty by default var type: SCType = .Confirmable //Type is CON by default var payload: NSData? //Add a payload (optional) var blockBody: NSData? //Helper for Block1 tranmission. Used by SCClient, modification has no effect lazy var options = [Int: [NSData]]() //CoAP-Options. It is recommend to use the addOption(..) method to add a new option. //The following properties are modified by SCClient/SCServer. Modification has no effect and is therefore not recommended var hostName: String? var port: UInt16? var addressData: NSData? var resourceForConfirmableResponse: SCResourceModel? var messageId: UInt16! var token: UInt64 = 0 var timeStamp: NSDate? //MARK: Internal Methods (allowed to use) convenience init(code: SCCodeValue, type: SCType, payload: NSData?) { self.init() self.code = code self.type = type self.payload = payload } func equalForCachingWithMessage(message: SCMessage) -> Bool { if code == message.code && hostName == message.hostName && port == message.port { var firstSet = Set(options.keys) var secondSet = Set(message.options.keys) var exOr = firstSet.exclusiveOr(secondSet) for optNo in exOr { if !(SCOption.isNumberNoCacheKey(optNo)) { return false } } var interSect = firstSet.intersect(secondSet) for optNo in interSect { if !(SCOption.isNumberNoCacheKey(optNo)) && !(SCMessage.compareOptionValueArrays(options[optNo]!, second: message.options[optNo]!)) { return false } } return true } return false } static func compareOptionValueArrays(first: [NSData], second: [NSData]) -> Bool { if first.count != second.count { return false } for var i = 0; i < first.count; i++ { if !first[i].isEqualToData(second[i]) { return false } } return true } static func copyFromMessage(message: SCMessage) -> SCMessage { var copiedMessage = SCMessage(code: message.code, type: message.type, payload: message.payload) copiedMessage.options = message.options copiedMessage.hostName = message.hostName copiedMessage.port = message.port copiedMessage.messageId = message.messageId copiedMessage.token = message.token copiedMessage.timeStamp = message.timeStamp return copiedMessage } func isFresh() -> Bool { func validateMaxAge(value: UInt) -> Bool { if timeStamp != nil { var expirationDate = timeStamp!.dateByAddingTimeInterval(Double(value)) return NSDate().compare(expirationDate) != .OrderedDescending } return false } if let maxAgeValues = options[SCOption.MaxAge.rawValue], firstData = maxAgeValues.first { return validateMaxAge(UInt.fromData(firstData)) } return validateMaxAge(kDefaultMaxAgeValue) } func addOption(option: Int, data: NSData) { if var currentOptionValue = options[option] { currentOptionValue.append(data) options[option] = currentOptionValue } else { options[option] = [data] } } func toData() -> NSData? { var resultData: NSMutableData var tokenLength = Int(ceil(log2(Double(token + 1)) / 8)) if tokenLength > 8 { return nil } let codeRawValue = code.toRawValue() let firstByte: UInt8 = UInt8((SCMessage.kCoapVersion << 6) | (type.rawValue << 4) | tokenLength) var actualMessageId: UInt16 = messageId ?? 0 var byteArray: [UInt8] = [firstByte, codeRawValue, UInt8(actualMessageId >> 8), UInt8(actualMessageId & 0xFF)] resultData = NSMutableData(bytes: &byteArray, length: byteArray.count) if tokenLength > 0 { var tokenByteArray = [UInt8]() for var i = 0; i < tokenLength; i++ { tokenByteArray.append(UInt8(((token) >> UInt64((tokenLength - i - 1) * 8)) & 0xFF)) } resultData.appendBytes(&tokenByteArray, length: tokenLength) } var sortedOptions = sorted(options) { $0.0 < $1.0 } var previousDelta = 0 for (key, valueArray) in sortedOptions { var optionDelta = key - previousDelta previousDelta += optionDelta for value in valueArray { var optionFirstByte: UInt8 var extendedDelta: NSData? var extendedLength: NSData? if optionDelta >= Int(kOptionTwoBytesExtraValue) + 0xFF { optionFirstByte = kOptionTwoBytesExtraValue << 4 var extendedDeltaValue: UInt16 = UInt16(optionDelta) - (UInt16(kOptionTwoBytesExtraValue) + 0xFF) var extendedByteArray: [UInt8] = [UInt8(extendedDeltaValue >> 8), UInt8(extendedDeltaValue & 0xFF)] extendedDelta = NSData(bytes: &extendedByteArray, length: extendedByteArray.count) } else if optionDelta >= Int(kOptionOneByteExtraValue) { optionFirstByte = kOptionOneByteExtraValue << 4 var extendedDeltaValue: UInt8 = UInt8(optionDelta) - kOptionOneByteExtraValue extendedDelta = NSData(bytes: &extendedDeltaValue, length: 1) } else { optionFirstByte = UInt8(optionDelta) << 4 } if value.length >= Int(kOptionTwoBytesExtraValue) + 0xFF { optionFirstByte += kOptionTwoBytesExtraValue var extendedLengthValue: UInt16 = UInt16(value.length) - (UInt16(kOptionTwoBytesExtraValue) + 0xFF) var extendedByteArray: [UInt8] = [UInt8(extendedLengthValue >> 8), UInt8(extendedLengthValue & 0xFF)] extendedLength = NSData(bytes: &extendedByteArray, length: extendedByteArray.count) } else if value.length >= Int(kOptionOneByteExtraValue) { optionFirstByte += kOptionOneByteExtraValue var extendedLengthValue: UInt8 = UInt8(value.length) - kOptionOneByteExtraValue extendedLength = NSData(bytes: &extendedLengthValue, length: 1) } else { optionFirstByte += UInt8(value.length) } resultData.appendBytes(&optionFirstByte, length: 1) if extendedDelta != nil { resultData.appendData(extendedDelta!) } if extendedLength != nil { resultData.appendData(extendedLength!) } resultData.appendData(value) } } if payload != nil { var payloadMarker: UInt8 = 0xFF resultData.appendBytes(&payloadMarker, length: 1) resultData.appendData(payload!) } return resultData } static func fromData(data: NSData) -> SCMessage? { if data.length < 4 { return nil } //Unparse Header var parserIndex = 4 var headerBytes = [UInt8](count: parserIndex, repeatedValue: 0) data.getBytes(&headerBytes, length: parserIndex) var firstByte = headerBytes[0] let tokenLenght = Int(firstByte) & 0xF firstByte >>= 4 let type = SCType(rawValue: Int(firstByte) & 0b11) firstByte >>= 2 if tokenLenght > 8 || type == nil || firstByte != UInt8(kCoapVersion) { return nil } //Assign header values to CoAP Message var message = SCMessage() message.type = type! message.code = SCCodeValue(rawValue: headerBytes[1]) message.messageId = (UInt16(headerBytes[2]) << 8) + UInt16(headerBytes[3]) if tokenLenght > 0 { var tokenByteArray = [UInt8](count: tokenLenght, repeatedValue: 0) data.getBytes(&tokenByteArray, range: NSMakeRange(4, tokenLenght)) for var i = 0; i < tokenByteArray.count; i++ { message.token += UInt64(tokenByteArray[i]) << ((UInt64(tokenByteArray.count) - UInt64(i + 1)) * 8) } } parserIndex += tokenLenght var currentOptDelta = 0 while parserIndex < data.length { var nextByte: UInt8 = 0 data.getBytes(&nextByte, range: NSMakeRange(parserIndex, 1)) parserIndex++ if nextByte == 0xFF { message.payload = data.subdataWithRange(NSMakeRange(parserIndex, data.length - parserIndex)) break } else { var optLength = nextByte & 0xF nextByte >>= 4 if nextByte == 0xF || optLength == 0xF { return nil } var finalDelta = 0 switch nextByte { case 13: data.getBytes(&finalDelta, range: NSMakeRange(parserIndex, 1)) finalDelta += 13 parserIndex++ case 14: var twoByteArray = [UInt8](count: 2, repeatedValue: 0) data.getBytes(&twoByteArray, range: NSMakeRange(parserIndex, 2)) finalDelta = (Int(twoByteArray[0]) << 8) + Int(twoByteArray[1]) finalDelta += (14 + 0xFF) parserIndex += 2 default: finalDelta = Int(nextByte) } finalDelta += currentOptDelta currentOptDelta = finalDelta var finalLenght = 0 switch optLength { case 13: data.getBytes(&finalLenght, range: NSMakeRange(parserIndex, 1)) finalLenght += 13 parserIndex++ case 14: var twoByteArray = [UInt8](count: 2, repeatedValue: 0) data.getBytes(&twoByteArray, range: NSMakeRange(parserIndex, 2)) finalLenght = (Int(twoByteArray[0]) << 8) + Int(twoByteArray[1]) finalLenght += (14 + 0xFF) parserIndex += 2 default: finalLenght = Int(optLength) } var optValue = NSData() if finalLenght > 0 { optValue = data.subdataWithRange(NSMakeRange(parserIndex, finalLenght)) parserIndex += finalLenght } message.addOption(finalDelta, data: optValue) } } return message } func toHttpUrlRequestWithUrl() -> NSMutableURLRequest { var urlRequest = NSMutableURLRequest() if code != SCCodeSample.Get.codeValue() { urlRequest.HTTPMethod = code.requestString()! } for (key, valueArray) in options { for value in valueArray { var fieldString: String if let optEnum = SCOption(rawValue: key) { switch optEnum.format() { case .String: fieldString = NSString(data: value, encoding: NSUTF8StringEncoding) as? String ?? "" case .Empty: fieldString = "" default: fieldString = String(UInt.fromData(value)) } } else { fieldString = "" } if let optionName = SCOption(rawValue: key)?.toString().uppercaseString { urlRequest.addValue(String(fieldString), forHTTPHeaderField: optionName) } } } urlRequest.HTTPBody = payload return urlRequest } static func fromHttpUrlResponse(urlResponse: NSHTTPURLResponse, data: NSData!) -> SCMessage { var message = SCMessage() message.payload = data message.code = SCCodeValue(rawValue: UInt8(urlResponse.statusCode & 0xff)) if let typeString = urlResponse.allHeaderFields[SCMessage.kProxyCoAPTypeKey] as? String, type = SCType.fromShortString(typeString) { message.type = type } for opt in SCOption.allValues { if let optValue = urlResponse.allHeaderFields["HTTP_\(opt.toString().uppercaseString)"] as? String { var optValueData: NSData switch opt.format() { case .Empty: optValueData = NSData() case .String: optValueData = optValue.dataUsingEncoding(NSUTF8StringEncoding)! default: if let intVal = optValue.toInt() { var byteArray = UInt(intVal).toByteArray() optValueData = NSData(bytes: &byteArray, length: byteArray.count) } else { optValueData = NSData() } } message.options[opt.rawValue] = [optValueData] } } return message } func completeUriPath() -> String { var finalPathString: String = "" if let pathDataArray = options[SCOption.UriPath.rawValue] { for var i = 0; i < pathDataArray.count; i++ { if let pathString = NSString(data: pathDataArray[i], encoding: NSUTF8StringEncoding) { if i > 0 { finalPathString += "/"} finalPathString += String(pathString) } } } return finalPathString } func uriQueryDictionary() -> [String : String] { var resultDict = [String : String]() if let queryDataArray = options[SCOption.UriQuery.rawValue] { for queryData in queryDataArray { if let queryString = NSString(data: queryData, encoding: NSUTF8StringEncoding), splitArray = queryString.componentsSeparatedByString("=") as? [String] where splitArray.count == 2 { resultDict[splitArray.first!] = splitArray.last! } } } return resultDict } static func getPathAndQueryDataArrayFromUriString(uriString: String) -> (pathDataArray: [NSData], queryDataArray: [NSData])? { func dataArrayFromString(string: String!, withSeparator separator: String) -> [NSData] { var resultDataArray = [NSData]() if string != nil { let stringArray = string.componentsSeparatedByString(separator) for subString in stringArray { if let data = subString.dataUsingEncoding(NSUTF8StringEncoding) { resultDataArray.append(data) } } } return resultDataArray } let splitArray = uriString.componentsSeparatedByString("?") if splitArray.count <= 2 { let resultPathDataArray = dataArrayFromString(splitArray.first, withSeparator: "/") let resultQueryDataArray = splitArray.count == 2 ? dataArrayFromString(splitArray.last, withSeparator: "&") : [] return (resultPathDataArray, resultQueryDataArray) } return nil } }
mit
360336e8f154cb573da9e79f1a1d4f27
35.459976
349
0.578418
4.797359
false
false
false
false
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Sources/Shared/Core/BinarySearch.swift
1
2245
import Foundation public class BinarySearch { public init() {} private func binarySearch(_ collection: [LayoutAttributes], less: (LayoutAttributes) -> Bool, match: (LayoutAttributes) -> Bool) -> Int? { guard var upperBound = collection.indices.last else { return nil } upperBound += 1 var lowerBound = 0 while lowerBound < upperBound { let midIndex = lowerBound + (upperBound - lowerBound) / 2 let element = collection[midIndex] if match(element) { return midIndex } else if less(element) { lowerBound = midIndex + 1 } else { upperBound = midIndex } } return nil } public func findElement(in collection: [LayoutAttributes], upper: (LayoutAttributes) -> Bool, lower: (LayoutAttributes) -> Bool, less: (LayoutAttributes) -> Bool, match: (LayoutAttributes) -> Bool) -> LayoutAttributes? { guard let firstMatchIndex = binarySearch(collection, less: less, match: match) else { return nil } return collection[firstMatchIndex] } public func findElements(in collection: [LayoutAttributes], upper: (LayoutAttributes) -> Bool, lower: (LayoutAttributes) -> Bool, less: (LayoutAttributes) -> Bool, match: (LayoutAttributes) -> Bool) -> [LayoutAttributes] { guard let firstMatchIndex = binarySearch(collection, less: less, match: match) else { return [] } var results = [LayoutAttributes]() for element in collection[..<firstMatchIndex].reversed() { guard upper(element) else { break } results.append(element) } for element in collection[firstMatchIndex...] { guard lower(element) else { break } results.append(element) } return results } }
mit
7f6642663649e5f4e21661e8d368dbdb
32.507463
85
0.50735
5.861619
false
false
false
false
turingcorp/gattaca
gattaca/Model/Perk/Abstract/MPerkFactory.swift
1
1224
import Foundation import CoreData extension MPerk { func factoryThumbnails() -> [MPerkThumbnailProtocol] { let perks:[MPerkThumbnailProtocol] = [] return perks } func factoryDispatchGroup() -> DispatchGroup { let dispatchGroup:DispatchGroup = DispatchGroup() dispatchGroup.setTarget( queue:DispatchQueue.global( qos:DispatchQoS.QoSClass.background)) return dispatchGroup } func factoryStoredPerks( completion:@escaping(([DPerk]?) -> ())) { // DManager.sharedInstance?.fetch(entity:DPerk.self) // { (data:[NSManagedObject]?) in // // let perks:[DPerk]? = data as? [DPerk] // completion(perks) // } } func factoryPerksMap(perks:[DPerk]) -> [String:DPerk] { var map:[String:DPerk] = [:] for perk:DPerk in perks { guard let identifier:String = perk.identifier else { continue } map[identifier] = perk } return map } }
mit
604f513f1fdc904c15bc1502cbe92a6c
21.666667
59
0.492647
4.995918
false
false
false
false
darkzero/DZ_UIKit
DZ_UIKit/Classes/Categories/UIColor+RGBA.swift
1
2430
// // UIColor+RGBA.swift // DZ_UIKit // // Created by Dora.Yuan on 2014/10/08. // Copyright (c) 2014 Dora.Yuan All rights reserved. // import UIKit let MAX_COLOR_RGB:CGFloat = 255.0; let DEFAULT_ALPHA:CGFloat = 1.0; let RED_MASK_HEX = 0x10000; let GREEN_MASK_HEX = 0x100; public func RGB(_ r:Int, _ g:Int, _ b:Int) -> UIColor { return UIColor.colorWithDec(Red:r, Green:g, Blue:b, Alpha:1.0) } public func RGBA(_ r:Int, _ g:Int, _ b:Int, _ a:CGFloat) -> UIColor { return UIColor.colorWithDec(Red:r, Green:g, Blue:b, Alpha:a) } public func RGB_HEX(_ hex:String, _ a:CGFloat) -> UIColor { return UIColor.colorWithHex(Hex: hex, Alpha: a) } extension UIColor { /** Create and return a color object with HEX string (like "3366CC") and alpha (0.0 ~ 1.0) - Parameters hex: HEX string - Parameters alpha: alpha - Return: color */ fileprivate class func colorWithHex( Hex hex:String, Alpha alpha:CGFloat ) -> UIColor { let colorScanner:Scanner = Scanner(string: hex); var color: uint = 0 colorScanner.scanHexInt32(&color) let r:CGFloat = CGFloat( ( color & 0xFF0000 ) >> 16 ) / 255.0 let g:CGFloat = CGFloat( ( color & 0x00FF00 ) >> 8 ) / 255.0 let b:CGFloat = CGFloat( color & 0x0000FF ) / 255.0 return UIColor(red: r, green: g, blue: b, alpha: alpha) } /** Create and return a color object with red, green, blue (0 ~ 255) and alpha (0.0 ~ 1.0) - Parameters Red: red (0 ~ 255) - Parameters Green: green (0 ~ 255) - Parameters Blue: blue (0 ~ 255) - Parameters Alpha: alpha ( 0.0 ~ 1.0 ) - Return: color */ fileprivate class func colorWithDec(Red r:Int, Green g:Int, Blue b:Int, Alpha alpha:CGFloat) -> UIColor { return UIColor( red: CGFloat(r)/MAX_COLOR_RGB, green: CGFloat(g)/MAX_COLOR_RGB, blue: CGFloat(b)/MAX_COLOR_RGB, alpha: alpha ); } /** Return gray level of the color object - Return: gray color */ public func getGary() -> Int { var r: CGFloat = 1.0 var g: CGFloat = 1.0 var b: CGFloat = 1.0 var a: CGFloat = 1.0 self.getRed(&r, green: &g, blue: &b, alpha: &a) var gray = Int(r*255.0*38.0 + g*255.0*75.0 + b*255.0*15.0) >> 7 gray = Int(ceil(CGFloat(gray) * a)) return gray; } }
mit
aa98c1f203b705f2de18931c9b44ce24
30.973684
109
0.577366
3.214286
false
false
false
false
moniqwerty/OpenWeatherApp
OpenWeatherApp/OpenWeatherApp/Model/City.swift
1
1425
// // City.swift // OpenWeatherApp // // Created by Monika Markovska on 3/19/16. // Copyright © 2016 Monika Markovska. All rights reserved. // import Foundation class City: NSObject, NSCoding{ var cityName: String! var temperature: Double? var humidity: Double? var weatherDescription: String? func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(cityName, forKey:"cityName") aCoder.encodeObject(temperature, forKey:"temperature") aCoder.encodeObject(humidity, forKey:"humidity") aCoder.encodeObject(weatherDescription, forKey:"weatherDescription") } required init (coder aDecoder: NSCoder) { if let name = aDecoder.decodeObjectForKey("cityName") as? String{ self.cityName = name } else { self.cityName = "" } if let temp = aDecoder.decodeObjectForKey("temperature") as? Double{ self.temperature = temp } else { self.temperature = 0.0 } if let hum = aDecoder.decodeObjectForKey("humidity") as? Double{ self.humidity = hum } else { self.humidity = 0.0 } if let desc = aDecoder.decodeObjectForKey("weatherDescription") as? String{ self.weatherDescription = desc } else { self.weatherDescription = "" } } override init (){} }
mit
156c4915b1a824c0a2e30171230a19bf
27.5
83
0.601124
4.843537
false
false
false
false
marinbenc/Starscream-RxSwift
Starscream+RxSwift.swift
1
2545
// // Starscream+RxSwift.swift // // Created by Marin Bencevic on 28/01/16. import Foundation import Socket_IO_Client_Swift import RxSwift //An enum returned by rx_response with different types of events that the socket can recieve. enum SocketEvent { case Connected case Message(String) case Data(NSData) } extension WebSocket { ///An observable sequence of strings recieved by the websocket func rx_text()-> Observable<String> { return Observable.create { [weak self] observer in self?.onText = { text in observer.on(.Next(text)) } self?.onDisconnect = { error in if let error = error { observer.on(.Error(error)) } else { let error = NSError(domain: "Unknown error", code: 0, userInfo: nil) observer.on(.Error(error)) } } return AnonymousDisposable { self?.disconnect() } } } ///An observable sequence of NSData recieved by the web socket func rx_data()-> Observable<NSData> { return Observable.create { [weak self] observer in self?.onData = { data in observer.on(.Next(data)) } self?.onDisconnect = { error in if let error = error { observer.on(.Error(error)) } else { let error = NSError(domain: "Unknown error", code: 0, userInfo: nil) observer.on(.Error(error)) } } return AnonymousDisposable { self?.disconnect() } } } ///An observable sequence of SocketEvents recieved from the web socket func rx_response()-> Observable<SocketEvent> { return Observable.create { [weak self] observer in self?.onConnect = { observer.on(.Next(.Connected)) } self?.onText = { text in observer.on(.Next(.Message(text))) } self?.onData = { data in observer.on(.Next(.Data(data))) } self?.onDisconnect = { error in if let error = error { observer.on(.Error(error)) } else { let error = NSError(domain: "Unknown error", code: 0, userInfo: nil) observer.on(.Error(error)) } } return AnonymousDisposable { self?.disconnect() } } } }
mit
29378641bc8ceb63d1597a3afcef4499
32.051948
93
0.517485
4.941748
false
false
false
false
jtsmrd/Intrview
ViewControllers/InterviewsTVC.swift
1
6309
// // InterviewsTVC.swift // SnapInterview // // Created by JT Smrdel on 1/24/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import UIKit import NotificationCenter class InterviewsTVC: UITableViewController { var profile = (UIApplication.shared.delegate as! AppDelegate).profile var individualInterviewDetailVC: IndividualInterviewDetailVC! var businessInterviewDetailVC: BusinessInterviewDetailVC! var interviews: [Interview] { get { switch profile.profileType! { case .Business: return (profile.businessProfile?.interviewCollection.interviews)! case .Individual: return (profile.individualProfile?.interviewCollection.interviews)! } } set(interviews) { switch profile.profileType! { case .Business: profile.businessProfile?.interviewCollection.interviews = interviews case .Individual: profile.individualProfile?.interviewCollection.interviews = interviews } } } override func viewDidLoad() { super.viewDidLoad() let attributes = [NSForegroundColorAttributeName : UIColor.white] navigationController?.navigationBar.titleTextAttributes = attributes navigationController?.navigationBar.tintColor = UIColor.white navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: (162/255), blue: (4/255), alpha: 1) tableView.register(UINib(nibName: "InterviewCell", bundle: nil), forCellReuseIdentifier: "InterviewCell") tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) var newInterviewCount = 0 switch profile.profileType! { case .Business: navigationItem.title = "Active Interviews" businessInterviewDetailVC = BusinessInterviewDetailVC(nibName: "BusinessInterviewDetailVC", bundle: nil) newInterviewCount = interviews.filter({ (interview) -> Bool in interview.businessNewFlag == true }).count case .Individual: navigationItem.title = "Interviews" individualInterviewDetailVC = IndividualInterviewDetailVC(nibName: "IndividualInterviewDetailVC", bundle: nil) newInterviewCount = interviews.filter({ (interview) -> Bool in interview.individualNewFlag == true }).count } if newInterviewCount > 0 { DispatchQueue.main.async { self.tabBarItem.badgeValue = "\(newInterviewCount)" } } else { DispatchQueue.main.async { self.tabBarItem.badgeValue = nil } } sortAndRefreshInterviews() } func sortAndRefreshInterviews() { interviews.sort { (int1, int2) -> Bool in int1.createDate! > int2.createDate! } DispatchQueue.main.async { self.tableView.reloadData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.interviews.count > 0 { return interviews.count } else { return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch profile.profileType! { case .Business: if !interviews.isEmpty { let interviewCell = tableView.dequeueReusableCell(withIdentifier: "InterviewCell", for: indexPath) as! InterviewCell interviewCell.configureCell(interview: interviews[indexPath.row], profileName: interviews[indexPath.row].individualName!, isNew: interviews[indexPath.row].businessNewFlag) return interviewCell } else { let noDataCell = UITableViewCell(style: .default, reuseIdentifier: "NoDataCell") noDataCell.textLabel?.text = "No Active Interviews" noDataCell.textLabel?.textColor = Global.grayColor noDataCell.textLabel?.textAlignment = .center return noDataCell } case .Individual: if !interviews.isEmpty { let interviewCell = tableView.dequeueReusableCell(withIdentifier: "InterviewCell", for: indexPath) as! InterviewCell interviewCell.configureCell(interview: interviews[indexPath.row], profileName: interviews[indexPath.row].businessName!, isNew: interviews[indexPath.row].individualNewFlag) return interviewCell } else { let noDataCell = UITableViewCell(style: .default, reuseIdentifier: "NoDataCell") noDataCell.textLabel?.text = "No Interviews Yet" noDataCell.textLabel?.textColor = Global.grayColor noDataCell.textLabel?.textAlignment = .center return noDataCell } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 58 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedInterview = interviews[indexPath.row] switch profile.profileType! { case .Business: businessInterviewDetailVC.interview = selectedInterview navigationController?.pushViewController(businessInterviewDetailVC, animated: true) case .Individual: individualInterviewDetailVC.interview = selectedInterview navigationController?.pushViewController(individualInterviewDetailVC, animated: true) } } }
mit
e6bff4f4eb728a254a402d03613674f3
35.252874
187
0.608592
5.470945
false
false
false
false
tp/Formulary
Formulary/Forms/FormViewController.swift
1
5636
// // FormViewController.swift // Formulary // // Created by Fabian Canas on 1/16/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import UIKit public class FormViewController: UIViewController, UITableViewDelegate { var dataSource: FormDataSource? public var form :Form { didSet { dataSource = FormDataSource(form: form, tableView: tableView) tableView?.dataSource = dataSource } } public var tableView: UITableView! public var tableViewStyle: UITableViewStyle = .Grouped init(form: Form) { self.form = form super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { form = ConcreteForm(sections: []) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init(coder aDecoder: NSCoder) { form = ConcreteForm(sections: []) super.init(coder: aDecoder) } func link(form: Form, table: UITableView) { dataSource = FormDataSource(form: form, tableView: tableView) tableView.dataSource = dataSource } override public func viewDidLoad() { super.viewDidLoad() if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight } if tableView.superview == nil { view.addSubview(tableView) } tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 60 tableView.rowHeight = 60 tableView.delegate = self dataSource = FormDataSource(form: form, tableView: tableView) tableView.dataSource = dataSource } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { if let cell = tableView.firstResponder()?.containingCell(), let selectedIndexPath = tableView.indexPathForCell(cell) { let keyboardInfo = KeyboardNotification(notification) var keyboardEndFrame = keyboardInfo.screenFrameEnd keyboardEndFrame = view.window!.convertRect(keyboardEndFrame, toView: view) var contentInset = tableView.contentInset var scrollIndicatorInsets = tableView.scrollIndicatorInsets contentInset.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y scrollIndicatorInsets.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y UIView.beginAnimations("keyboardAnimation", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .EaseInOut) UIView.setAnimationDuration(keyboardInfo.animationDuration) tableView.contentInset = contentInset tableView.scrollIndicatorInsets = scrollIndicatorInsets tableView.scrollToRowAtIndexPath(selectedIndexPath, atScrollPosition: .None, animated: true) UIView.commitAnimations() } } func keyboardWillHide(notification: NSNotification) { let keyboardInfo = KeyboardNotification(notification) var contentInset = tableView.contentInset var scrollIndicatorInsets = tableView.scrollIndicatorInsets contentInset.bottom = 0 scrollIndicatorInsets.bottom = 0 UIView.beginAnimations("keyboardAnimation", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .EaseInOut) UIView.setAnimationDuration(keyboardInfo.animationDuration) tableView.contentInset = contentInset tableView.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { tableView.firstResponder()?.resignFirstResponder() } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? FormTableViewCell { cell.formRow?.action?(nil) cell.action?(nil) } } } extension UIView { func firstResponder() -> UIView? { if isFirstResponder() { return self } for subview in (subviews as! [UIView]) { if let responder = subview.firstResponder() { return responder } } return nil } func containingCell() -> UITableViewCell? { if let c = self as? UITableViewCell { return c } return superview?.containingCell() } }
mit
8f872a93a29ce277103c7bdfa4756914
36.573333
154
0.647622
6.04721
false
false
false
false
maxdignan/TwitterJSON
TwitterJSON/TwitterJSON.swift
2
5251
// // TwitterJSON.swift // TwitterJSON // // Created by Kyle Goslan on 04/08/2015. // Copyright (c) 2015 Kyle Goslan. All rights reserved. // import Foundation import SwiftyJSON import Alamofire import Accounts import Social /** All the real network requests are sent through this object. */ public class TwitterJSON { /** Nuber of results to return. */ public static var numberOfResults = 20 /** Needed to feedback alerts to the user. */ public static var viewController: UIViewController? /** Deals with the final request to the API. :param: SLRequestMethod Will always be either .GET or .POST. :param: Dictionary Parameters for the query. :param: Dictionary Parameters for the query. :param: String The API url destination. :param: Completion Handler for the request containing an error and or JSON. */ public class func makeRequest(requestMethod: SLRequestMethod, parameters: [String : String]!, apiURL: String, completion: ((success: Bool, json: JSON) -> Void)) { TwitterJSON.getAccount {(account: ACAccount?) -> Void in if let _ = account { let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: requestMethod, URL: NSURL(string: apiURL), parameters: parameters) postRequest.account = account postRequest.performRequestWithHandler({ (data: NSData!, urlResponse: NSHTTPURLResponse!, error: NSError!) -> Void in if error == nil { let json = JSON(data: data) completion(success: true, json: json) } else { completion(success: false, json: nil) } }) } else { completion(success: false, json: nil) } } } /** Get the Twitter account configured in settings. :param: completion A closure which contains the first account. */ private class func getAccount(completionHandler: (account: ACAccount?) -> Void) { let accountStore = ACAccountStore() let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccountsWithType(accountType, options: nil) { (granted: Bool, error: NSError!) -> Void in if granted { let accounts: [ACAccount] = accountStore.accountsWithAccountType(accountType) as! [ACAccount] if accounts.count == 1 { completionHandler(account: accounts.first!) } else { let alertController = UIAlertController(title: "Select an account", message: nil, preferredStyle: .Alert) for account in accounts { let alertAction = UIAlertAction(title: account.username, style: .Default) { (alertAction: UIAlertAction!) -> Void in completionHandler(account: account) println("test") } alertController.addAction(alertAction) } TwitterJSON.viewController?.presentViewController(alertController, animated: true, completion: nil) } } else { let title = "Grant Access To Twitter" let message = "You need to give permission for this application to use your Twitter account. Manage in Settings." let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "Okay", style: .Default, handler: nil) alertController.addAction(action) TwitterJSON.viewController?.presentViewController(alertController, animated: true, completion: nil) } } } /** Loads profile images of users. :param: Optional Array of TJTweet objects. :param: Optional Array of TJUser objects. :param: Completion Returns the arry of objects passed in with the images loaded. */ internal class func loadImages(tweets: [TJTweet]?, users: [TJUser]?, completion: (tweets: [TJTweet]?, users: [TJUser]?) -> Void) { var i = 0 if let tweets = tweets { for tweet in tweets { Alamofire.request(.GET, tweet.user.profileImageURL).response { (request, response, data, error) in tweet.user.profileImage = UIImage(data: data!, scale:1) i++ if i == tweets.count { completion(tweets: tweets, users: nil) } } } } if let users = users { for user in users { Alamofire.request(.GET, user.profileImageURL).response { (request, response, data, error) in user.profileImage = UIImage(data: data!, scale:1) i++ if i == users.count { completion(tweets: nil, users: users) } } } } } }
mit
b3f5cd2c37c374a65ed66ed5ed7ea518
39.713178
166
0.574938
5.293347
false
false
false
false
Reality-Virtually-Hackathon/Team-2
WorkspaceAR/ViewController+DataManager.swift
1
4523
// // ViewController+DataManager.swift // WorkspaceAR // // Created by Avery Lamp on 10/7/17. // Copyright © 2017 Apple. All rights reserved. // import UIKit import SceneKit extension ViewController: DataManagerDelegate{ func drawPoints() { let points = DataManager.shared().alignmentPoints guard points.count > 0 else { print("NO POINTS SENT!"); return } guard let cameraTransform = session.currentFrame?.camera.transform, let focusSquarePosition = focusSquare.lastPosition else { statusViewController.showMessage("CANNOT PLACE OBJECT\nTry moving left or right.") return } expandContinueButton(message: "Confirm Point Alignment") let vo = VirtualObject() let rootNode = SCNNode.init() vo.addChildNode(rootNode) // Setup the table physics let width = 10; let length = 10; let planeHeight = 0.00001 let planeGeometry = SCNBox(width: CGFloat(width), height: CGFloat(planeHeight), length: CGFloat(length), chamferRadius: 0) let transparentMaterial = SCNMaterial() transparentMaterial.diffuse.contents = UIColor(white: 1.0, alpha: 0.0) planeGeometry.materials = [transparentMaterial, transparentMaterial, transparentMaterial, transparentMaterial, transparentMaterial, transparentMaterial] let planeNode = SCNNode(geometry: planeGeometry) planeNode.position = SCNVector3Make(0, Float(planeHeight - 0.00005), 0) let physicsShape = SCNPhysicsShape(geometry: planeGeometry, options:nil) planeNode.physicsBody = SCNPhysicsBody(type: .kinematic, shape: physicsShape) vo.addChildNode(planeNode); guard let (worldPosition, _, _) = sceneView.worldPosition(fromScreenPosition: screenCenter, objectPosition: focusSquare.lastPosition, infinitePlane: true) else { print("No Plane found"); return } vo.position = SCNVector3.init(worldPosition) var vecPoints:[SCNVector3] = [] //loops through the points, drawing spheres for i in 0..<points.count { let cgp = points[i] let newVec = SCNVector3.init(cgp.x, 0, cgp.y) vecPoints.append(newVec) let pointNode = SCNNode() let pointGeometry = SCNSphere(radius: 0.007) let orangeMaterial = SCNMaterial() if i == 0 { pointNode.name = "first-alignment-node" orangeMaterial.diffuse.contents = UIColor.green } else { orangeMaterial.diffuse.contents = UIColor.red } pointGeometry.materials = [orangeMaterial] pointNode.geometry = pointGeometry pointNode.position = newVec rootNode.addChildNode(pointNode) } //loops through the points, adding lines between them for i in 0..<points.count-1 { let newTempNode = SCNNode() let newLine = newTempNode.buildLineInTwoPointsWithRotation(from: vecPoints[i], to: vecPoints[i+1], radius: 0.005, color: .cyan) rootNode.addChildNode(newLine) } virtualObjectInteraction.selectedObject = vo vo.setPosition(focusSquarePosition, relativeTo: cameraTransform, smoothMovement: false) updateQueue.async { self.sceneView.scene.rootNode.addChildNode(vo) } print("Received Alignment Points") DataManager.shared().rootNode = rootNode } //incoming recieved delegates func receivedAlignmentPoints(points: [CGPoint]) { //must be client! statusViewController.showMessage("Received \(points.count) alignment points") let ut = DataManager.shared().userType guard ut == .Client else { return } //must be alignment! let state = DataManager.shared().state guard state == .AlignmentStage else { return } //if it is, draw the points drawPoints() } func receivedObjectsUpdate(objects: [SharedARObject]) { statusViewController.showMessage("Received Object update ") print("Received Objects Update") } func receivedNewObject(object: SharedARObject) { statusViewController.showMessage("Received new obejct: \(object.name) ") print("Received New Object") } func newDevicesConnected(devices: [String]) { print("New Devices Connected") if devices.count > 1{ self.statusViewController.showMessage("Devices connected: \(devices.joined(separator: ", "))") }else{ self.statusViewController.showMessage("Device connected: \(devices.joined(separator: ", "))") } devicesConnectedLabel.text = "Other Devices Connected: \(DataManager.shared().allConnectedDevices.count)" } }
mit
ccf7a5243ff669d0b64607e93cc105e7
34.606299
163
0.692835
4.171587
false
false
false
false
apple/swift-nio-http2
Tests/NIOHTTP2Tests/HTTP2ErrorTests.swift
1
13695
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOHTTP2 class HTTP2ErrorTests: XCTestCase { func testEquatableExcludesFileAndLine() throws { XCTAssertEqual(NIOHTTP2Errors.excessiveOutboundFrameBuffering(), NIOHTTP2Errors.excessiveOutboundFrameBuffering(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.invalidALPNToken(), NIOHTTP2Errors.invalidALPNToken(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.noSuchStream(streamID: .rootStream), NIOHTTP2Errors.noSuchStream(streamID: .rootStream, file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.noSuchStream(streamID: 1), NIOHTTP2Errors.noSuchStream(streamID: 2)) XCTAssertEqual(NIOHTTP2Errors.streamClosed(streamID: .rootStream, errorCode: .cancel), NIOHTTP2Errors.streamClosed(streamID: .rootStream, errorCode: .cancel, file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .cancel), NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .compressionError)) XCTAssertNotEqual(NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .cancel), NIOHTTP2Errors.streamClosed(streamID: 2, errorCode: .cancel)) XCTAssertEqual(NIOHTTP2Errors.badClientMagic(), NIOHTTP2Errors.badClientMagic(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.badStreamStateTransition(), NIOHTTP2Errors.badStreamStateTransition(file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.badStreamStateTransition(from: .closed), NIOHTTP2Errors.badStreamStateTransition()) XCTAssertEqual(NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2), NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2, file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2), NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 2, currentWindowSize: 2)) XCTAssertNotEqual(NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 3), NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2)) XCTAssertEqual(NIOHTTP2Errors.flowControlViolation(), NIOHTTP2Errors.flowControlViolation(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1)), NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1), file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1)), NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 2))) XCTAssertEqual(NIOHTTP2Errors.ioOnClosedConnection(), NIOHTTP2Errors.ioOnClosedConnection(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.receivedBadSettings(), NIOHTTP2Errors.receivedBadSettings(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.maxStreamsViolation(), NIOHTTP2Errors.maxStreamsViolation(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.streamIDTooSmall(), NIOHTTP2Errors.streamIDTooSmall(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.missingPreface(), NIOHTTP2Errors.missingPreface(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.createdStreamAfterGoaway(), NIOHTTP2Errors.createdStreamAfterGoaway(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.invalidStreamIDForPeer(), NIOHTTP2Errors.invalidStreamIDForPeer(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.raisedGoawayLastStreamID(), NIOHTTP2Errors.raisedGoawayLastStreamID(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.invalidWindowIncrementSize(), NIOHTTP2Errors.invalidWindowIncrementSize(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.pushInViolationOfSetting(), NIOHTTP2Errors.pushInViolationOfSetting(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.unsupported(info: "info"), NIOHTTP2Errors.unsupported(info: "info", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.unsupported(info: "info"), NIOHTTP2Errors.unsupported(info: "notinfo")) XCTAssertEqual(NIOHTTP2Errors.unableToSerializeFrame(), NIOHTTP2Errors.unableToSerializeFrame(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.unableToParseFrame(), NIOHTTP2Errors.unableToParseFrame(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.missingPseudoHeader("missing"), NIOHTTP2Errors.missingPseudoHeader("missing", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.missingPseudoHeader("missing"), NIOHTTP2Errors.missingPseudoHeader("notmissing")) XCTAssertEqual(NIOHTTP2Errors.duplicatePseudoHeader("duplicate"), NIOHTTP2Errors.duplicatePseudoHeader("duplicate", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.duplicatePseudoHeader("duplicate"), NIOHTTP2Errors.duplicatePseudoHeader("notduplicate")) XCTAssertEqual(NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after"), NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after"), NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("notafter")) XCTAssertEqual(NIOHTTP2Errors.unknownPseudoHeader("unknown"), NIOHTTP2Errors.unknownPseudoHeader("unknown", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.unknownPseudoHeader("unknown"), NIOHTTP2Errors.unknownPseudoHeader("notunknown")) XCTAssertEqual(NIOHTTP2Errors.invalidPseudoHeaders([:]), NIOHTTP2Errors.invalidPseudoHeaders([:], file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.invalidPseudoHeaders([:]), NIOHTTP2Errors.invalidPseudoHeaders(["not": "empty"])) XCTAssertEqual(NIOHTTP2Errors.missingHostHeader(), NIOHTTP2Errors.missingHostHeader(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.duplicateHostHeader(), NIOHTTP2Errors.duplicateHostHeader(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.emptyPathHeader(), NIOHTTP2Errors.emptyPathHeader(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.invalidStatusValue("invalid"), NIOHTTP2Errors.invalidStatusValue("invalid", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.invalidStatusValue("invalid"), NIOHTTP2Errors.invalidStatusValue("notinvalid")) XCTAssertEqual(NIOHTTP2Errors.priorityCycle(streamID: .rootStream), NIOHTTP2Errors.priorityCycle(streamID: .rootStream, file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.priorityCycle(streamID: .rootStream), NIOHTTP2Errors.priorityCycle(streamID: 1)) XCTAssertEqual(NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream), NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream, file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream), NIOHTTP2Errors.trailersWithoutEndStream(streamID: 1)) XCTAssertEqual(NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName"), NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName"), NIOHTTP2Errors.invalidHTTP2HeaderFieldName("notFieldName")) XCTAssertEqual(NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value", file: "", line: 0)) XCTAssertNotEqual(NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), NIOHTTP2Errors.forbiddenHeaderField(name: "notname", value: "value")) XCTAssertNotEqual(NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "notvalue")) XCTAssertEqual(NIOHTTP2Errors.contentLengthViolated(), NIOHTTP2Errors.contentLengthViolated(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.excessiveEmptyDataFrames(), NIOHTTP2Errors.excessiveEmptyDataFrames(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.excessivelyLargeHeaderBlock(), NIOHTTP2Errors.excessivelyLargeHeaderBlock(file: "", line: 0)) XCTAssertEqual(NIOHTTP2Errors.noStreamIDAvailable(), NIOHTTP2Errors.noStreamIDAvailable(file: "", line: 0)) } func testFitsInAnExistentialContainer() { XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.ExcessiveOutboundFrameBuffering>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidALPNToken>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.NoSuchStream>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.StreamClosed>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.BadClientMagic>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.BadStreamStateTransition>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidFlowControlWindowSize>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.FlowControlViolation>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidSetting>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.IOOnClosedConnection>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.ReceivedBadSettings>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.MaxStreamsViolation>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.StreamIDTooSmall>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.MissingPreface>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.CreatedStreamAfterGoaway>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidStreamIDForPeer>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.RaisedGoawayLastStreamID>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidWindowIncrementSize>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.PushInViolationOfSetting>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.Unsupported>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.UnableToSerializeFrame>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.UnableToParseFrame>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.MissingPseudoHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.DuplicatePseudoHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.PseudoHeaderAfterRegularHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.UnknownPseudoHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidPseudoHeaders>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.MissingHostHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.DuplicateHostHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.EmptyPathHeader>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidStatusValue>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.PriorityCycle>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.TrailersWithoutEndStream>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.InvalidHTTP2HeaderFieldName>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.ForbiddenHeaderField>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.ContentLengthViolated>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.ExcessiveEmptyDataFrames>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.ExcessivelyLargeHeaderBlock>.size, 24) XCTAssertLessThanOrEqual(MemoryLayout<NIOHTTP2Errors.NoStreamIDAvailable>.size, 24) } }
apache-2.0
73ba16dffbcc5d5d787791e1d6aa7dff
57.029661
132
0.696605
5.243109
false
false
false
false
youkchansim/CSPhotoGallery
Example/CSPhotoGallery/ViewController.swift
1
1322
// // ViewController.swift // CSPhotoGallery // // Created by chansim.youk on 12/30/2016. // Copyright (c) 2016 chansim.youk. All rights reserved. // import UIKit import CSPhotoGallery import Photos class ViewController: UIViewController { @IBAction func btnAction(_ sender: Any) { let designManager = CSPhotoDesignManager.instance // Main designManager.photoGalleryOKButtonTitle = "OK" let vc = CSPhotoGalleryViewController.instance vc.delegate = self vc.CHECK_MAX_COUNT = 10 vc.horizontalCount = 4 // present(vc, animated: true) navigationController?.pushViewController(vc, animated: true) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: CSPhotoGalleryDelegate { func getAssets(assets: [PHAsset]) { assets.forEach { let size = CGSize(width: $0.pixelWidth, height: $0.pixelHeight) PhotoManager.sharedInstance.assetToImage(asset: $0, imageSize: size, completionHandler: nil) } } }
mit
5b923af69914208e7c25c9ae2c8f6808
27.73913
104
0.657337
4.638596
false
false
false
false
testpress/ios-app
ios-app/UI/LoginActivityViewController.swift
1
6922
// // LoginActivityViewController.swift // ios-app // // Created by Karthik on 16/04/19. // Copyright © 2019 Testpress. All rights reserved. // import UIKit import TTGSnackbar class LoginActivityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var logoutDevicesButton: UIButton! @IBOutlet weak var infoView: UIStackView! @IBOutlet weak var infoLabel: UILabel! var activityIndicator: UIActivityIndicatorView! // Progress bar var emptyView: EmptyView! var items = [LoginActivity]() var pager: LoginActivityPager var loadingItems: Bool = false var firstCallBack: Bool = true required init?(coder aDecoder: NSCoder) { self.pager = LoginActivityPager() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self activityIndicator = UIUtils.initActivityIndicator(parentView: self.tableView) activityIndicator?.center = CGPoint(x: tableView.center.x, y: tableView.center.y) // Set table view footer as progress spinner let pagingSpinner = UIActivityIndicatorView(style: .gray) pagingSpinner.startAnimating() pagingSpinner.color = Colors.getRGB(Colors.PRIMARY) pagingSpinner.hidesWhenStopped = true tableView.tableFooterView = pagingSpinner // Set table view backgroud emptyView = EmptyView.getInstance() tableView.backgroundView = emptyView emptyView.frame = view.frame UIUtils.setTableViewSeperatorInset(tableView, size: 10) let instituteSettings = DBManager<InstituteSettings>().getResultsFromDB()[0] infoView.isHidden = true infoLabel.isHidden = true if (instituteSettings.enableParallelLoginRestriction) { infoView.isHidden = false infoLabel.isHidden = false infoLabel.text = Strings.PARALLEL_LOGIN_RESTRICTION_INFO + "\(instituteSettings.maxParallelLogins) \n" infoView.addBackground(color: Colors.getRGB(Colors.BLACK_TEXT)) } self.setStatusBarColor() } func getNavBarHeight() -> CGFloat { return UINavigationController().navigationBar.frame.size.height } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() if (items.isEmpty) { activityIndicator?.startAnimating() } } override func viewDidAppear(_ animated: Bool) { if (items.isEmpty || firstCallBack) { firstCallBack = false tableView.tableFooterView?.isHidden = true pager.reset() loadItems() } } func loadItems() { if loadingItems { return } loadingItems = true pager.next(completion: { items, error in if let error = error { debugPrint(error.message ?? "No error") debugPrint(error.kind) self.handleError(error) return } self.items = Array(items!.values) if self.items.count == 0 { self.setEmptyText() } self.tableView.reloadData() if (self.activityIndicator?.isAnimating)! { self.activityIndicator?.stopAnimating() } self.tableView.tableFooterView?.isHidden = true self.loadingItems = false }) } func setEmptyText() { emptyView.setValues(image: Images.LoginActivityIcon.image, title: "No data available") } func handleError(_ error: TPError) { var retryHandler: (() -> Void)? if error.kind == .network { retryHandler = { self.activityIndicator?.startAnimating() self.loadItems() } } let (image, title, description) = error.getDisplayInfo() if (activityIndicator?.isAnimating)! { activityIndicator?.stopAnimating() } loadingItems = false if items.count == 0 { emptyView.setValues(image: image, title: title, description: description, retryHandler: retryHandler) } else { TTGSnackbar(message: description, duration: .middle).show() } tableView.reloadData() } func numberOfSections(in tableView: UITableView) -> Int { return items.count > 0 ? 1 : 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if items.count == 0 { tableView.backgroundView?.isHidden = false } else { tableView.backgroundView?.isHidden = true } return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableViewCell(cellForRowAt: indexPath) // Load more items on scroll to bottom if indexPath.row >= (items.count - 4) && !loadingItems { if pager.hasMore { tableView.tableFooterView?.isHidden = false loadItems() } else { tableView.tableFooterView?.isHidden = true } } return cell } func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LoginActivityTableCell", for: indexPath) as! LoginActivityCell cell.ipAddress?.text = items[indexPath.row].ipAddress cell.deviceName?.text = items[indexPath.row].userAgent cell.lastUsedTime?.text = "Last Used : \(FormatDate.getElapsedTime(dateString: items[indexPath.row].lastUsed))" if items[indexPath.row].currentDevice { cell.lastUsedTime?.text = "Currently using" } return cell } @IBAction func logoutDevicesButtonClick(_ sender: UIButton) { activityIndicator?.startAnimating() TPApiClient.apiCall(endpointProvider: TPEndpointProvider(.logoutDevices), completion: { _,error in if let error = error { self.activityIndicator?.stopAnimating() debugPrint(error.message ?? "No error") debugPrint(error.kind) let (_, _, description) = error.getDisplayInfo() TTGSnackbar(message: description, duration: .middle).show() return } self.items.removeAll() self.pager.reset() self.loadItems() }) } @IBAction func back(_ sender: Any) { dismiss(animated: true, completion: nil) } }
mit
e86db1ac43675a5f6d6239716fd3b2ca
30.894009
128
0.602659
5.243182
false
false
false
false
vbudhram/firefox-ios
Client/Extensions/UIAlertControllerExtensions.swift
5
8398
/* 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 typealias UIAlertActionCallback = (UIAlertAction) -> Void // MARK: - Extension methods for building specific UIAlertController instances used across the app extension UIAlertController { /** Builds the Alert view that asks the user if they wish to opt into crash reporting. - parameter sendReportCallback: Send report option handler - parameter alwaysSendCallback: Always send option handler - parameter dontSendCallback: Dont send option handler - parameter neverSendCallback: Never send option handler - returns: UIAlertController for opting into crash reporting after a crash occurred */ class func crashOptInAlert( _ sendReportCallback: @escaping UIAlertActionCallback, alwaysSendCallback: @escaping UIAlertActionCallback, dontSendCallback: @escaping UIAlertActionCallback) -> UIAlertController { let alert = UIAlertController( title: NSLocalizedString("Oops! Firefox crashed", comment: "Title for prompt displayed to user after the app crashes"), message: NSLocalizedString("Send a crash report so Mozilla can fix the problem?", comment: "Message displayed in the crash dialog above the buttons used to select when sending reports"), preferredStyle: .alert ) let sendReport = UIAlertAction( title: NSLocalizedString("Send Report", comment: "Used as a button label for crash dialog prompt"), style: .default, handler: sendReportCallback ) let alwaysSend = UIAlertAction( title: NSLocalizedString("Always Send", comment: "Used as a button label for crash dialog prompt"), style: .default, handler: alwaysSendCallback ) let dontSend = UIAlertAction( title: NSLocalizedString("Don’t Send", comment: "Used as a button label for crash dialog prompt"), style: .default, handler: dontSendCallback ) alert.addAction(sendReport) alert.addAction(alwaysSend) alert.addAction(dontSend) return alert } /** Builds the Alert view that asks the user if they wish to restore their tabs after a crash. - parameter okayCallback: Okay option handler - parameter noCallback: No option handler - returns: UIAlertController for asking the user to restore tabs after a crash */ class func restoreTabsAlert(okayCallback: @escaping UIAlertActionCallback, noCallback: @escaping UIAlertActionCallback) -> UIAlertController { let alert = UIAlertController( title: NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title"), message: NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description"), preferredStyle: .alert ) let noOption = UIAlertAction( title: NSLocalizedString("No", comment: "Restore Tabs Negative Action"), style: .cancel, handler: noCallback ) let okayOption = UIAlertAction( title: NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action"), style: .default, handler: okayCallback ) alert.addAction(okayOption) alert.addAction(noOption) return alert } class func clearPrivateDataAlert(okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController { let alert = UIAlertController( title: "", message: NSLocalizedString("This action will clear all of your private data. It cannot be undone.", tableName: "ClearPrivateDataConfirm", comment: "Description of the confirmation dialog shown when a user tries to clear their private data."), preferredStyle: .alert ) let noOption = UIAlertAction( title: NSLocalizedString("Cancel", tableName: "ClearPrivateDataConfirm", comment: "The cancel button when confirming clear private data."), style: .cancel, handler: nil ) let okayOption = UIAlertAction( title: NSLocalizedString("OK", tableName: "ClearPrivateDataConfirm", comment: "The button that clears private data."), style: .destructive, handler: okayCallback ) alert.addAction(okayOption) alert.addAction(noOption) return alert } /** Builds the Alert view that asks if the users wants to also delete history stored on their other devices. - parameter okayCallback: Okay option handler. - returns: UIAlertController for asking the user to restore tabs after a crash */ class func clearSyncedHistoryAlert(okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController { let alert = UIAlertController( title: "", message: NSLocalizedString("This action will clear all of your private data, including history from your synced devices.", tableName: "ClearHistoryConfirm", comment: "Description of the confirmation dialog shown when a user tries to clear history that's synced to another device."), preferredStyle: .alert ) let noOption = UIAlertAction( title: NSLocalizedString("Cancel", tableName: "ClearHistoryConfirm", comment: "The cancel button when confirming clear history."), style: .cancel, handler: nil ) let okayOption = UIAlertAction( title: NSLocalizedString("OK", tableName: "ClearHistoryConfirm", comment: "The confirmation button that clears history even when Sync is connected."), style: .destructive, handler: okayCallback ) alert.addAction(okayOption) alert.addAction(noOption) return alert } /** Creates an alert view to warn the user that their logins will either be completely deleted in the case of local-only logins or deleted across synced devices in synced account logins. - parameter deleteCallback: Block to run when delete is tapped. - parameter hasSyncedLogins: Boolean indicating the user has logins that have been synced. - returns: UIAlertController instance */ class func deleteLoginAlertWithDeleteCallback( _ deleteCallback: @escaping UIAlertActionCallback, hasSyncedLogins: Bool) -> UIAlertController { let areYouSureTitle = NSLocalizedString("Are you sure?", tableName: "LoginManager", comment: "Prompt title when deleting logins") let deleteLocalMessage = NSLocalizedString("Logins will be permanently removed.", tableName: "LoginManager", comment: "Prompt message warning the user that deleting non-synced logins will permanently remove them") let deleteSyncedDevicesMessage = NSLocalizedString("Logins will be removed from all connected devices.", tableName: "LoginManager", comment: "Prompt message warning the user that deleted logins will remove logins from all connected devices") let cancelActionTitle = NSLocalizedString("Cancel", tableName: "LoginManager", comment: "Prompt option for cancelling out of deletion") let deleteActionTitle = NSLocalizedString("Delete", tableName: "LoginManager", comment: "Label for the button used to delete the current login.") let deleteAlert: UIAlertController if hasSyncedLogins { deleteAlert = UIAlertController(title: areYouSureTitle, message: deleteSyncedDevicesMessage, preferredStyle: .alert) } else { deleteAlert = UIAlertController(title: areYouSureTitle, message: deleteLocalMessage, preferredStyle: .alert) } let cancelAction = UIAlertAction(title: cancelActionTitle, style: .cancel, handler: nil) let deleteAction = UIAlertAction(title: deleteActionTitle, style: .destructive, handler: deleteCallback) deleteAlert.addAction(cancelAction) deleteAlert.addAction(deleteAction) return deleteAlert } }
mpl-2.0
9a6a83035cf4f77cb2aaed6b0d28ab58
43.189474
294
0.678657
5.68065
false
false
false
false
Shannon-Yang/SYNetworking
SYNetworking/SYCacheMetadata.swift
1
3587
// // SYCacheMetadata.swift // SYNetworking // // Created by Shannon Yang on 2016/12/7. // Copyright © 2016年 Hangzhou Yunti Technology Co. Ltd. All rights reserved. // import Foundation import ObjectMapper /// store cached metadata, implement NSSecureCoding protocol class SYCacheMetadata: NSObject, NSSecureCoding { /// can be used to identify and invalidate local cache var cacheKey: String /// cachemetadate create data var creationDate: Date /// request response string encoding, when call "responseString" var responseStringEncoding: String.Encoding /// request responseJSONOptions, when call "responseSwiftyJSON" or "responseJSON" var responseJSONOptions: JSONSerialization.ReadingOptions /// request responsePropertyListOptions, when call "responsePropertyList" var responsePropertyListOptions: PropertyListSerialization.ReadOptions /// request responseObjectKeyPath, when call "responseObject" or "responseObjectArray" var responseObjectKeyPath: String? /// request responseObjectContext, when call "responseObject" or "responseObjectArray" var responseObjectContext: MapContext? /// supportsSecureCoding static var supportsSecureCoding: Bool { return true } //MARK: - Enum enum Key: String { case cacheKey case creationDate case responseStringEncoding case responseJSONOptions case responsePropertyListOptions case responseObjectKeyPath case responseObjectContext } //MARK: - aDecoder required init?(coder aDecoder: NSCoder) { self.cacheKey = aDecoder.decodeObject(forKey: Key.cacheKey.rawValue) as! String self.creationDate = aDecoder.decodeObject(forKey: Key.creationDate.rawValue) as! Date self.responseStringEncoding = String.Encoding(rawValue: aDecoder.decodeObject(forKey: Key.responseStringEncoding.rawValue) as! UInt) self.responseJSONOptions = JSONSerialization.ReadingOptions(rawValue: aDecoder.decodeObject(forKey: Key.responseJSONOptions.rawValue) as! UInt) self.responsePropertyListOptions = PropertyListSerialization.ReadOptions(rawValue: aDecoder.decodeObject(forKey: Key.responsePropertyListOptions.rawValue) as! UInt) self.responseObjectKeyPath = aDecoder.decodeObject(forKey: Key.responseObjectKeyPath.rawValue) as? String self.responseObjectContext = aDecoder.decodeObject(forKey: Key.responseObjectContext.rawValue) as? MapContext } func encode(with aCoder: NSCoder) { aCoder.encode(self.cacheKey, forKey: Key.cacheKey.rawValue) aCoder.encode(self.creationDate, forKey: Key.creationDate.rawValue) aCoder.encode( self.responseStringEncoding.rawValue, forKey: Key.responseStringEncoding.rawValue) aCoder.encode(self.responseJSONOptions.rawValue, forKey: Key.responseJSONOptions.rawValue) aCoder.encode(self.responsePropertyListOptions.rawValue, forKey: Key.responsePropertyListOptions.rawValue) aCoder.encode(self.responseObjectKeyPath, forKey: Key.responseObjectKeyPath.rawValue) aCoder.encode(self.responseObjectContext, forKey: Key.responseObjectContext.rawValue) } //MARK: - Init override init() { self.cacheKey = "" self.creationDate = Date() self.responsePropertyListOptions = [] self.responseStringEncoding = .isoLatin1 self.responseJSONOptions = .allowFragments super.init() } }
mit
425a92d838e8553298103daf89d2d079
35.571429
172
0.72154
5.30963
false
false
false
false
gaurav1981/SwiftStructures
Source/Extensions/Int.swift
1
2453
// // Int.swift // SwiftStructures // // Created by Wayne Bishop on 7/1/16. // Copyright © 2016 Arbutus Software Inc. All rights reserved. // import Foundation extension Int { //iterates the closure body a specified number of times func times(closure:(Int)-> Void) { for i in 0...self { closure(i) } } //build fibonacci sequence to a specified position - default func fibNormal() -> Array<Int>! { //check trivial condition guard self > 2 else { return nil } //initialize the sequence var sequence: Array<Int> = [0, 1] var i: Int = sequence.count while i != self { let results: Int = sequence[i - 1] + sequence[i - 2] sequence.append(results) i += 1 } return sequence } //build fibonacci sequence to a specified position - recursive mutating func fibRecursive(_ sequence: Array<Int> = [0, 1]) -> Array<Int>! { var final = Array<Int>() //mutated copy var output = sequence //check trivial condition guard self > 2 else { return nil } let i: Int = output.count //set base condition if i == self { return output } let results: Int = output[i - 1] + output[i - 2] output.append(results) //set iteration final = self.fibRecursive(output) return final } //build fibonacci sequence to a specified position - trailing closure func fibClosure(withFormula formula: (Array<Int>) -> Int) -> Array<Int>! { //check trivial condition guard self > 2 else { return nil } //initialize the sequence var sequence: Array<Int> = [0, 1] var i: Int = sequence.count while i != self { let results: Int = formula(sequence) sequence.append(results) i += 1 } return sequence } //end function }
mit
b9328d070bd5a98e7194c4f8d291341c
18.307087
80
0.451876
5.307359
false
false
false
false
corinnekrych/aerogear-ios-sync
AeroGearSync/InMemoryDataStore.swift
2
2968
import Foundation public class InMemoryDataStore<T>: DataStore { private var documents = Dictionary<Key, ClientDocument<T>>() private var shadows = Dictionary<Key, ShadowDocument<T>>() private var backups = Dictionary<Key, BackupShadowDocument<T>>() private var edits = Dictionary<Key, [Edit]?>() public init() { } public func saveClientDocument(document: ClientDocument<T>) { let key = InMemoryDataStore.key(document.id, document.clientId) documents[key] = document } public func getClientDocument(documentId: String, clientId: String) -> ClientDocument<T>? { return documents[InMemoryDataStore.key(documentId, clientId)] } public func saveShadowDocument(shadow: ShadowDocument<T>) { let key = InMemoryDataStore.key(shadow.clientDocument.id, shadow.clientDocument.clientId) shadows[key] = shadow } public func getShadowDocument(documentId: String, clientId: String) -> ShadowDocument<T>? { return shadows[InMemoryDataStore.key(documentId, clientId)] } public func saveBackupShadowDocument(backup: BackupShadowDocument<T>) { let key = InMemoryDataStore.key(backup.shadowDocument.clientDocument.id, backup.shadowDocument.clientDocument.clientId) backups[key] = backup } public func getBackupShadowDocument(documentId: String, clientId: String) -> BackupShadowDocument<T>? { return backups[InMemoryDataStore.key(documentId, clientId)] } public func saveEdits(edit: Edit) { let key = InMemoryDataStore.key(edit.documentId, edit.clientId) if var pendingEdits = self.edits[key] { pendingEdits!.append(edit) self.edits.updateValue(pendingEdits, forKey: key) } else { self.edits.updateValue([edit], forKey: key) } } public func getEdits(documentId: String, clientId: String) -> [Edit]? { return edits[InMemoryDataStore.key(documentId, clientId)]? } public func removeEdit(edit: Edit) { let key = InMemoryDataStore.key(edit.documentId, edit.clientId) if var pendingEdits = edits[key]? { edits.updateValue(pendingEdits.filter { edit.serverVersion != $0.serverVersion }, forKey: key) } } public func removeEdits(documentId: String, clientId: String) { edits.removeValueForKey(Key(id: documentId, clientId: clientId)) } private class func key(id: String, _ clientId: String) -> Key { return Key(id: id, clientId: clientId) } } func ==(lhs: Key, rhs: Key) -> Bool { return lhs.hashValue == rhs.hashValue } struct Key: Hashable { let id: String let clientId: String init(id: String, clientId: String) { self.id = id self.clientId = clientId } var hashValue: Int { get { return "\(id),\(clientId)".hashValue } } }
apache-2.0
3be1126e0cd2801f10bb32537e9e08ac
31.977778
127
0.648248
4.351906
false
false
false
false
cocoascientist/Playgrounds
LocationTracking.playground/Sources/LocationTracker.swift
1
6150
// // LocationTracker.swift // LocationTracker // // Created by Andrew Shepard on 3/15/15. // Copyright (c) 2015 Andrew Shepard. All rights reserved. // import Foundation import CoreLocation /** The LocationTracker class defines a mechanism for determining the current location and observing location changes. */ public class LocationTracker: NSObject, CLLocationManagerDelegate { /// An alias for the location change observer type. public typealias Observer = (location: LocationResult) -> () /// The last location result received. Initially the location is unknown. private var lastResult: LocationResult = .Failure(LocationError.UnknownLocation) /// The collection of location observers private var observers: [Observer] = [] /// the minimum distance traveled before a location change is published. private let threshold: Double /// A `LocationResult` representing the current location. var currentLocation: LocationResult { return self.lastResult } /** Type representing either a Location or a Reason the location could not be determined. - Success: A successful result with a valid Location. - Failure: An unsuccessful result */ public enum LocationResult { case Success(Location) case Failure(ErrorType) } enum LocationError: ErrorType { case UnknownLocation case Other(NSError) } /** Location value representing a `CLLocation` and some local metadata. - physical: A CLLocation object for the current location. - city: The city the location is in. - state: The state the location is in. - neighborhood: The neighborhood the location is in. */ public struct Location: Equatable { public let physical: CLLocation public let city: String public let state: String public let neighborhood: String init(location physical: CLLocation, city: String, state: String, neighborhood: String) { self.physical = physical self.city = city self.state = state self.neighborhood = neighborhood } } /** Initializes a new LocationTracker with the default minimum distance threshold of 0 meters. :returns: LocationTracker with the default minimum distance threshold of 0 meters. */ public convenience override init() { self.init(threshold: 0.0) } /** Initializes a new LocationTracker with the specified minimum distance threshold. :param: threshold The minimum distance change in meters before a new location is published. :returns: LocationTracker with the specified minimum distance threshold. */ public init(threshold: Double) { self.threshold = threshold super.init() self.locationManager.startUpdatingLocation() } // MARK: - Public /** Adds a location change observer to execute whenever the location significantly changes. :param: observer The callback function to execute when a location change occurs. */ public func addLocationChangeObserver(observer: Observer) -> Void { observers.append(observer) } // MARK: - CLLocationManagerDelegate public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { locationManager.startUpdatingLocation() } public func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { let result = LocationResult.Failure(LocationError.Other(error)) self.publishChangeWithResult(result) self.lastResult = result } public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) { if let currentLocation = locations.first as? CLLocation { if shouldUpdateWithLocation(currentLocation) { CLGeocoder().reverseGeocodeLocation(currentLocation, completionHandler: { (placemarks, error) -> Void in if let placemark = placemarks?.first { if let city = placemark.locality { if let state = placemark.administrativeArea { if let neighborhood = placemark.subLocality { let location = Location(location: currentLocation, city: city, state: state, neighborhood: neighborhood) let result = LocationResult.Success(location) self.publishChangeWithResult(result) self.lastResult = result } } } } else { let result = LocationResult.Failure(LocationError.Other(error!)) self.publishChangeWithResult(result) self.lastResult = result } }) } // location hasn't changed significantly } } // MARK: - Private private lazy var locationManager: CLLocationManager = { let locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest return locationManager }() private func publishChangeWithResult(result: LocationResult) { for observer in observers { observer(location: result) } } private func shouldUpdateWithLocation(location: CLLocation) -> Bool { switch lastResult { case .Success(let loc): return location.distanceFromLocation(loc.physical) > threshold case .Failure: return true } } } public func ==(lhs: LocationTracker.Location, rhs: LocationTracker.Location) -> Bool { return lhs.physical == rhs.physical }
mit
228b932ddf3fdb99565ab31c2dd3323b
34.350575
140
0.61935
5.879541
false
false
false
false
glimpseio/BricBrac
Sources/Curio/Curio+Cocoa.swift
1
4170
// // Curio+Cocoa.swift // Bric-à-brac // // Created by Marc Prud'hommeaux on 7/20/15. // Copyright © 2010-2021 io.glimpse. All rights reserved. // /// NOTE: do not import any BricBrac framework headers; curiotool needs to be compiled as one big lump of source with no external frameworks import Foundation import BricBrac public extension Curio { /// Outputs a Swift file with the types for the given module. If the output text is the same as the destination /// file, then nothing will be output and the file will remain untouched, making this tool suitable to use /// as part of a build process (since it will not unnecessarily dirty a file). /// /// - Parameters: /// - module: the module to output /// - name: the rootname /// - dir: the folder /// - source: the schema source file (optional: to be included with `includeSchemaSourceVar`) /// - Returns: true if the schema was output successfully *and* it was different than any pre-existing file that is present func emit(_ module: CodeModule, name: String, dir: String, source: String? = nil) throws -> Bool { let locpath = (dir as NSString).appendingPathComponent(name) let emitter = CodeEmitter(stream: "") module.emit(emitter) var code = emitter.stream /// Embed the schema source string directly in the output file; the string can itself be parsed into a `JSONSchema` instance. if let includeSchemaSourceVar = includeSchemaSourceVar, let source = source { let parts = includeSchemaSourceVar.split(separator: ".") if parts.count == 2 { code += "\n\npublic extension \(parts[0]) {\n /// The source of the JSON Schema for this type.\n static let \(parts[1]): String = \"\"\"\n\(source)\n\"\"\"\n}\n" } else { code += "public var \(includeSchemaSourceVar) = \"\"\"\n\(source)\n\"\"\"" } } let tmppath = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) .appendingPathComponent(name) try code.write(toFile: tmppath.path, atomically: true, encoding: String.Encoding.utf8) let loccode: String do { loccode = try NSString(contentsOfFile: locpath, encoding: String.Encoding.utf8.rawValue) as String } catch { loccode = "" } if loccode == code { return false // contents are unchanged from local version; skip compiling } var status: Int32 = 0 #if false // os(macOS) // only on macOS until we can get swiftc working on Linux // If we can access the URL then try to compile the file if let bundle = Bundle(for: JSONParser.self).executableURL { let frameworkDir = bundle .deletingLastPathComponent() .deletingLastPathComponent() let args = [ "/usr/bin/xcrun", "swiftc", "-framework", "BricBrac", "-F", frameworkDir.path, "-o", tmppath.path, tmppath.path, ] print(args.joined(separator: " ")) let task = Process.launchedProcess(launchPath: args[0], arguments: Array(args.dropFirst())) task.waitUntilExit() status = task.terminationStatus if status != 0 { throw CodegenErrors.compileError("Could not compile \(tmppath)") } } #endif if status == 0 { if loccode != code { // if the code has changed, then write it to the test if FileManager.default.fileExists(atPath: locpath) { #if os(macOS) try FileManager.default.trashItem(at: URL(fileURLWithPath: locpath), resultingItemURL: nil) #else try FileManager.default.removeItem(at: URL(fileURLWithPath: locpath)) #endif } try code.write(toFile: locpath, atomically: true, encoding: String.Encoding.utf8) } } return true } }
mit
b78a0a2199a2c82474acee276caeab74
39.862745
183
0.587332
4.560175
false
false
false
false
nferocious76/NFImageView
Example/Pods/NFImageView/NFImageView/Classes/NFImageViewFunctions.swift
1
5529
// // NFImageViewFunctions.swift // Pods // // Created by Neil Francis Hipona on 23/07/2016. // Copyright (c) 2016 Neil Francis Ramirez Hipona. All rights reserved. // import Foundation import UIKit // MARK: - Public Functions extension NFImageView { /** * Force starting image loading */ public func forceStartLoadingState() { if !loadingEnabled { return } switch loadingType { case .Progress: loadingProgressView.hidden = false loadingProgressView.progress = 0.0 loadingProgressView.alpha = 0.0 UIView.animateWithDuration(0.25, animations: { self.loadingProgressView.alpha = 1.0 }) default: loadingIndicator.startAnimating() } } /** * Force stopping image loading */ public func forceStopLoadingState() { if !loadingEnabled { return } switch loadingType { case .Progress: loadingProgressView.alpha = 1.0 loadingProgressView.setProgress(0.0, animated: true) UIView.animateWithDuration(0.25, animations: { self.loadingProgressView.alpha = 0.0 }, completion: { _ in self.loadingProgressView.hidden = true }) default: loadingIndicator.stopAnimating() } } /** * Stop issued image download request */ public func cancelLoadImageRequest() { requestReceipt?.request.cancel() } /** * Set image from image URL string */ public func setImageFromURLString(URLString: String, completion: NFImageViewRequestCompletion? = nil) { if !URLString.isEmpty, let imageURL = NSURL(string: URLString) { setImageFromURL(imageURL, completion: completion) } } /** * Set image from image URL */ public func setImageFromURL(imageURL: NSURL, completion: NFImageViewRequestCompletion? = nil) { if !loadingEnabled { loadImage(imageURL, completion: completion) }else{ switch loadingType { case .Progress: loadImageWithProgress(imageURL, completion: completion) default: loadImageWithSpinner(imageURL, completion: completion) } } } /** * Set thumbnail and large image from URL sting with blur effect transition */ public func setThumbImageAndLargeImageFromURLString(thumbURLString thumbURLString: String, largeURLString: String, completion: NFImageViewRequestCompletion? = nil) { if !thumbURLString.isEmpty && !largeURLString.isEmpty, let thumbURL = NSURL(string: thumbURLString), let largeURL = NSURL(string: largeURLString) { if let cachedImage = NFImageCacheAPI.sharedAPI.checkForImageContentInCacheStorage(largeURL) { image = cachedImage // update cache for url request dispatch_async(NFImageCacheAPI.sharedAPI.imageDownloadQueue, { NFImageCacheAPI.sharedAPI.downloadImage(thumbURL) NFImageCacheAPI.sharedAPI.downloadImage(largeURL) }) }else{ setThumbImageAndLargeImageFromURL(thumbURL: thumbURL, largeURL: largeURL) } } } /** * Set thumbnail and large image from URL with blur effect transition */ public func setThumbImageAndLargeImageFromURL(thumbURL thumbURL: NSURL, largeURL: NSURL, completion: NFImageViewRequestCompletion? = nil) { if !loadingEnabled { loadImage(thumbURL, completion: { (code, error) in if code == .Success { self.loadImage(largeURL, completion: { (code, error) in completion?(code: code, error: error) }) }else{ completion?(code: code, error: error) } }) }else{ blurEffect.hidden = false switch loadingType { case .Progress: loadImageWithProgress(thumbURL, shouldContinueLoading: true, completion: { (code, error) in if code == .Success { self.loadImageWithProgress(largeURL, completion: { (code, error) in self.blurEffect.hidden = true completion?(code: code, error: error) }) }else{ self.blurEffect.hidden = true completion?(code: code, error: error) } }) default: loadImageWithSpinner(thumbURL, completion: { (code, error) in if code == .Success { self.loadImageWithSpinner(largeURL, completion: { (code, error) in self.blurEffect.hidden = true completion?(code: code, error: error) }) }else{ self.blurEffect.hidden = true completion?(code: code, error: error) } }) } } } }
mit
7adeee7d09a3ce61a3ce660906d9fb8d
32.92638
169
0.52939
5.529
false
false
false
false
russbishop/swift
test/PrintAsObjC/enums.swift
1
4654
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-doc -o %t %s -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/enums.swiftmodule -parse -emit-objc-header-path %t/enums.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module // RUN: FileCheck %s < %t/enums.h // RUN: FileCheck -check-prefix=NEGATIVE %s < %t/enums.h // RUN: %check-in-clang %t/enums.h // RUN: %check-in-clang -fno-modules -Qunused-arguments %t/enums.h -include Foundation.h -include ctypes.h -include CoreFoundation.h // REQUIRES: objc_interop import Foundation // NEGATIVE-NOT: NSMalformedEnumMissingTypedef : // NEGATIVE-NOT: enum EnumNamed // CHECK-LABEL: enum FooComments : NSInteger; // CHECK-LABEL: enum NegativeValues : int16_t; // CHECK-LABEL: enum ObjcEnumNamed : NSInteger; // CHECK-LABEL: @interface AnEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo; // CHECK-NEXT: - (void)acceptPlainEnum:(enum NSMalformedEnumMissingTypedef)_; // CHECK-NEXT: - (enum ObjcEnumNamed)takeAndReturnRenamedEnum:(enum ObjcEnumNamed)foo; // CHECK: @end @objc class AnEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } @objc func acceptPlainEnum(_: MalformedEnumMissingTypedef) {} @objc func takeAndReturnRenamedEnum(_ foo: EnumNamed) -> EnumNamed { return .A } } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcEnumNamed, "EnumNamed") { // CHECK-NEXT: ObjcEnumNamedA = 0, // CHECK-NEXT: ObjcEnumNamedB = 1, // CHECK-NEXT: ObjcEnumNamedC = 2, // CHECK-NEXT: ObjcEnumNamedD = 3, // CHECK-NEXT: ObjcEnumNamedHelloDolly = 4, // CHECK-NEXT: }; @objc(ObjcEnumNamed) enum EnumNamed: Int { case A, B, C, d, helloDolly } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, EnumWithNamedConstants) { // CHECK-NEXT: kEnumA SWIFT_COMPILE_NAME("A") = 0, // CHECK-NEXT: kEnumB SWIFT_COMPILE_NAME("B") = 1, // CHECK-NEXT: kEnumC SWIFT_COMPILE_NAME("C") = 2, // CHECK-NEXT: }; @objc enum EnumWithNamedConstants: Int { @objc(kEnumA) case A @objc(kEnumB) case B @objc(kEnumC) case C } // CHECK-LABEL: typedef SWIFT_ENUM(unsigned int, ExplicitValues) { // CHECK-NEXT: ExplicitValuesZim = 0, // CHECK-NEXT: ExplicitValuesZang = 219, // CHECK-NEXT: ExplicitValuesZung = 220, // CHECK-NEXT: }; // NEGATIVE-NOT: ExplicitValuesDomain @objc enum ExplicitValues: CUnsignedInt { case Zim, Zang = 219, Zung func methodNotExportedToObjC() {} } // CHECK: /** // CHECK-NEXT: Foo: A feer, a female feer. // CHECK-NEXT: */ // CHECK-NEXT: typedef SWIFT_ENUM(NSInteger, FooComments) { // CHECK: /** // CHECK-NEXT: Zim: A zeer, a female zeer. // CHECK: */ // CHECK-NEXT: FooCommentsZim = 0, // CHECK-NEXT: FooCommentsZang = 1, // CHECK-NEXT: FooCommentsZung = 2, // CHECK-NEXT: }; /// Foo: A feer, a female feer. @objc public enum FooComments: Int { /// Zim: A zeer, a female zeer. case Zim case Zang, Zung } // CHECK-LABEL: typedef SWIFT_ENUM(int16_t, NegativeValues) { // CHECK-NEXT: Zang = -219, // CHECK-NEXT: Zung = -218, // CHECK-NEXT: }; @objc enum NegativeValues: Int16 { case Zang = -219, Zung func methodNotExportedToObjC() {} } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeErrorProtocol) { // CHECK-NEXT: SomeErrorProtocolBadness = 9001, // CHECK-NEXT: SomeErrorProtocolWorseness = 9002, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const SomeErrorProtocolDomain = @"enums.SomeErrorProtocol"; @objc enum SomeErrorProtocol: Int, ErrorProtocol { case Badness = 9001 case Worseness } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeOtherErrorProtocol) { // CHECK-NEXT: SomeOtherErrorProtocolDomain = 0, // CHECK-NEXT: }; // NEGATIVE-NOT: NSString * _Nonnull const SomeOtherErrorProtocolDomain @objc enum SomeOtherErrorProtocol: Int, ErrorProtocol { case Domain // collision! } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcErrorType, "SomeRenamedErrorType") { // CHECK-NEXT: ObjcErrorTypeBadStuff = 0, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const ObjcErrorTypeDomain = @"enums.SomeRenamedErrorType"; @objc(ObjcErrorType) enum SomeRenamedErrorType: Int, ErrorProtocol { case BadStuff } // CHECK-NOT: enum {{[A-Z]+}} // CHECK-LABEL: @interface ZEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo; // CHECK: @end @objc class ZEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } }
apache-2.0
3acb33ab576e99e2a803cd5e557761ba
32.970803
228
0.709712
3.247732
false
false
false
false
viniciusaro/SwiftResolver
Sources/DependencyPool.swift
1
3826
final class DependencyPool { private var factories: Atomic<[String: AnyFactory]> = Atomic([:]) private var sharedInstances = InstancePool() private var singletonInstances = InstancePool() func clearShared() { self.sharedInstances.clear() } func instanceCountFor<T>(type: T.Type) -> Int { let identifier = String(describing: T.self) guard let factory = self.factories.value[identifier] else { return 0 } return factory.instanceCount } } extension DependencyPool { func register<Factory: FactoryType>(_ factory: Factory) -> TypeSpecifier { self.internalRegister(factory) return TypeSpecifier(onRegister: { identifier in self.internalRegister(factory, specificIdentifier: identifier) }) } private func internalRegister<Factory: FactoryType>(_ factory: Factory, specificIdentifier: String = "") { let elementTypeIdentifier = String(describing: Factory.Element.self).withoutTypeExtension let typeSpecificIdentifier = specificIdentifier.withoutTypeExtension let identifier = elementTypeIdentifier + typeSpecificIdentifier self.factories.mutate { $0[identifier] = factory.asAny() } if typeSpecificIdentifier.count > 0 { self.factories.mutate { $0[typeSpecificIdentifier] = factory.asAny() } } } } extension DependencyPool { func instance<T>() throws -> T { let identifier = String(describing: T.self).withoutTypeExtension return try self.instance(identifier: identifier) } func instance<T>(tag: String) throws -> T { let elementType = String(describing: T.self).withoutTypeExtension let identifier = elementType + tag return try self.instance(identifier: identifier) } func instance<GenericType, ImplementationType>(_ elementType: ImplementationType) throws -> GenericType { let elementTypeIdentifier = String(describing: ImplementationType.self).withoutTypeExtension let typeSpecificIdentifier = String(describing: GenericType.self).withoutTypeExtension let identifier = elementTypeIdentifier + typeSpecificIdentifier return try self.instance(identifier: identifier) } private func instance<T>(identifier: String) throws -> T { guard let factory = self.factories.value[identifier] else { throw ContainerError.unregisteredValue(T.self) } switch factory.scope { case .instance: return try self.buildInstance(with: factory) case .shared: return try self.buildSharedInstance(with: factory) case .singleton: return try self.buildSingletonInstance(with: factory) } } } extension DependencyPool { private func buildInstance<T>(with factory: AnyFactory) throws -> T { guard let element = try factory.build() as? T else { throw ContainerError.unregisteredValue(T.self) } return element } private func buildSharedInstance<T>(with factory: AnyFactory) throws -> T { if let element: T = self.sharedInstances.get() { return element } guard let element = try factory.build() as? T else { throw ContainerError.unregisteredValue(T.self) } self.sharedInstances.register(instance: element) return element } private func buildSingletonInstance<T>(with factory: AnyFactory) throws -> T { if let element: T = self.singletonInstances.get() { return element } guard let element = try factory.build() as? T else { throw ContainerError.unregisteredValue(T.self) } self.singletonInstances.register(instance: element) return element } }
mit
0503c12a40023c074673c2db48283fc0
36.881188
110
0.66414
4.867684
false
false
false
false
gerardogrisolini/iWebretail
iWebretail/MovementController.swift
1
6626
// // MovementController.swift // iWebretail // // Created by Gerardo Grisolini on 12/04/17. // Copyright © 2017 Gerardo Grisolini. All rights reserved. // import UIKit class MovementController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var amountLabel: UILabel! var label: UILabel! var movementArticles: [MovementArticle] private var repository: MovementArticleProtocol required init?(coder aDecoder: NSCoder) { self.movementArticles = [] repository = IoCContainer.shared.resolve() as MovementArticleProtocol super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self makeBar() } func makeBar() { // badge label label = UILabel(frame: CGRect(x: 8, y: -4, width: 29, height: 20)) label.layer.borderColor = UIColor.clear.cgColor label.layer.borderWidth = 2 label.layer.cornerRadius = label.bounds.size.height / 2 label.textAlignment = .center label.layer.masksToBounds = true label.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 600)) label.textColor = .darkText if Synchronizer.shared.movement.completed { label.backgroundColor = UIColor(name: "whitesmoke") } else { label.backgroundColor = UIColor(name: "lightgreen") } // button let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 29, height: 29)) let basket = UIImage(named: "basket")?.withRenderingMode(.alwaysTemplate) rightButton.setImage(basket, for: .normal) rightButton.tintColor = UINavigationBar.appearance().tintColor rightButton.addTarget(self, action: #selector(rightButtonTouched), for: .touchUpInside) rightButton.addSubview(label) // Bar button item self.tabBarController?.tabBar.tintColor = UINavigationBar.appearance().tintColor self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) } @objc func rightButtonTouched(sender: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "RegisterView") as! RegisterController self.navigationController!.pushViewController(vc, animated: true) } override func viewDidAppear(_ animated: Bool) { self.movementArticles = try! repository.getAll(id: Synchronizer.shared.movement.movementId) self.updateAmount() tableView.reloadData() } @IBAction func stepperValueChanged(_ sender: UIStepper) { let point = sender.convert(CGPoint(x: 0, y: 0), to: tableView) let indexPath = self.tableView.indexPathForRow(at: point)! let item = movementArticles[indexPath.row] let cell = tableView.cellForRow(at: indexPath) as! ArticleCell item.movementArticleQuantity = sender.value cell.textQuantity.text = String(sender.value) cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice) try! repository.update(id: item.movementArticleId, item: item) self.updateAmount() } @IBAction func textValueChanged(_ sender: UITextField) { let point = sender.convert(CGPoint(x: 0, y: 0), to: tableView) let indexPath = self.tableView.indexPathForRow(at: point)! let item = movementArticles[indexPath.row] let cell = tableView.cellForRow(at: indexPath) as! ArticleCell if sender == cell.textQuantity { item.movementArticleQuantity = Double(sender.text!)! cell.stepperQuantity.value = item.movementArticleQuantity } else { item.movementArticlePrice = Double(sender.text!)! } cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice) try! repository.update(id: item.movementArticleId, item: item) self.updateAmount() } func updateAmount() { let amount = movementArticles .map { $0.movementArticleQuantity * $0.movementArticlePrice as Double } .reduce (0, +) amountLabel.text = amount.formatCurrency() let quantity = movementArticles .map { $0.movementArticleQuantity } .reduce (0, +) label.text = quantity.description if Synchronizer.shared.movement.movementAmount != amount { try! repository.updateAmount(item: Synchronizer.shared.movement, amount: amount) } } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movementArticles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath) as! ArticleCell let index = (indexPath as NSIndexPath).row let item = movementArticles[index] cell.labelBarcode.text = item.movementArticleBarcode cell.labelName.text = item.movementProduct cell.textPrice.text = String(item.movementArticlePrice) cell.textQuantity.text = String(item.movementArticleQuantity) cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice) cell.stepperQuantity.value = item.movementArticleQuantity return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return !Synchronizer.shared.movement.completed } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { do { try repository.delete(id: self.movementArticles[indexPath.row].movementArticleId) self.movementArticles.remove(at: indexPath.row) self.updateAmount() tableView.deleteRows(at: [indexPath], with: .fade) } catch { self.navigationController?.alert(title: "Error".locale, message: "\(error)") } } } }
apache-2.0
6abad016cc39a1c41d9dbcebe7f8ee05
37.970588
127
0.653887
4.849927
false
false
false
false
akihiro0228/ColorGaugeView
Pod/Classes/ColorGaugeView.swift
1
5131
// // ColorGaugeView.swift // Pods // // Created by akihiro on 2015/07/14. // // import UIKit public enum ColorGaugeType { case LeftToRight case RightToLeft case BottomToTop case TopToBottom } @IBDesignable public class ColorGaugeView : UIView { // subviews private let gaugeView : UIView = UIView(frame: CGRectZero) private let gaugeBarView : UIView = UIView(frame: CGRectZero) private let restBarView : UIView = UIView(frame: CGRectZero) // gauge range private let gaugeMin : Float = 0 private var gaugeMax : Float = 0 // gauge type public var type : ColorGaugeType = .LeftToRight { didSet { self.layoutBars(CGFloat(self.gauge - Float(Int(self.gauge)))) } } // gauge value public var gauge : Float = 0 { didSet { if gauge <= gaugeMin { gauge = gaugeMin } if gauge >= gaugeMax { gauge = gaugeMax } self.updateGauge() } } // gauge bar colors public var barColors : [UIColor] = [] { didSet { self.gaugeMax = Float(barColors.count) } } // gauge background color @IBInspectable public var defaultColor: UIColor = UIColor.clearColor() { didSet { self.gaugeView.backgroundColor = defaultColor } } // gauge border color @IBInspectable public var borderColor: UIColor = UIColor.clearColor() { didSet { self.gaugeView.layer.borderColor = borderColor.CGColor } } // gauge border width @IBInspectable public var borderWidth: CGFloat = 0 { didSet { self.gaugeView.layer.borderWidth = borderWidth } } // gauge border radius @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { self.gaugeView.layer.cornerRadius = cornerRadius } } // show only IB override public func prepareForInterfaceBuilder() { self.gaugeView.frame.size = self.frame.size self.addSubview(self.gaugeView) self.gaugeView.layer.borderColor = borderColor.CGColor self.gaugeView.layer.borderWidth = borderWidth self.gaugeView.layer.cornerRadius = cornerRadius } // initialize override public init(frame: CGRect) { super.init(frame: frame) self.setupView() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupView() } private func setupView() { self.gaugeView.frame = self.bounds self.gaugeView.setTranslatesAutoresizingMaskIntoConstraints(true) self.gaugeView.autoresizingMask = UIViewAutoresizing.FlexibleWidth|UIViewAutoresizing.FlexibleHeight self.gaugeView.clipsToBounds = true self.addSubview(self.gaugeView) self.gaugeView.addSubview(self.gaugeBarView) self.gaugeView.addSubview(self.restBarView) } private func updateGauge() { let restIndex = Int(self.gauge) let progress = CGFloat(self.gauge - Float(restIndex)) if restIndex != 0 { self.restBarView.backgroundColor = self.barColors[restIndex - 1] } if progress != 0 { self.gaugeBarView.backgroundColor = self.barColors[restIndex] } self.layoutBars(progress) if restIndex == 0 { self.restBarView.frame = CGRectZero } } private func layoutBars(progress: CGFloat) { switch self.type { case .LeftToRight: self.layoutLeftToRight(progress) case .RightToLeft: self.layoutRightToLeft(progress) case .BottomToTop: self.layoutBottomToTop(progress) case .TopToBottom: self.layoutTopToBottom(progress) } } // layout bar methods private func layoutLeftToRight(progress: CGFloat) { self.gaugeBarView.frame = CGRectMake(0, 0, self.frame.size.width * progress, self.frame.size.height) self.restBarView.frame = CGRectMake(self.gaugeBarView.frame.size.width, 0, self.frame.size.width - self.gaugeBarView.frame.size.width, self.frame.size.height) } private func layoutRightToLeft(progress: CGFloat) { self.restBarView.frame = CGRectMake(0, 0, self.frame.size.width * (1 - progress), self.frame.size.height) self.gaugeBarView.frame = CGRectMake(self.restBarView.frame.size.width, 0, self.frame.size.width - self.restBarView.frame.size.width, self.frame.size.height) } private func layoutTopToBottom(progress: CGFloat) { self.gaugeBarView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height * progress) self.restBarView.frame = CGRectMake(0, self.gaugeBarView.frame.size.height, self.frame.size.width, self.frame.size.height - self.gaugeBarView.frame.size.height) } private func layoutBottomToTop(progress: CGFloat) { self.restBarView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height * (1 - progress)) self.gaugeBarView.frame = CGRectMake(0, self.restBarView.frame.size.height, self.frame.size.width, self.frame.size.height - self.restBarView.frame.size.height) } }
mit
40b144966fb0ccd4cc6754fad8a67371
31.481013
168
0.659326
4.219572
false
false
false
false
shaoyihe/100-Days-of-IOS
13 - STICKY SECTION HEADERS/13 - STICKY SECTION HEADERS/MovieStore.swift
1
886
// // MovieStore.swift // 12 - ADD NEW ITEM // // Created by heshaoyi on 3/9/16. // Copyright © 2016 heshaoyi. All rights reserved. // import UIKit class MovieStore { var moviesDic = [String : [Movie]]() var movieIndex = [Int : String]() init(){ ["Iron Man", "Spider Man", "Jaws", "7 Years", "America history x", "Alies", "Java", "Ruby", "Swift", "IOS", "Node", "C#","Python"].forEach{ let nameIndex = $0.startIndex let movieIndex = $0.substringToIndex(nameIndex.successor()) if let _ = moviesDic[movieIndex]{ moviesDic[movieIndex]?.append(Movie($0)) }else{ moviesDic[movieIndex] = [Movie($0)] } } for(i , v) in moviesDic.keys.sort({return $0 <= $1}).enumerate() { movieIndex[i] = v } } }
mit
c23455c192869933ca9a953e4d4ada97
25.029412
147
0.509605
3.627049
false
false
false
false
gminky019/Content-Media-App
Content Media App/Content Media App/ViewController.swift
1
42148
// // ViewController.swift // Content Media App // // Created by Garrett Minky on 2/27/16. // Copyright © 2016 Garrett Minky. All rights reserved. // /* Main controller for the main page and loading pages */ import QuartzCore import UIKit class ViewController: UIViewController { @IBOutlet weak var menuButton: UIBarButtonItem! @IBOutlet weak var heroOneView: UIImageView! @IBOutlet weak var heroTwoView: UIImageView! @IBOutlet weak var heroThreeView: UIImageView! @IBOutlet weak var heroOneTitle: UITextView! @IBOutlet weak var heroTwoTitle: UITextView! @IBOutlet weak var heroThreeTitle: UITextView! @IBOutlet weak var heroOneType: UITextView! @IBOutlet weak var heroTwoType: UITextView! @IBOutlet weak var heroThreeType: UITextView! @IBOutlet weak var heroOneIcon: UIImageView! @IBOutlet weak var heroTwoIcon: UIImageView! @IBOutlet weak var heroThreeIcon: UIImageView! @IBOutlet weak var articleOne: UIImageView! @IBOutlet weak var articleTwo: UIImageView! @IBOutlet weak var articleThree: UIImageView! @IBOutlet weak var articleFour: UIImageView! @IBOutlet weak var articleOneType: UITextView! @IBOutlet weak var articleTwoType: UITextView! @IBOutlet weak var articleThreeType: UITextView! @IBOutlet weak var articleFourType: UITextView! @IBOutlet weak var articleOneTitle: UITextView! @IBOutlet weak var articleTwoTitle: UITextView! @IBOutlet weak var articleThreeTitle: UITextView! @IBOutlet weak var articleFourTitle: UITextView! @IBOutlet weak var articleOneIcon: UIImageView! @IBOutlet weak var articleTwoIcon: UIImageView! @IBOutlet weak var articleThreeIcon: UIImageView! @IBOutlet weak var articleFourIcon: UIImageView! @IBOutlet weak var watchHero: UIImageView! @IBOutlet weak var watchHeroTitle: UITextView! @IBOutlet weak var watchHeroType: UITextView! @IBOutlet weak var watchHeroIcon: UIImageView! @IBOutlet weak var watchArticleOne: UIImageView! @IBOutlet weak var watchArticleTwo: UIImageView! @IBOutlet weak var watchArticleOneType: UITextView! @IBOutlet weak var watchArticleTwoType: UITextView! @IBOutlet weak var watchArticleOneTitle: UITextView! @IBOutlet weak var watchArticleTwoTitle: UITextView! @IBOutlet weak var watchArticleOneIcon: UIImageView! @IBOutlet weak var watchArticleTwoIcon: UIImageView! @IBOutlet weak var readHero: UIImageView! @IBOutlet weak var readHeroTitle: UITextView! @IBOutlet weak var readHeroType: UITextView! @IBOutlet weak var readHeroIcon: UIImageView! @IBOutlet weak var readArticleOne: UIImageView! @IBOutlet weak var readArticleTwo: UIImageView! @IBOutlet weak var readArticleOneType: UITextView! @IBOutlet weak var readArticleTwoType: UITextView! @IBOutlet weak var readArticleOneTitle: UITextView! @IBOutlet weak var readArticleTwoTitle: UITextView! @IBOutlet weak var readArticleOneIcon: UIImageView! @IBOutlet weak var readArticleTwoIcon: UIImageView! @IBOutlet weak var learnHero: UIImageView! @IBOutlet weak var learnHeroTitle: UITextView! @IBOutlet weak var learnHeroType: UITextView! @IBOutlet weak var learnHeroIcon: UIImageView! @IBOutlet weak var learnArticleOne: UIImageView! @IBOutlet weak var learnArticleTwo: UIImageView! @IBOutlet weak var learnArticleOneType: UITextView! @IBOutlet weak var learnArticleTwoType: UITextView! @IBOutlet weak var learnArticleOneTitle: UITextView! @IBOutlet weak var learnArticleTwoTitle: UITextView! @IBOutlet weak var learnArticleOneIcon: UIImageView! @IBOutlet weak var learnArticleTwoIcon: UIImageView! @IBOutlet weak var watchLabel: UITextView! @IBOutlet weak var readLabel: UITextView! @IBOutlet weak var learnLabel: UITextView! @IBOutlet weak var shopLabel: UITextView! @IBOutlet weak var shopHero: UIImageView! @IBOutlet weak var shopHeroTitle: UITextView! @IBOutlet weak var shopHeroType: UITextView! @IBOutlet weak var shopHeroIcon: UIImageView! @IBOutlet weak var shopArticleOne: UIImageView! @IBOutlet weak var shopArticleTwo: UIImageView! @IBOutlet weak var shopArticleOneType: UITextView! @IBOutlet weak var shopArticleTwoType: UITextView! @IBOutlet weak var shopArticleOneTitle: UITextView! @IBOutlet weak var shopArticleTwoTitle: UITextView! @IBOutlet weak var shopArticleOneIcon: UIImageView! @IBOutlet weak var shopArticleTwoIcon: UIImageView! @IBOutlet weak var footerImageOne: UIImageView! @IBOutlet weak var footerImageTwo: UIImageView! @IBOutlet weak var footerImageThree: UIImageView! @IBOutlet weak var footerImageFour: UIImageView! @IBOutlet weak var footerBackground: UIImageView! var articleClicked = "null" // Hero Articles var contDict: [String: ThumbNail] = [String: ThumbNail]() var passedThumbnail: ThumbNail! var imageHeroOne = UIImage (named: "tempHeroOne.jpg") var titleHeroOne = "Ice Melting In Arctic: How can you save the polar bears?" var typeHeroOne = "READ" var imageHeroTwo = UIImage (named: "tempHeroTwo.jpg") var titleHeroTwo = "Monkeys of the Jungle" var typeHeroTwo = "READ" var imageHeroThree = UIImage (named: "tempHeroThree.jpg") var titleHeroThree = "Dolphins: Communication with Sonar" var typeHeroThree = "LEARN" // Featured Articles var imageArticleOne = UIImage (named: "tempArtOne.jpg") var titleArticleOne = "Jungle Book: Out Now, and it's good!" var typeArticleOne = "READ" var imageArticleTwo = UIImage (named: "tempArtTwo.jpg") var titleArticleTwo = "The Incredibly Diverse Ecosystem in Just This River Will Blow Your Mind" var typeArticleTwo = "LEARN" var imageArticleThree = UIImage (named: "bb8.png") var titleArticleThree = "BB8 Saves The Day" var typeArticleThree = "WATCH" var imageArticleFour = UIImage (named: "kyloren.png") var titleArticleFour = "Learn The Dark Side of The Force with Kylo Ren" var typeArticleFour = "LEARN" // Watch Articles var imageWatchHero = UIImage(named: "MileniumFalcon.png") var titleWatchHero = "Millennium Falcon: Kessel Run in 12 Parsecs" var typeWatchHero = "RE/MX" var imageWatchArticleOne = UIImage(named: "DarthMal.png") var titleWatchArticleOne = "Darth Mal: What was his downfall?" var typeWatchArticleOne = "WATCH" var imageWatchArticleTwo = UIImage(named: "r2d2.png") var titleWatchArticleTwo = "Why didn't R2D2 give up the map earlier?" var typeWatchArticleTwo = "RE/MX" // Read Articles var imageReadHero = UIImage(named: "DarthMal.png") var titleReadHero = "Darth Mal: What was his downfall?" var typeReadHero = "RE/MX" var imageReadArticleOne = UIImage(named: "r2d2.png") var titleReadArticleOne = "Why didn't R2D2 give up the map earlier?" var typeReadArticleOne = "WATCH" var imageReadArticleTwo = UIImage(named: "MileniumFalcon.png") var titleReadArticleTwo = "Millennium Falcon: Kessel Run in 12 Parsecs" var typeReadArticleTwo = "RE/MX" // Learn Articles var imageLearnHero = UIImage(named: "r2d2.png") var titleLearnHero = "Why didn't R2D2 give up the map earlier?" var typeLearnHero = "RE/MX" var imageLearnArticleOne = UIImage(named: "DarthMal.png") var titleLearnArticleOne = "Darth Mal: What was his downfall?" var typeLearnArticleOne = "WATCH" var imageLearnArticleTwo = UIImage(named: "MileniumFalcon.png") var titleLearnArticleTwo = "Millennium Falcon: Kessel Run in 12 Parsecs" var typeLearnArticleTwo = "RE/MX" // Shop Articles var imageShopHero = UIImage (named: "tempArtTwo.jpg") var titleShopHero = "The Incredibly Diverse Ecosystem in Just This River Will Blow Your Mind" var typeShopHero = "RE/MX" var imageShopArticleOne = UIImage(named: "DarthMal.png") var titleShopArticleOne = "Darth Mal: What was his downfall?" var typeShopArticleOne = "WATCH" var imageShopArticleTwo = UIImage(named: "MileniumFalcon.png") var titleShopArticleTwo = "Millennium Falcon: Kessel Run in 12 Parsecs" var typeShopArticleTwo = "RE/MX" override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(frame: CGRect(x:0, y:0, width: 86, height: 44)) let image = UIImage(named: "Logo.png") imageView.contentMode = .ScaleAspectFit imageView.image = image navigationItem.titleView = imageView var overlay : UIView //var cdaLogo = UIImage(named: "CDALoadingLogo.png") overlay = UIView(frame: view.frame) //overlay.backgroundColor = UIColor.whiteColor() //overlay.alpha = 1.0 let backgroundOverlay = UIImage(named: "BackgroundImageLoading2.png") let backgroundView = UIImageView(image: backgroundOverlay) var activityIndicator = UIActivityIndicatorView() activityIndicator.frame = CGRectMake(0, 0, 40, 40) activityIndicator.activityIndicatorViewStyle = .WhiteLarge activityIndicator.center = CGPointMake(overlay.bounds.width / 2, (overlay.bounds.height / 3)*2) //let logoView = UIImageView(image: cdaLogo) //logoView.frame = CGRectMake((overlay.bounds.width / 2) - 317/2, (overlay.bounds.height / 7), 317, 400) backgroundView.addSubview(activityIndicator) //overlay.addSubview(activityIndicator) //overlay.addSubview(logoView) view.addSubview(backgroundView) activityIndicator.startAnimating() let typeColor = UIColor.init(red: 221/255, green: 180/255, blue: 0/255, alpha: 1) // Navigation if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } var mainP: MainPageContent? var integrate: MiddleIntegration = MiddleIntegration() /* integrate.getReadPage(){(returned: ContentPage) in var thatHolder = 0 }*/ integrate.getMainPage(){ (main: MainPageContent) in mainP = main // Hero Articles let heroOne = mainP!.hero[0] as! ThumbNail let heroTwo = mainP!.hero[1] as! ThumbNail let heroThree = mainP!.hero[2] as! ThumbNail self.contDict["HeroOne"] = heroOne self.contDict["HeroTwo"] = heroTwo self.contDict["HeroThree"] = heroThree // Hero One self.heroOneView.image = heroOne.pic self.imageHeroOne = self.heroOneView.image self.heroOneTitle.text = heroOne.title self.heroOneTitle.font = UIFont(name: "Roboto-Bold", size: 18) self.heroOneTitle.textColor = UIColor.whiteColor() self.heroOneIcon.image = UIImage(named: "readicon.png") // Hero Two self.heroTwoView.image = heroTwo.pic self.heroTwoTitle.text = heroTwo.title self.heroTwoTitle.font = UIFont(name: "Roboto-Bold", size: 18) self.heroTwoTitle.textColor = UIColor.whiteColor() self.heroTwoIcon.image = UIImage(named: "readicon.png") // Hero Three self.heroThreeView.image = heroThree.pic self.heroThreeTitle.text = heroThree.title self.heroThreeTitle.font = UIFont(name: "Roboto-Bold", size: 18) self.heroThreeTitle.textColor = UIColor.whiteColor() self.heroThreeIcon.image = UIImage(named: "readicon.png") // Featured Articles let featuredOne = mainP!.subHero[0] as! ThumbNail let featuredTwo = mainP!.subHero[1] as! ThumbNail let featuredThree = mainP!.subHero[2] as! ThumbNail let featuredFour = mainP!.subHero[3] as! ThumbNail self.contDict["featuredOne"] = featuredOne self.contDict["featuredTwo"] = featuredTwo self.contDict["featuredThree"] = featuredThree self.contDict["featuredFour"] = featuredFour // Featured One self.articleOne.image = featuredOne.pic self.articleOneTitle.text = featuredOne.title self.articleOneTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.articleOneTitle.textColor = UIColor.blackColor() self.articleOneTitle.textAlignment = .Center self.articleOneIcon.image = UIImage(named: "readIconSmall.png") // Featured Two self.articleTwo.image = featuredTwo.pic self.articleTwoTitle.text = featuredTwo.title self.articleTwoTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.articleTwoTitle.textColor = UIColor.blackColor() self.articleTwoTitle.textAlignment = .Center self.articleTwoIcon.image = UIImage(named: "readIconSmall.png") // Featured Three self.articleThree.image = featuredThree.pic self.articleThreeTitle.text = featuredThree.title self.articleThreeTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.articleThreeTitle.textColor = UIColor.blackColor() self.articleThreeTitle.textAlignment = .Center self.articleThreeIcon.image = UIImage(named: "readIconSmall.png") // Featured Four self.articleFour.image = featuredFour.pic self.articleFourTitle.text = featuredFour.title self.articleFourTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.articleFourTitle.textColor = UIColor.blackColor() self.articleFourTitle.textAlignment = .Center self.articleFourIcon.image = UIImage(named: "readIconSmall.png") let contentHero:[SubHero] = mainP!.contentHero // Load content from backend into content views for categoryHero in contentHero { let mainH : ThumbNail = categoryHero.main as! ThumbNail let subC: [Content] = categoryHero.sub let sub1: ThumbNail = subC[0] as! ThumbNail let sub2: ThumbNail = subC[1] as! ThumbNail switch categoryHero.type { case "read": self.readHero.image = mainH.pic self.readHeroTitle.text = mainH.title self.readHeroType.text = categoryHero.type self.readHeroIcon.image = UIImage (named: "readicon.png") self.readArticleOne.image = sub1.pic self.readArticleOneTitle.text = sub1.title self.readArticleOneType.text = categoryHero.type self.readArticleOneIcon.image = UIImage (named: "readIconSmall.png") self.readArticleTwo.image = sub2.pic self.readArticleTwoTitle.text = sub2.title self.readArticleTwoType.text = categoryHero.type self.readArticleTwoIcon.image = UIImage (named: "readIconSmall.png") self.contDict["readHero"] = mainH self.contDict["readArticleOne"] = sub1 self.contDict["readArticleTwo"] = sub2 case "watch": self.watchHero.image = mainH.pic self.watchHeroTitle.text = mainH.title self.watchHeroType.text = categoryHero.type self.watchArticleOne.image = sub1.pic self.watchArticleOneTitle.text = sub1.title self.watchArticleOneType.text = categoryHero.type self.watchArticleTwo.image = sub2.pic self.watchArticleTwoTitle.text = sub2.title self.watchArticleTwoType.text = categoryHero.type self.watchHeroIcon.image = UIImage (named: "playicon.png") self.watchArticleOneIcon.image = UIImage (named: "playiconsmall.png") self.watchArticleTwoIcon.image = UIImage (named: "playiconsmall.png") self.contDict["watchHero"] = mainH self.contDict["watchArticleOne"] = sub1 self.contDict["watchArticleTwo"] = sub2 case "shop": self.shopHero.image = mainH.pic self.shopHeroTitle.text = mainH.title self.shopHeroType.text = categoryHero.type self.shopArticleOne.image = sub1.pic self.shopArticleOneTitle.text = sub1.title self.shopArticleOneType.text = categoryHero.type self.shopArticleTwo.image = sub2.pic self.shopArticleTwoTitle.text = sub2.title self.shopArticleTwoType.text = categoryHero.type self.shopHeroIcon.image = UIImage (named: "readicon.png") self.shopArticleOneIcon.image = UIImage (named: "readIconSmall.png") self.shopArticleTwoIcon.image = UIImage (named: "readIconSmall.png") self.contDict["shopHero"] = mainH self.contDict["shopArticleOne"] = sub1 self.contDict["shopArticleTwo"] = sub2 case "learn": self.learnHero.image = mainH.pic self.learnHeroTitle.text = mainH.title self.learnHeroType.text = categoryHero.type self.learnArticleOne.image = sub1.pic self.learnArticleOneTitle.text = sub1.title self.learnArticleOneType.text = categoryHero.type self.learnArticleTwo.image = sub2.pic self.learnArticleTwoTitle.text = sub2.title self.learnArticleTwoType.text = categoryHero.type self.learnHeroIcon.image = UIImage (named: "readicon.png") self.learnArticleOneIcon.image = UIImage (named: "readIconSmall.png") self.learnArticleTwoIcon.image = UIImage (named: "readIconSmall.png") self.contDict["learnHero"] = mainH self.contDict["learnArticleOne"] = sub1 self.contDict["learnArticleTwo"] = sub2 default: break } // Watch self.watchHeroTitle.font = UIFont(name: "Roboto-Bold", size: 18) self.watchHeroTitle.textColor = UIColor.whiteColor() self.watchHeroType.font = UIFont(name: "Roboto-Medium", size: 12) self.watchHeroType.textColor = typeColor self.watchArticleOneType.font = UIFont(name: "Roboto-Medium", size: 12) self.watchArticleOneType.textColor = typeColor self.watchArticleOneType.textAlignment = .Center self.watchArticleOneTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.watchArticleOneTitle.textColor = UIColor.blackColor() self.watchArticleOneTitle.textAlignment = .Center self.watchArticleTwoType.font = UIFont(name: "Roboto-Medium", size: 12) self.watchArticleTwoType.textColor = typeColor self.watchArticleTwoType.textAlignment = .Center self.watchArticleTwoTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.watchArticleTwoTitle.textColor = UIColor.blackColor() self.watchArticleTwoTitle.textAlignment = .Center // Read self.readHeroTitle.font = UIFont(name: "Roboto-Bold", size: 18) self.readHeroTitle.textColor = UIColor.whiteColor() self.readHeroType.font = UIFont(name: "Roboto-Medium", size: 12) self.readHeroType.textColor = typeColor self.readArticleOneType.font = UIFont(name: "Roboto-Medium", size: 12) self.readArticleOneType.textColor = typeColor self.readArticleOneType.textAlignment = .Center self.readArticleOneTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.readArticleOneTitle.textColor = UIColor.blackColor() self.readArticleOneTitle.textAlignment = .Center self.readArticleTwoType.font = UIFont(name: "Roboto-Medium", size: 12) self.readArticleTwoType.textColor = typeColor self.readArticleTwoType.textAlignment = .Center self.readArticleTwoTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.readArticleTwoTitle.textColor = UIColor.blackColor() self.readArticleTwoTitle.textAlignment = .Center // Learn self.learnHeroTitle.font = UIFont(name: "Roboto-Bold", size: 18) self.learnHeroTitle.textColor = UIColor.whiteColor() self.learnHeroType.font = UIFont(name: "Roboto-Medium", size: 12) self.learnHeroType.textColor = typeColor self.learnArticleOneType.font = UIFont(name: "Roboto-Medium", size: 12) self.learnArticleOneType.textColor = typeColor self.learnArticleOneType.textAlignment = .Center self.learnArticleOneTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.learnArticleOneTitle.textColor = UIColor.blackColor() self.learnArticleOneTitle.textAlignment = .Center self.learnArticleTwoType.font = UIFont(name: "Roboto-Medium", size: 12) self.learnArticleTwoType.textColor = typeColor self.learnArticleTwoType.textAlignment = .Center self.learnArticleTwoTitle.font = UIFont(name: "Roboto-Bold", size: 14) self.learnArticleTwoTitle.textColor = UIColor.blackColor() self.learnArticleTwoTitle.textAlignment = .Center // Shop self.shopHeroIcon.image = UIImage (named: "readicon.png") self.shopArticleOneIcon.image = UIImage (named: "readIconSmall.png") self.shopArticleTwoIcon.image = UIImage (named: "readIconSmall.png") } backgroundView.removeFromSuperview() } // Hero One Type heroOneType.text = typeHeroOne heroOneType.font = UIFont(name: "Roboto-Medium", size: 12) heroOneType.textColor = typeColor // Hero One Tap Gesture Recognizer heroOneView.tag = 1 heroOneView.userInteractionEnabled = true let tapRecognizerHeroOne = UITapGestureRecognizer(target: self, action: "imageTapped:") heroOneView.addGestureRecognizer(tapRecognizerHeroOne) // Hero Two Type heroTwoType.text = typeHeroTwo heroTwoType.font = UIFont(name: "Roboto-Medium", size: 12) heroTwoType.textColor = typeColor // Hero Two Tap Gesture Recognizer heroTwoView.tag = 2 heroTwoView.userInteractionEnabled = true let tapRecognizerHeroTwo = UITapGestureRecognizer(target: self, action: "imageTapped:") heroTwoView.addGestureRecognizer(tapRecognizerHeroTwo) // Hero Three Type heroThreeType.text = typeHeroThree heroThreeType.font = UIFont(name: "Roboto-Medium", size: 12) heroThreeType.textColor = typeColor //heroThreeView.addGestureRecognizer(tapRecognizer) // Hero Three Tap Gesture Recognizer heroThreeView.tag = 3 heroThreeView.userInteractionEnabled = true let tapRecognizerHeroThree = UITapGestureRecognizer(target: self, action: "imageTapped:") heroThreeView.addGestureRecognizer(tapRecognizerHeroThree) // Add Gradient to all heroes let gradientLayerH1 = CAGradientLayer.init() let gradientLayerH2 = CAGradientLayer.init() let gradientLayerH3 = CAGradientLayer.init() let colors = [ UIColor.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.7).CGColor, UIColor.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0).CGColor ] let startPoint = CGPointMake(0.0, 1.0) let endPoint = CGPointMake(0.0, 0.0) gradientLayerH1.frame = heroOneView.bounds gradientLayerH2.frame = heroTwoView.bounds gradientLayerH3.frame = heroThreeView.bounds gradientLayerH1.colors = colors gradientLayerH2.colors = colors gradientLayerH3.colors = colors gradientLayerH1.startPoint = startPoint gradientLayerH1.endPoint = endPoint gradientLayerH2.startPoint = startPoint gradientLayerH2.endPoint = endPoint gradientLayerH3.startPoint = startPoint gradientLayerH3.endPoint = endPoint self.heroOneView.layer.addSublayer(gradientLayerH1) self.heroTwoView.layer.addSublayer(gradientLayerH2) self.heroThreeView.layer.addSublayer(gradientLayerH3) // Article One articleOneType.text = typeArticleOne articleOneType.font = UIFont(name: "Roboto-Medium", size: 12) articleOneType.textColor = typeColor articleOneType.textAlignment = .Center // Article One Tap Gesture Recognizer articleOne.tag = 4 articleOne.userInteractionEnabled = true let tapRecognizerArticleOne = UITapGestureRecognizer(target: self, action: "imageTapped:") articleOne.addGestureRecognizer(tapRecognizerArticleOne) // Article Two articleTwoType.text = typeArticleTwo articleTwoType.font = UIFont(name: "Roboto-Medium", size: 12) articleTwoType.textColor = typeColor articleTwoType.textAlignment = .Center // Article Two Tap Gesture Recognizer articleTwo.tag = 5 articleTwo.userInteractionEnabled = true let tapRecognizerArticleTwo = UITapGestureRecognizer(target: self, action: "imageTapped:") articleTwo.addGestureRecognizer(tapRecognizerArticleTwo) // Article Three articleThreeType.text = typeArticleThree articleThreeType.font = UIFont(name: "Roboto-Medium", size: 12) articleThreeType.textColor = typeColor articleThreeType.textAlignment = .Center // Article Three Tap Gesture Recognizer articleThree.tag = 6 articleThree.userInteractionEnabled = true let tapRecognizerArticleThree = UITapGestureRecognizer(target: self, action: "imageTapped:") articleThree.addGestureRecognizer(tapRecognizerArticleThree) // Article Four articleFourType.text = typeArticleFour articleFourType.font = UIFont(name: "Roboto-Medium", size: 12) articleFourType.textColor = typeColor articleFourType.textAlignment = .Center // Article Four Tap Gesture Recognizer articleFour.tag = 7 articleFour.userInteractionEnabled = true let tapRecognizerArticleFour = UITapGestureRecognizer(target: self, action: "imageTapped:") articleFour.addGestureRecognizer(tapRecognizerArticleFour) // ------- Watch -------- watchLabel.text = "Watch" watchLabel.font = UIFont(name: "Roboto-Bold", size: 24) watchLabel.textColor = UIColor.blackColor() // Hero // Watch Hero Tap Gesture Recognizer watchHero.tag = 10 watchHero.userInteractionEnabled = true let tapRecognizerWatchHero = UITapGestureRecognizer(target: self, action: "imageTappedVideo:") watchHero.addGestureRecognizer(tapRecognizerWatchHero) // Article One // Watch Article One Tap Gesture Recognizer watchArticleOne.tag = 11 watchArticleOne.userInteractionEnabled = true let tapRecognizerWatchArticleOne = UITapGestureRecognizer(target: self, action: "imageTappedVideo:") watchArticleOne.addGestureRecognizer(tapRecognizerWatchArticleOne) // Article Two // Watch Article Two Tap Gesture Recognizer watchArticleTwo.tag = 12 watchArticleTwo.userInteractionEnabled = true let tapRecognizerWatchArticleTwo = UITapGestureRecognizer(target: self, action: "imageTappedVideo:") watchArticleTwo.addGestureRecognizer(tapRecognizerWatchArticleTwo) // ------- Read -------- readLabel.text = "Read" readLabel.font = UIFont(name: "Roboto-Bold", size: 24) readLabel.textColor = UIColor.blackColor() // Hero // Read Hero Tap Gesture Recognizer readHero.tag = 20 readHero.userInteractionEnabled = true let tapRecognizerReadHero = UITapGestureRecognizer(target: self, action: "imageTapped:") readHero.addGestureRecognizer(tapRecognizerReadHero) // Article One // Read Article One Tap Gesture Recognizer readArticleOne.tag = 21 readArticleOne.userInteractionEnabled = true let tapRecognizerReadArticleOne = UITapGestureRecognizer(target: self, action: "imageTapped:") readArticleOne.addGestureRecognizer(tapRecognizerReadArticleOne) // Article Two // Read Article Two Tap Gesture Recognizer readArticleTwo.tag = 22 readArticleTwo.userInteractionEnabled = true let tapRecognizerReadArticleTwo = UITapGestureRecognizer(target: self, action: "imageTapped:") readArticleTwo.addGestureRecognizer(tapRecognizerReadArticleTwo) // ------- Learn -------- learnLabel.text = "Learn" learnLabel.font = UIFont(name: "Roboto-Bold", size: 24) learnLabel.textColor = UIColor.blackColor() // Hero // Learn Hero Tap Gesture Recognizer learnHero.tag = 30 learnHero.userInteractionEnabled = true let tapRecognizerLearnHero = UITapGestureRecognizer(target: self, action: "imageTapped:") learnHero.addGestureRecognizer(tapRecognizerLearnHero) // Article One // Learn Article One Tap Gesture Recognizer learnArticleOne.tag = 31 learnArticleOne.userInteractionEnabled = true let tapRecognizerLearnArticleOne = UITapGestureRecognizer(target: self, action: "imageTapped:") learnArticleOne.addGestureRecognizer(tapRecognizerLearnArticleOne) // Article Two // Learn Article Two Tap Gesture Recognizer learnArticleTwo.tag = 32 learnArticleTwo.userInteractionEnabled = true let tapRecognizerLearnArticleTwo = UITapGestureRecognizer(target: self, action: "imageTapped:") learnArticleTwo.addGestureRecognizer(tapRecognizerLearnArticleTwo) // ------- Shop -------- shopLabel.text = "Shop" shopLabel.font = UIFont(name: "Roboto-Bold", size: 24) shopLabel.textColor = UIColor.blackColor() // Hero self.shopHero.image = imageShopHero shopHeroTitle.text = titleShopHero shopHeroTitle.font = UIFont(name: "Roboto-Bold", size: 18) shopHeroTitle.textColor = UIColor.whiteColor() shopHeroType.text = typeShopHero shopHeroType.font = UIFont(name: "Roboto-Medium", size: 12) shopHeroType.textColor = typeColor // Shop Hero Tap Gesture Recognizer shopHero.tag = 40 shopHero.userInteractionEnabled = true let tapRecognizerShopHero = UITapGestureRecognizer(target: self, action: "imageTapped:") shopHero.addGestureRecognizer(tapRecognizerShopHero) // Article One shopArticleOne.image = imageShopArticleOne shopArticleOneType.text = typeShopArticleOne shopArticleOneType.font = UIFont(name: "Roboto-Medium", size: 12) shopArticleOneType.textColor = typeColor shopArticleOneType.textAlignment = .Center shopArticleOneTitle.textAlignment = .Center shopArticleOneTitle.text = titleShopArticleOne shopArticleOneTitle.font = UIFont(name: "Roboto-Bold", size: 14) shopArticleOneTitle.textColor = UIColor.blackColor() // Shop Article One Tap Gesture Recognizer shopArticleOne.tag = 41 shopArticleOne.userInteractionEnabled = true let tapRecognizerShopArticleOne = UITapGestureRecognizer(target: self, action: "imageTapped:") shopArticleOne.addGestureRecognizer(tapRecognizerShopArticleOne) // Article Two shopArticleTwo.image = imageShopArticleTwo shopArticleTwoType.text = typeShopArticleTwo shopArticleTwoType.font = UIFont(name: "Roboto-Medium", size: 12) shopArticleTwoType.textColor = typeColor shopArticleTwoType.textAlignment = .Center shopArticleTwoTitle.text = titleShopArticleTwo shopArticleTwoTitle.font = UIFont(name: "Roboto-Bold", size: 14) shopArticleTwoTitle.textColor = UIColor.blackColor() shopArticleTwoTitle.textAlignment = .Center // Learn Article Two Tap Gesture Recognizer shopArticleTwo.tag = 32 shopArticleTwo.userInteractionEnabled = true let tapRecognizerShopArticleTwo = UITapGestureRecognizer(target: self, action: "imageTapped:") shopArticleTwo.addGestureRecognizer(tapRecognizerShopArticleTwo) // Footer footerBackground.image = UIImage(named: "black.png") footerImageOne.image = UIImage(named: "twitter2.png") footerImageTwo.image = UIImage(named: "facebook2.png") footerImageThree.image = UIImage(named: "youtube2.png") footerImageFour.image = UIImage(named: "instagram2.png") } // This function sends the correct thumbnail to the article when it is clicked func imageTapped(gestureRecognizer: UITapGestureRecognizer) { switch gestureRecognizer.view!.tag { case 1: articleClicked = "Hero One" passedThumbnail = self.contDict["HeroOne"]! case 2: articleClicked = "Hero Two" passedThumbnail = self.contDict["HeroTwo"] case 3: articleClicked = "Hero Three" passedThumbnail = self.contDict["HeroThree"] case 4: articleClicked = "Article One" passedThumbnail = self.contDict["featuredOne"] case 5: articleClicked = "Article Two" passedThumbnail = self.contDict["featuredTwo"] case 6: articleClicked = "Article Three" passedThumbnail = self.contDict["featuredThree"] case 7: articleClicked = "Article Four" passedThumbnail = self.contDict["featuredFour"] case 10: articleClicked = "Watch Hero" passedThumbnail = self.contDict["watchHero"] case 11: articleClicked = "Watch Article One" passedThumbnail = self.contDict["watchArticleOne"] case 12: articleClicked = "Watch Article Two" passedThumbnail = self.contDict["watchArticleTwo"] case 20: articleClicked = "Read Hero" passedThumbnail = self.contDict["readHero"] case 21: articleClicked = "Read Article One" passedThumbnail = self.contDict["readArticleOne"] case 22: articleClicked = "Read Article Two" passedThumbnail = self.contDict["readArticleTwo"] case 30: articleClicked = "Learn Hero" passedThumbnail = self.contDict["learnHero"] case 31: articleClicked = "Learn Article One" passedThumbnail = self.contDict["learnArticleOne"] case 32: articleClicked = "Learn Article Two" passedThumbnail = self.contDict["learnArticleTwo"] case 40: articleClicked = "Shop Hero" passedThumbnail = self.contDict["shopHero"] case 41: articleClicked = "Shop Article One" passedThumbnail = self.contDict["shopArticleOne"] case 42: articleClicked = "Shop Article Two" passedThumbnail = self.contDict["shopArticleTwo"] default: articleClicked = "null" } self.performSegueWithIdentifier("goToArticle", sender: self) } // This function sends the correct video to the article when it is clicked func imageTappedVideo(gestureRecognizer: UITapGestureRecognizer) { switch gestureRecognizer.view!.tag { case 1: articleClicked = "Hero One" passedThumbnail = self.contDict["HeroOne"]! case 2: articleClicked = "Hero Two" passedThumbnail = self.contDict["HeroTwo"] case 3: articleClicked = "Hero Three" passedThumbnail = self.contDict["HeroThree"] case 4: articleClicked = "Article One" passedThumbnail = self.contDict["featuredOne"] case 5: articleClicked = "Article Two" passedThumbnail = self.contDict["featuredTwo"] case 6: articleClicked = "Article Three" passedThumbnail = self.contDict["featuredThree"] case 7: articleClicked = "Article Four" passedThumbnail = self.contDict["featuredFour"] case 10: articleClicked = "Watch Hero" passedThumbnail = self.contDict["watchHero"] case 11: articleClicked = "Watch Article One" passedThumbnail = self.contDict["watchArticleOne"] case 12: articleClicked = "Watch Article Two" passedThumbnail = self.contDict["watchArticleTwo"] case 20: articleClicked = "Read Hero" passedThumbnail = self.contDict["readHero"] case 21: articleClicked = "Read Article One" passedThumbnail = self.contDict["readArticleOne"] case 22: articleClicked = "Read Article Two" passedThumbnail = self.contDict["readArticleTwo"] case 30: articleClicked = "Learn Hero" passedThumbnail = self.contDict["learnHero"] case 31: articleClicked = "Learn Article One" passedThumbnail = self.contDict["learnArticleOne"] case 32: articleClicked = "Learn Article Two" passedThumbnail = self.contDict["learnArticleTwo"] case 40: articleClicked = "Shop Hero" passedThumbnail = self.contDict["shopHero"] case 41: articleClicked = "Shop Article One" passedThumbnail = self.contDict["shopArticleOne"] case 42: articleClicked = "Shop Article Two" passedThumbnail = self.contDict["shopArticleTwo"] default: articleClicked = "null" } self.performSegueWithIdentifier("goToVideo", sender: self) } // This function overwrites the prepareForSegue function when transitioning between views override func viewDidAppear(animated: Bool) { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "goToArticle" { let DestViewController : articleViewController = segue.destinationViewController as! articleViewController DestViewController.article = articleClicked DestViewController.articleThumbnail = passedThumbnail } else if segue.identifier == "goToVideo" { let DestViewVideoController : videoViewController = segue.destinationViewController as! videoViewController DestViewVideoController.articleThumbnail = passedThumbnail } } }
apache-2.0
5662a74d9d35d6c7fe8abc7b4fd74586
40.483268
119
0.616461
4.925441
false
false
false
false
benlangmuir/swift
test/SILOptimizer/pointer_conversion_linux.swift
13
2849
// RUN: %target-swift-frontend -module-name pointer_conversion -emit-sil -O %s | %FileCheck %s // REQUIRES: optimized_stdlib // UNSUPPORTED: objc_interop // Opaque, unoptimizable functions to call. @_silgen_name("takesConstRawPointer") func takesConstRawPointer(_ x: UnsafeRawPointer) @_silgen_name("takesOptConstRawPointer") func takesOptConstRawPointer(_ x: UnsafeRawPointer?) @_silgen_name("takesMutableRawPointer") func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) @_silgen_name("takesOptMutableRawPointer") func takesOptMutableRawPointer(_ x: UnsafeMutableRawPointer?) // Opaque function for generating values @_silgen_name("get") func get<T>() -> T // The purpose of these tests is to make sure the storage is never released // before the call to the opaque function. // CHECK-LABEL: sil @$s18pointer_conversion17testOptionalArrayyyF public func testOptionalArray() { let array: [Int]? = get() takesOptConstRawPointer(array) // CHECK: bb0: // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]( // CHECK: [[ORIGINAL_OWNER:%.*]] = struct_extract {{%.*}} : $_ContiguousArrayBuffer<Int>, #_ContiguousArrayBuffer._storage // CHECK: [[ORIGINAL_OWNER_EXISTENTIAL:%.*]] = init_existential_ref [[ORIGINAL_OWNER]] // CHECK: [[OWNER:%.+]] = enum $Optional<AnyObject>, #Optional.some!enumelt, [[ORIGINAL_OWNER_EXISTENTIAL]] // CHECK-NEXT: [[POINTER:%.+]] = struct $UnsafeRawPointer ( // CHECK-NEXT: [[DEP_POINTER:%.+]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[ORIGINAL_OWNER]] // CHECK-NEXT: [[OPT_POINTER:%.+]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP_POINTER]] // CHECK-NEXT: br [[CALL_BRANCH:bb[0-9]+]]([[OPT_POINTER]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[CALL_BRANCH]]([[OPT_POINTER:%.+]] : $Optional<UnsafeRawPointer>, [[OWNER:%.+]] : $Optional<AnyObject>): // CHECK-NOT: release // CHECK-NEXT: [[DEP_OPT_POINTER:%.+]] = mark_dependence [[OPT_POINTER]] : $Optional<UnsafeRawPointer> on [[OWNER]] : $Optional<AnyObject> // CHECK: [[FN:%.+]] = function_ref @takesOptConstRawPointer // CHECK-NEXT: apply [[FN]]([[DEP_OPT_POINTER]]) // CHECK-NOT: release // CHECK-NOT: {{^bb[0-9]+:}} // CHECK: release_value {{%.+}} : $Optional<Array<Int>> // CHECK-NEXT: [[EMPTY:%.+]] = tuple () // CHECK-NEXT: return [[EMPTY]] // CHECK: [[NONE_BB]]: // CHECK-NEXT: [[NO_POINTER:%.+]] = enum $Optional<UnsafeRawPointer>, #Optional.none!enumelt // CHECK-NEXT: [[NO_OWNER:%.+]] = enum $Optional<AnyObject>, #Optional.none!enumelt // CHECK-NEXT: br [[CALL_BRANCH]]([[NO_POINTER]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>) } // CHECK: end sil function '$s18pointer_conversion17testOptionalArrayyyF'
apache-2.0
bd5f7d9823114168894154c5c0130756
51.759259
140
0.680239
3.844804
false
true
false
false
josefdolezal/fit-cvut
BI-IOS/practice-5/bi-ios-recognizers/ViewController.swift
2
1848
// // ViewController.swift // bi-ios-recognizers // // Created by Dominik Vesely on 03/11/15. // Copyright © 2015 Ackee s.r.o. All rights reserved. // import UIKit class ViewController: UIViewController, PanelViewDelegate { weak var graphView : GraphView! weak var panelView : PanelView! override func loadView() { self.view = UIView() view.backgroundColor = .whiteColor() let gv = GraphView(frame: CGRectZero) gv.autoresizingMask = UIViewAutoresizing.FlexibleWidth; self.view.addSubview(gv) self.graphView = gv let pv = PanelView(frame: CGRectZero) pv.autoresizingMask = UIViewAutoresizing.FlexibleWidth; pv.delegate = self view.addSubview(pv) self.panelView = pv } //MARK: PanelViewDelegate func syncedValueChanged(syncedValue: Double, panel: PanelView) { graphView.amplitude = CGFloat(syncedValue) } func selectedColorChanged(color: UIColor, panel: PanelView) { graphView.lineColor = color } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Nastavuje natvrdo velikost graph view velikost self.graphView.frame = CGRectMake(8, 20 + 8, CGRectGetWidth(self.view.bounds) - 16, 200); self.panelView.frame = CGRectMake(8, 20 + 16 + 200, CGRectGetWidth(self.view.bounds) - 16, 128); } override func viewDidLoad() { super.viewDidLoad() // tactile // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4ec9557a7e335e40d035db3bceb9c522
24.30137
104
0.6183
4.594527
false
false
false
false
apascual/braintree_ios
UITests/BraintreeThreeDSecure_UITests.swift
1
21589
/* IMPORTRANT Hardware keyboard should be disabled on simulator for tests to run reliably. */ import XCTest class BraintreeThreeDSecurePaymentFlow_UITests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchArguments.append("-EnvironmentSandbox") app.launchArguments.append("-ClientToken") app.launchArguments.append("-Integration:BraintreeDemoThreeDSecurePaymentFlowViewController") self.app.launch() sleep(1) self.waitForElementToBeHittable(app.textFields["Card Number"]) sleep(2) } func getPasswordField() -> XCUIElement { return app.webViews.otherElements["bank_frame"].children(matching: .other).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element.children(matching: .other).element(boundBy: 18).children(matching: .secureTextField).element } func getSubmutButton() -> XCUIElement { return app.webViews.otherElements["bank_frame"].children(matching: .other).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element.children(matching: .other).buttons["Submit"] } func testThreeDSecurePaymentFlow_completesAuthentication_receivesNonce() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(4) let elementsQuery = app.webViews.element.otherElements let passwordTextField = getPasswordField() passwordTextField.tap() sleep(2) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) } func testThreeDSecurePaymentFlow_failsAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000010") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.webViews.element.otherElements let passwordTextField = elementsQuery.children(matching: .other).children(matching: .secureTextField).element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) } func testThreeDSecurePaymentFlow_bypassesAuthentication_notEnrolled() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000051") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_bypassesAuthentication_lookupFailed() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000077") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_incorrectPassword_callsBackWithError_exactlyOnce() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000028") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.webViews.element.otherElements let passwordTextField = elementsQuery.children(matching: .other).children(matching: .secureTextField).element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) sleep(2) self.waitForElementToAppear(app.staticTexts["Callback Count: 1"]) } func testThreeDSecurePaymentFlow_passiveAuthentication_notPromptedForAuthentication() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000101") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) } func testThreeDSecurePaymentFlow_returnsNonce_whenIssuerDown() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000036") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.webViews.element.otherElements let passwordTextField = elementsQuery.children(matching: .other).children(matching: .secureTextField).element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) } func testThreeDSecurePaymentFlow_acceptsPassword_failsToAuthenticateNonce_dueToCardinalError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000093") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(4) let elementsQuery = app.webViews.element.otherElements let passwordTextField = elementsQuery.children(matching: .other).children(matching: .secureTextField).element passwordTextField.tap() sleep(2) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) } func testThreeDSecurePaymentFlow_returnsToApp_whenCancelTapped() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["Done"]) app.buttons["Done"].forceTapElement() self.waitForElementToAppear(app.buttons["Cancelled🎲"]) XCTAssertTrue(app.buttons["Cancelled🎲"].exists); } func testThreeDSecurePaymentFlow_bypassedAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000990000000004") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_lookupError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000085") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_unavailable() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000069") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_timeout() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000044") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(5) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } } class BraintreeThreeDSecure_UITests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchArguments.append("-EnvironmentSandbox") app.launchArguments.append("-ClientToken") app.launchArguments.append("-Integration:BraintreeDemoThreeDSecureViewController") self.app.launch() sleep(1) self.waitForElementToBeHittable(app.textFields["Card Number"]) sleep(2) } func getPasswordField() -> XCUIElement { return app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web View\"].webViews",".webViews"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element(boundBy: 18).children(matching: .secureTextField).element } func getSubmutButton() -> XCUIElement { return app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web View\"].webViews",".webViews"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element(boundBy: 0).children(matching: .other).element.children(matching: .other).buttons["Submit"] } func testThreeDSecure_completesAuthentication_receivesNonce() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.otherElements["Authentication"] let passwordTextField = getPasswordField() passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) XCTAssertTrue(app.buttons["Liability shift possible and liability shifted"].exists); } func testThreeDSecure_failsAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000010") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.otherElements["Authentication"] let passwordTextField = getPasswordField() passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) XCTAssertTrue(app.buttons["Failed to authenticate, please try a different form of payment."].exists); } func testThreeDSecure_bypassesAuthentication_notEnrolled() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000051") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_bypassesAuthentication_lookupFailed() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000077") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_incorrectPassword_callsBackWithError_exactlyOnce() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000028") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.otherElements["Authentication"] let passwordTextField = getPasswordField() passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) XCTAssertTrue(app.buttons["Failed to authenticate, please try a different form of payment."].exists); sleep(2) self.waitForElementToAppear(app.staticTexts["Callback Count: 1"]) XCTAssertTrue(app.staticTexts["Callback Count: 1"].exists); } func testThreeDSecure_passiveAuthentication_notPromptedForAuthentication() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000101") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) XCTAssertTrue(app.buttons["Liability shift possible and liability shifted"].exists); } func testThreeDSecure_returnsNonce_whenIssuerDown() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000036") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.otherElements["Authentication"] let passwordTextField = getPasswordField() passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) XCTAssertTrue(app.buttons["An unexpected error occurred"].exists); } func testThreeDSecure_acceptsPassword_failsToAuthenticateNonce_dueToCardinalError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000093") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) let elementsQuery = app.otherElements["Authentication"] let passwordTextField = getPasswordField() passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmutButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) XCTAssertTrue(app.buttons["An unexpected error occurred"].exists); } func testThreeDSecure_returnsToApp_whenCancelTapped() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToBeHittable(app.buttons["Cancel"]) app.buttons["Cancel"].forceTapElement() self.waitForElementToAppear(app.buttons["Cancelled🎲"]) XCTAssertTrue(app.buttons["Cancelled🎲"].exists); } func testThreeDSecure_bypassedAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000990000000004") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_lookupError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000085") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_unavailable() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000069") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_timeout() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000044") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(5) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } }
mit
ebdb97429d09ccac85d0bbdd0ed69a01
41.142578
391
0.684942
4.987748
false
true
false
false
accepton/accepton-apple
Pod/Classes/AcceptOnUIMachine/Drivers/CreditCard/Stripe.swift
1
1550
import Foundation import StripePrivate extension STPCardParams { convenience init(_ creditCardParams: AcceptOnAPICreditCardParams) { self.init() self.number = creditCardParams.number self.expMonth = UInt(((creditCardParams.expMonth ?? "") as NSString).intValue) self.expYear = UInt((creditCardParams.expYear as NSString).intValue) self.cvc = creditCardParams.cvc } } class AcceptOnUIMachineCreditCardStripePlugin: AcceptOnUIMachineCreditCardDriverPlugin { override var name: String { return "stripe" } override func beginTransactionWithFormOptions(formOptions: AcceptOnUIMachineFormOptions) { //Assuming they are using stripe let stripePublishableKey = formOptions.paymentMethods.stripePublishableKey if let stripePublishableKey = stripePublishableKey { Stripe.setDefaultPublishableKey(stripePublishableKey) let card = STPCardParams(formOptions.creditCardParams!) STPAPIClient.sharedClient().createTokenWithCard(card) { token, err in if let err = err { self.delegate?.creditCardPlugin(self, didFailWithMessage: err.localizedDescription) return } let tokenId = token!.tokenId self.delegate.creditCardPlugin(self, didSucceedWithNonce: tokenId) } } else { self.delegate.creditCardPlugin(self, didFailWithMessage: "Stripe could not be configured") } } }
mit
26ae424901ce8e2778b681da3eb516e8
38.769231
103
0.668387
5.656934
false
false
false
false
yonaskolb/XcodeGen
Sources/XcodeGenKit/GraphVizGenerator.swift
1
1701
import DOT import Foundation import GraphViz import ProjectSpec extension Dependency { var graphVizName: String { switch self.type { case .bundle, .package, .sdk, .framework, .carthage: return "[\(self.type)]\\n\(reference)" case .target: return reference } } } extension Dependency.DependencyType: CustomStringConvertible { public var description: String { switch self { case .bundle: return "bundle" case .package: return "package" case .framework: return "framework" case .carthage: return "carthage" case .sdk: return "sdk" case .target: return "target" } } } extension Node { init(target: Target) { self.init(target.name) self.shape = .box } init(dependency: Dependency) { self.init(dependency.reference) self.shape = .box self.label = dependency.graphVizName } } public class GraphVizGenerator { public init() {} public func generateModuleGraphViz(targets: [Target]) -> String { return DOTEncoder().encode(generateGraph(targets: targets)) } func generateGraph(targets: [Target]) -> Graph { var graph = Graph(directed: true) targets.forEach { target in target.dependencies.forEach { dependency in let from = Node(target: target) graph.append(from) let to = Node(dependency: dependency) graph.append(to) var edge = Edge(from: from, to: to) edge.style = .dashed graph.append(edge) } } return graph } }
mit
477d25d7dd1386eca4dd6fcb2e8ccd30
24.772727
69
0.576132
4.395349
false
false
false
false
ZackKingS/Tasks
Pods/SwiftTheme/Source/UIColorExtension.swift
1
5138
// // UIColorExtension.swift // HEXColor // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit /** MissingHashMarkAsPrefix: "Invalid RGB string, missing '#' as prefix" UnableToScanHexValue: "Scan hex error" MismatchedHexStringLength: "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8" */ public enum UIColorInputError : Error { case missingHashMarkAsPrefix, unableToScanHexValue, mismatchedHexStringLength } extension UIColor { /** The shorthand three-digit hexadecimal representation of color. #RGB defines to the color #RRGGBB. - parameter hex3: Three-digit hexadecimal value. - parameter alpha: 0.0 - 1.0. The default is 1.0. */ public convenience init(hex3: UInt16, alpha: CGFloat = 1) { let divisor = CGFloat(15) let red = CGFloat((hex3 & 0xF00) >> 8) / divisor let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor let blue = CGFloat( hex3 & 0x00F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #RRGGBBAA. - parameter hex4: Four-digit hexadecimal value. */ public convenience init(hex4: UInt16) { let divisor = CGFloat(15) let red = CGFloat((hex4 & 0xF000) >> 12) / divisor let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor let alpha = CGFloat( hex4 & 0x000F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex6: Six-digit hexadecimal value. */ public convenience init(hex6: UInt32, alpha: CGFloat = 1) { let divisor = CGFloat(255) let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor let blue = CGFloat( hex6 & 0x0000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA. - parameter hex8: Eight-digit hexadecimal value. */ public convenience init(hex8: UInt32) { let divisor = CGFloat(255) let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor let alpha = CGFloat( hex8 & 0x000000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, throws error. - parameter rgba: String value. */ public convenience init(rgba_throws rgba: String) throws { guard rgba.hasPrefix("#") else { throw UIColorInputError.missingHashMarkAsPrefix } let hexString: String = rgba.substring(from: rgba.characters.index(rgba.startIndex, offsetBy: 1)) var hexValue: UInt32 = 0 guard Scanner(string: hexString).scanHexInt32(&hexValue) else { throw UIColorInputError.unableToScanHexValue } switch (hexString.characters.count) { case 3: self.init(hex3: UInt16(hexValue)) case 4: self.init(hex4: UInt16(hexValue)) case 6: self.init(hex6: hexValue) case 8: self.init(hex8: hexValue) default: throw UIColorInputError.mismatchedHexStringLength } } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, fails to default color. - parameter rgba: String value. */ public convenience init(rgba: String, defaultColor: UIColor = UIColor.clear) { guard let color = try? UIColor(rgba_throws: rgba) else { self.init(cgColor: defaultColor.cgColor) return } self.init(cgColor: color.cgColor) } /** Hex string of a UIColor instance. - parameter rgba: Whether the alpha should be included. */ public func hexString(_ includeAlpha: Bool) -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) if (includeAlpha) { return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) } else { return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } } open override var description: String { return self.hexString(true) } open override var debugDescription: String { return self.hexString(true) } }
apache-2.0
c6aa42033fe79b57e418702f6ccd45f9
33.253333
110
0.591865
3.973705
false
false
false
false
OscarSwanros/swift
test/DebugInfo/returnlocation.swift
15
6279
// RUN: %target-swift-frontend -g -emit-ir %s -o %t.ll // REQUIRES: objc_interop import Foundation // This file contains linetable testcases for all permutations // of simple/complex/empty return expressions, // cleanups/no cleanups, single / multiple return locations. // RUN: %FileCheck %s --check-prefix=CHECK_NONE < %t.ll // CHECK_NONE: define{{( protected)?}} {{.*}}void {{.*}}none public func none(_ a: inout Int64) { // CHECK_NONE: call void @llvm.dbg{{.*}}, !dbg // CHECK_NONE: store{{.*}}, !dbg // CHECK_NONE: !dbg ![[NONE_INIT:.*]] a -= 2 // CHECK_NONE: ret {{.*}}, !dbg ![[NONE_RET:.*]] // CHECK_NONE: ![[NONE_INIT]] = !DILocation(line: [[@LINE-2]], column: // CHECK_NONE: ![[NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_EMPTY < %t.ll // CHECK_EMPTY: define {{.*}}empty public func empty(_ a: inout Int64) { if a > 24 { // CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET1:.*]] // CHECK-DAG_EMPTY_RET1: ![[EMPTY_RET1]] = !DILocation(line: [[@LINE+1]], column: 6, return } a -= 2 // CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET2:.*]] // CHECK-DAG_EMPTY_RET2: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 3, return // CHECK-DAG_EMPTY: ret {{.*}}, !dbg ![[EMPTY_RET:.*]] // CHECK-DAG_EMPTY: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_EMPTY_NONE < %t.ll // CHECK_EMPTY_NONE: define {{.*}}empty_none public func empty_none(_ a: inout Int64) { if a > 24 { return } a -= 2 // CHECK_EMPTY_NONE: ret {{.*}}, !dbg ![[EMPTY_NONE_RET:.*]] // CHECK_EMPTY_NONE: ![[EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_RET < %t.ll // CHECK_SIMPLE_RET: define {{.*}}simple public func simple(_ a: Int64) -> Int64 { if a > 24 { return 0 } return 1 // CHECK_SIMPLE_RET: ret i{{.*}}, !dbg ![[SIMPLE_RET:.*]] // CHECK_SIMPLE_RET: ![[SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_RET < %t.ll // CHECK_COMPLEX_RET: define {{.*}}complex public func complex(_ a: Int64) -> Int64 { if a > 24 { return a*a } return a/2 // CHECK_COMPLEX_RET: ret i{{.*}}, !dbg ![[COMPLEX_RET:.*]] // CHECK_COMPLEX_RET: ![[COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_SIMPLE < %t.ll // CHECK_COMPLEX_SIMPLE: define {{.*}}complex_simple public func complex_simple(_ a: Int64) -> Int64 { if a > 24 { return a*a } return 2 // CHECK_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[COMPLEX_SIMPLE_RET:.*]] // CHECK_COMPLEX_SIMPLE: ![[COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_COMPLEX < %t.ll // CHECK_SIMPLE_COMPLEX: define {{.*}}simple_complex public func simple_complex(_ a: Int64) -> Int64 { if a > 24 { return a*a } return 2 // CHECK_SIMPLE_COMPLEX: ret {{.*}}, !dbg ![[SIMPLE_COMPLEX_RET:.*]] // CHECK_SIMPLE_COMPLEX: ![[SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // --------------------------------------------------------------------- // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_NONE < %t.ll // CHECK_CLEANUP_NONE: define {{.*}}cleanup_none public func cleanup_none(_ a: inout NSString) { a = "empty" // CHECK_CLEANUP_NONE: ret void, !dbg ![[CLEANUP_NONE_RET:.*]] // CHECK_CLEANUP_NONE: ![[CLEANUP_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY < %t.ll // CHECK_CLEANUP_EMPTY: define {{.*}}cleanup_empty public func cleanup_empty(_ a: inout NSString) { if a.length > 24 { return } a = "empty" return // CHECK_CLEANUP_EMPTY: ret void, !dbg ![[CLEANUP_EMPTY_RET:.*]] // CHECK_CLEANUP_EMPTY: ![[CLEANUP_EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY_NONE < %t.ll // CHECK_CLEANUP_EMPTY_NONE: define {{.*}}cleanup_empty_none public func cleanup_empty_none(_ a: inout NSString) { if a.length > 24 { return } a = "empty" // CHECK_CLEANUP_EMPTY_NONE: ret {{.*}}, !dbg ![[CLEANUP_EMPTY_NONE_RET:.*]] // CHECK_CLEANUP_EMPTY_NONE: ![[CLEANUP_EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_RET < %t.ll // CHECK_CLEANUP_SIMPLE_RET: define {{.*}}cleanup_simple public func cleanup_simple(_ a: NSString) -> Int64 { if a.length > 24 { return 0 } return 1 // CHECK_CLEANUP_SIMPLE_RET: ret {{.*}}, !dbg ![[CLEANUP_SIMPLE_RET:.*]] // CHECK_CLEANUP_SIMPLE_RET: ![[CLEANUP_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX < %t.ll // CHECK_CLEANUP_COMPLEX: define {{.*}}cleanup_complex public func cleanup_complex(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return Int64(a.length/2) // CHECK_CLEANUP_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_RET:.*]] // CHECK_CLEANUP_COMPLEX: ![[CLEANUP_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX_SIMPLE < %t.ll // CHECK_CLEANUP_COMPLEX_SIMPLE: define {{.*}}cleanup_complex_simple public func cleanup_complex_simple(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return 2 // CHECK_CLEANUP_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_SIMPLE_RET:.*]] // CHECK_CLEANUP_COMPLEX_SIMPLE: ![[CLEANUP_COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_COMPLEX < %t.ll // CHECK_CLEANUP_SIMPLE_COMPLEX: define {{.*}}cleanup_simple_complex public func cleanup_simple_complex(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return 2 // CHECK_CLEANUP_SIMPLE_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_SIMPLE_COMPLEX_RET:.*]] // CHECK_CLEANUP_SIMPLE_COMPLEX: ![[CLEANUP_SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // ---------------------------------------------------------------------
apache-2.0
aac3e18e112e50c37cb4832aae911fa6
33.883333
110
0.600096
3.152108
false
false
false
false
ianyh/Amethyst
Amethyst/Model/WindowsInformation.swift
1
6716
// // WindowsInformation.swift // Amethyst // // Created by Ian Ynda-Hummel on 5/15/16. // Copyright © 2016 Ian Ynda-Hummel. All rights reserved. // import ApplicationServices import Foundation import Silica extension CGRect { func approximatelyEqual(to otherRect: CGRect, within tolerance: CGRect) -> Bool { return abs(origin.x - otherRect.origin.x) < tolerance.origin.x && abs(origin.y - otherRect.origin.y) < tolerance.origin.y && abs(width - otherRect.width) < tolerance.width && abs(height - otherRect.height) < tolerance.height } } struct WindowsInformation<Window: WindowType> { let ids: Set<CGWindowID> let descriptions: CGWindowsInfo<Window>? init?(windows: [Window]) { guard let descriptions = CGWindowsInfo<Window>(options: .optionOnScreenOnly, windowID: CGWindowID(0)) else { return nil } self.ids = Set(windows.map { $0.cgID() }) self.descriptions = descriptions } } extension WindowsInformation { // convert Window objects to CGWindowIDs. // additionally, return the full set of window descriptions (which is unsorted and may contain extra windows) fileprivate static func windowInformation(_ windows: [Window]) -> (IDs: Set<CGWindowID>, descriptions: [[String: AnyObject]]?) { let ids = Set(windows.map { $0.cgID() }) return (IDs: ids, descriptions: CGWindowsInfo<Window>(options: .optionOnScreenOnly, windowID: CGWindowID(0))?.descriptions) } fileprivate static func onScreenWindowsAtPoint(_ point: CGPoint, withIDs windowIDs: Set<CGWindowID>, withDescriptions windowDescriptions: [[String: AnyObject]]) -> [[String: AnyObject]] { var ret: [[String: AnyObject]] = [] // build a list of windows at this point for windowDescription in windowDescriptions { guard let windowID = (windowDescription[kCGWindowNumber as String] as? NSNumber).flatMap({ CGWindowID($0.intValue) }), windowIDs.contains(windowID) else { continue } // only consider windows with bounds guard let windowFrameDictionary = windowDescription[kCGWindowBounds as String] as? [String: Any] else { continue } // only consider window bounds that contain the given point let windowFrame = CGRect(dictionaryRepresentation: windowFrameDictionary as CFDictionary)! guard windowFrame.contains(point) else { continue } ret.append(windowDescription) } return ret } // if there are several windows at a given screen point, take the top one static func topWindowForScreenAtPoint(_ point: CGPoint, withWindows windows: [Window]) -> Window? { let (ids, maybeWindowDescriptions) = windowInformation(windows) guard let windowDescriptions = maybeWindowDescriptions, !windowDescriptions.isEmpty else { return nil } let windowsAtPoint = onScreenWindowsAtPoint(point, withIDs: ids, withDescriptions: windowDescriptions) guard !windowsAtPoint.isEmpty else { return nil } guard windowsAtPoint.count > 1 else { return windowInWindows(windows, withCGWindowDescription: windowsAtPoint[0]) } var windowToFocus: [String: AnyObject]? var minCount = windowDescriptions.count for windowDescription in windowsAtPoint { guard let windowID = windowDescription[kCGWindowNumber as String] as? NSNumber else { continue } guard let windowsAboveWindow = CGWindowsInfo<Window>(options: .optionOnScreenAboveWindow, windowID: windowID.uint32Value) else { continue } if windowsAboveWindow.descriptions.count < minCount { windowToFocus = windowDescription minCount = windowsAboveWindow.descriptions.count } } guard let windowDictionaryToFocus = windowToFocus else { return nil } return windowInWindows(windows, withCGWindowDescription: windowDictionaryToFocus) } // get the first window at a certain point, excluding one specific window from consideration static func alternateWindowForScreenAtPoint(_ point: CGPoint, withWindows windows: [Window], butNot ignoreWindow: Window?) -> Window? { // only consider windows on this screen let (ids, maybeWindowDescriptions) = windowInformation(windows) guard let windowDescriptions = maybeWindowDescriptions, !windowDescriptions.isEmpty else { return nil } let windowsAtPoint = onScreenWindowsAtPoint(point, withIDs: ids, withDescriptions: windowDescriptions) for windowDescription in windowsAtPoint { if let window = windowInWindows(windows, withCGWindowDescription: windowDescription) { if let ignored = ignoreWindow, window != ignored { return window } } } return nil } // find a window based on its window description within an array of Window objects static func windowInWindows(_ windows: [Window], withCGWindowDescription windowDescription: [String: AnyObject]) -> Window? { let potentialWindows = windows.filter { guard let windowOwnerPID = windowDescription[kCGWindowOwnerPID as String] as? NSNumber else { return false } guard windowOwnerPID.int32Value == $0.pid() else { return false } guard let boundsDictionary = windowDescription[kCGWindowBounds as String] as? [String: Any] else { return false } let windowFrame = CGRect(dictionaryRepresentation: boundsDictionary as CFDictionary)! guard windowFrame.equalTo($0.frame()) else { return false } return true } guard potentialWindows.count > 1 else { return potentialWindows.first } return potentialWindows.first { guard let describedTitle = windowDescription[kCGWindowName as String] as? String else { return false } let describedOwner = windowDescription[kCGWindowOwnerName as String] as? String let describedOwnedTitle = describedOwner.flatMap { "\(describedTitle) - \($0)" } return describedTitle == $0.title() || describedOwnedTitle == $0.title() } } }
mit
fe07f8d391965a228b68cee233a9ed5c
37.815029
140
0.634401
4.988856
false
false
false
false
CleanCocoa/FatSidebar
FatSidebar/FatSidebarItemOverlay.swift
1
4251
// Copyright © 2017 Christian Tietze. All rights reserved. Distributed under the MIT License. import Cocoa class FatSidebarItemOverlay: FatSidebarItem { weak var base: FatSidebarItem! override func mouseHeld(_ timer: Timer) { self.animator().alphaValue = 0.0 base.mouseHeld(timer) } // MARK: - Hovering static var hoverStarted: Notification.Name { return Notification.Name(rawValue: "fat sidebar hover did start") } var didExit = false var overlayFinished: (() -> Void)? private var trackingArea: NSTrackingArea? override func updateTrackingAreas() { super.updateTrackingAreas() if let oldTrackingArea = self.trackingArea { self.removeTrackingArea(oldTrackingArea) } guard !didExit else { return } createAndAssignTrackingArea() fireEnteredOrExitedWithInitialMouseCoordinates() } fileprivate func createAndAssignTrackingArea() { let newTrackingArea = NSTrackingArea( rect: self.bounds, options: [.mouseEnteredAndExited, .activeAlways], owner: self, userInfo: nil) self.addTrackingArea(newTrackingArea) self.trackingArea = newTrackingArea } fileprivate func fireEnteredOrExitedWithInitialMouseCoordinates() { guard let absoluteMousePoint = self.window?.mouseLocationOutsideOfEventStream else { return } let mousePoint = self.convert(absoluteMousePoint, from: nil) if NSPointInRect(mousePoint, self.bounds) { mouseDidEnter() } else { mouseDidExit() } } override func mouseEntered(with event: NSEvent) { mouseDidEnter() } /// - note: Use when event is not available, as in `updateTrackingRect`. fileprivate func mouseDidEnter() { self.window?.disableCursorRects() NSCursor.pointingHand.set() NotificationCenter.default.post(name: FatSidebarItemOverlay.hoverStarted, object: self) } @objc func hoverDidStart(notification: Notification) { if let overlay = notification.object as? FatSidebarItemOverlay, overlay === self { return } endHover() } override func mouseExited(with event: NSEvent) { mouseDidExit() } /// - note: Use when event is not available, as in `updateTrackingRect`. fileprivate func mouseDidExit() { didExit = true // Call before endHover to prevend updateTrackingRect loop endHover() } fileprivate func endHover() { self.window?.enableCursorRects() self.window?.resetCursorRects() self.removeFromSuperview() overlayFinished?() } // MARK: - Scrolling func setupScrollSyncing(scrollView: NSScrollView) { self.scrolledOffset = scrollView.scrolledY self.windowHeight = scrollView.window?.frame.height scrollView.postsBoundsChangedNotifications = true NotificationCenter.default.addObserver( self, selector: #selector(didScroll(_:)), name: NSView.boundsDidChangeNotification, object: scrollView.contentView) NotificationCenter.default.addObserver( self, selector: #selector(didResizeWindow(_:)), name: NSWindow.didResizeNotification, object: scrollView.window) } fileprivate var windowHeight: CGFloat? @objc func didResizeWindow(_ notification: Notification) { guard let window = notification.object as? NSWindow, let oldHeight = windowHeight else { return } let newHeight = window.frame.height let diff = oldHeight - newHeight self.frame.origin.y -= diff self.windowHeight = newHeight } fileprivate var scrolledOffset: CGFloat? @objc func didScroll(_ notification: Notification) { guard let contentView = notification.object as? NSView, let scrollView = contentView.superview as? NSScrollView, let scrolledOffset = scrolledOffset else { return } let diff = scrolledOffset - scrollView.scrolledY self.frame.origin.y -= diff self.scrolledOffset = scrollView.scrolledY } }
mit
db763c0a938b4d5ab96f02adc346cb47
27.52349
116
0.654118
5.227552
false
false
false
false