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
BarTabs/bartabs
ios-application/Bar Tabs/Geotification.swift
1
3041
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import MapKit import CoreLocation struct GeoKey { static let name = "name" static let latitude = "latitude" static let longitude = "longitude" static let radius = "radius" static let identifier = "identifier" } enum EventType: String { case onEntry = "On Entry" case onExit = "On Exit" } class Geotification: NSObject, NSCoding, MKAnnotation { var coordinate: CLLocationCoordinate2D var objectID: Int64 var name: String var radius: CLLocationDistance var identifier: String var title: String? { if name.isEmpty { return "No Name" } return name } var subtitle: String? { return "Radius: \(radius)m" } init(objectID: Int64, name: String, coordinate: CLLocationCoordinate2D, radius: CLLocationDistance) { self.objectID = objectID self.name = name self.coordinate = coordinate self.radius = radius self.identifier = NSUUID().uuidString } // MARK: NSCoding required init?(coder decoder: NSCoder) { let latitude = decoder.decodeDouble(forKey: GeoKey.latitude) let longitude = decoder.decodeDouble(forKey: GeoKey.longitude) objectID = -1 name = decoder.decodeObject(forKey: GeoKey.name) as! String coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) radius = decoder.decodeDouble(forKey: GeoKey.radius) identifier = decoder.decodeObject(forKey: GeoKey.identifier) as! String } func encode(with coder: NSCoder) { coder.encode(coordinate.latitude, forKey: GeoKey.latitude) coder.encode(coordinate.longitude, forKey: GeoKey.longitude) coder.encode(name, forKey: GeoKey.name) coder.encode(radius, forKey: GeoKey.radius) coder.encode(identifier, forKey: GeoKey.identifier) } }
gpl-3.0
1d70a32ce903682fb93ff93a7f752ac9
33.168539
105
0.692535
4.505185
false
false
false
false
Anviking/Chromatism
Chromatism/NSIndexSet+Additions.swift
1
1367
// // NSIndexSet+Intersection.swift // Chromatism // // Created by Johannes Lund on 2014-07-14. // Copyright (c) 2014 anviking. All rights reserved. // import UIKit func NSIndexSetDelta(_ oldSet: IndexSet, newSet: IndexSet) -> (additions: IndexSet, deletions: IndexSet) { // Old: ABC // ∆(-) B // ∆(+) D // New: A CD // deletions = old - new // additions = new - old let additions = newSet - oldSet let deletions = oldSet - newSet return (additions, deletions) } func -(left: IndexSet, right: IndexSet) -> IndexSet { var indexSet = left for range in right.rangeView { indexSet.remove(integersIn: Range(range)) } return indexSet } func +(left: IndexSet, right: IndexSet) -> IndexSet { var indexSet = left for range in right.rangeView { indexSet.insert(integersIn: Range(range)) } return indexSet } func -=(left: inout IndexSet, right: IndexSet) { left = left - right } func +=(left: inout IndexSet, right: IndexSet) { left = left + right } func -=(left: inout IndexSet, right: Range<Int>) { left.remove(integersIn: right) } func +=(left: inout IndexSet, right: Range<Int>) { left.insert(integersIn: right) } extension NSRange { var end: Int { return location + length } var start: Int { return location } }
mit
e00746124dba50b293af53871bcba17f
19.651515
106
0.619956
3.724044
false
false
false
false
WhisperSystems/Signal-iOS
SignalShareExtension/SAEFailedViewController.swift
1
3380
// // Copyright (c) 2018 Open Whisper Systems. All rights reserved. // import UIKit import SignalMessaging import PureLayout // All Observer methods will be invoked from the main thread. protocol SAEFailedViewDelegate: class { func shareViewWasCancelled() } class SAEFailedViewController: UIViewController { weak var delegate: SAEFailedViewDelegate? let failureTitle: String let failureMessage: String // MARK: Initializers and Factory Methods init(delegate: SAEFailedViewDelegate, title: String, message: String) { self.delegate = delegate self.failureTitle = title self.failureMessage = message super.init(nibName: nil, bundle: nil) } @available(*, unavailable, message:"use other constructor instead.") required init?(coder aDecoder: NSCoder) { notImplemented() } override func loadView() { super.loadView() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelPressed)) self.navigationItem.title = "Signal" self.view.backgroundColor = UIColor.ows_signalBrandBlue let logoImage = UIImage(named: "logoSignal") let logoImageView = UIImageView(image: logoImage) self.view.addSubview(logoImageView) logoImageView.autoCenterInSuperview() let logoSize = CGFloat(120) logoImageView.autoSetDimension(.width, toSize: logoSize) logoImageView.autoSetDimension(.height, toSize: logoSize) let titleLabel = UILabel() titleLabel.textColor = UIColor.white titleLabel.font = UIFont.ows_mediumFont(withSize: 18) titleLabel.text = failureTitle titleLabel.textAlignment = .center titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byWordWrapping self.view.addSubview(titleLabel) titleLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: 20) titleLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: 20) titleLabel.autoPinEdge(.top, to: .bottom, of: logoImageView, withOffset: 25) let messageLabel = UILabel() messageLabel.textColor = UIColor.white messageLabel.font = UIFont.ows_regularFont(withSize: 14) messageLabel.text = failureMessage messageLabel.textAlignment = .center messageLabel.numberOfLines = 0 messageLabel.lineBreakMode = .byWordWrapping self.view.addSubview(messageLabel) messageLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: 20) messageLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: 20) messageLabel.autoPinEdge(.top, to: .bottom, of: titleLabel, withOffset: 10) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = false } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } // MARK: - Event Handlers @objc func cancelPressed(sender: UIButton) { guard let delegate = delegate else { owsFailDebug("missing delegate") return } delegate.shareViewWasCancelled() } }
gpl-3.0
06ed6b84eed5f45baca6b3e3f3d07d31
33.845361
97
0.665976
5.339652
false
false
false
false
brokenseal/WhereIsMaFood
WhereIsMaFood/LocationManager.swift
1
2009
// // LocationManager.swift // WhereIsMaFood // // Created by Davide Callegari on 28/07/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import MapKit import Foundation import CoreLocation class LocationManager: NSObject { private let clLocationManager = CLLocationManager() var lastLocation: CLLocation? init( distanceFilter: Double = 200.0, accuracy: CLLocationAccuracy = kCLLocationAccuracyNearestTenMeters ) { super.init() clLocationManager.delegate = self clLocationManager.distanceFilter = distanceFilter // update every # meters clLocationManager.desiredAccuracy = accuracy } func initiate() { handleAuthorizationStatus(CLLocationManager.authorizationStatus()) } func startReceivingLocationUpdates(){ clLocationManager.startUpdatingLocation() } func stopReceivingLocationsUpdate(){ clLocationManager.stopUpdatingLocation() } func handleAuthorizationStatus(_ authorizationStatus: CLAuthorizationStatus) { switch authorizationStatus { case .notDetermined: clLocationManager.requestWhenInUseAuthorization() case .denied: App.main.trigger( App.Message.warnUser, object: "The app cannot work properly withouth the permission to monitor its position while in use" ) case .authorizedWhenInUse, .authorizedAlways: startReceivingLocationUpdates() default: return } } } extension LocationManager: CLLocationManagerDelegate { func locationManager( _ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus ) { handleAuthorizationStatus(status) App.main.trigger(App.Message.locationAuthorizationStatusUpdated, object: status) } func locationManager( _ manager: CLLocationManager, didUpdateLocations locations: [CLLocation] ) { if let location = locations.last { lastLocation = location App.main.trigger(App.Message.newLocation, object: location) } } }
mit
c0d95087e578d97065c0c53e6e7164bf
25.421053
107
0.733566
5.32626
false
false
false
false
xedin/swift
test/expr/closure/trailing.swift
2
21251
// RUN: %target-typecheck-verify-swift -swift-version 4 @discardableResult func takeFunc(_ f: (Int) -> Int) -> Int {} func takeValueAndFunc(_ value: Int, _ f: (Int) -> Int) {} func takeTwoFuncs(_ f: (Int) -> Int, _ g: (Int) -> Int) {} func takeFuncWithDefault(f : ((Int) -> Int)? = nil) {} func takeTwoFuncsWithDefaults(f1 : ((Int) -> Int)? = nil, f2 : ((String) -> String)? = nil) {} struct X { func takeFunc(_ f: (Int) -> Int) {} func takeValueAndFunc(_ value: Int, f: (Int) -> Int) {} func takeTwoFuncs(_ f: (Int) -> Int, g: (Int) -> Int) {} } func addToMemberCalls(_ x: X) { x.takeFunc() { x in x } x.takeFunc() { $0 } x.takeValueAndFunc(1) { x in x } x.takeTwoFuncs({ x in x }) { y in y } } func addToCalls() { takeFunc() { x in x } takeFunc() { $0 } takeValueAndFunc(1) { x in x } takeTwoFuncs({ x in x }) { y in y } } func makeCalls() { takeFunc { x in x } takeFunc { $0 } takeTwoFuncs ({ x in x }) { y in y } } func notPostfix() { _ = 1 + takeFunc { $0 } } func notLiterals() { struct SR3671 { // <https://bugs.swift.org/browse/SR-3671> var v: Int = 1 { // expected-error {{variable with getter/setter cannot have an initial value}} get { return self.v } } } var x: Int? = nil { get { } } // expected-error {{variable with getter/setter cannot have an initial value}} _ = 1 {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{9-9=do }} _ = "hello" {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{15-15=do }} _ = [42] {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{12-12=do }} _ = (6765, 10946, 17711) {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{28-28=do }} } class C { func map(_ x: (Int) -> Int) -> C { return self } func filter(_ x: (Int) -> Bool) -> C { return self } } var a = C().map {$0 + 1}.filter {$0 % 3 == 0} var b = C().map {$0 + 1} .filter {$0 % 3 == 0} var c = C().map { $0 + 1 } var c2 = C().map // expected-note{{callee is here}} { // expected-warning{{braces here form a trailing closure separated from its callee by multiple newlines}} $0 + 1 } var c3 = C().map // expected-note{{callee is here}} // blah blah blah { // expected-warning{{braces here form a trailing closure separated from its callee by multiple newlines}} $0 + 1 } // Calls with multiple trailing closures should be rejected until we have time // to design it right. // <rdar://problem/16835718> Ban multiple trailing closures func multiTrailingClosure(_ a : () -> (), b : () -> ()) { // expected-note {{'multiTrailingClosure(_:b:)' declared here}} multiTrailingClosure({}) {} // ok multiTrailingClosure {} {} // expected-error {{missing argument for parameter #1 in call}} expected-error {{consecutive statements on a line must be separated by ';'}} {{26-26=;}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{27-27=do }} } func labeledArgumentAndTrailingClosure() { // Trailing closures can bind to labeled parameters. takeFuncWithDefault { $0 + 1 } takeFuncWithDefault() { $0 + 1 } // ... but not non-trailing closures. takeFuncWithDefault({ $0 + 1 }) // expected-error {{missing argument label 'f:' in call}} {{23-23=f: }} takeFuncWithDefault(f: { $0 + 1 }) // Trailing closure binds to last parameter, always. takeTwoFuncsWithDefaults { "Hello, " + $0 } takeTwoFuncsWithDefaults { $0 + 1 } // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '((String) -> String)?'}} takeTwoFuncsWithDefaults(f1: {$0 + 1 }) } // rdar://problem/17965209 func rdar17965209_f<T>(_ t: T) {} func rdar17965209(x: Int = 0, _ handler: (_ y: Int) -> ()) {} func rdar17965209_test() { rdar17965209() { (y) -> () in rdar17965209_f(1) } rdar17965209(x: 5) { (y) -> () in rdar17965209_f(1) } } // <rdar://problem/22298549> QoI: Unwanted trailing closure produces weird error func limitXY(_ xy:Int, toGamut gamut: [Int]) {} let someInt = 0 let intArray = [someInt] limitXY(someInt, toGamut: intArray) {} // expected-error{{cannot invoke 'limitXY' with an argument list of type '(Int, toGamut: [Int], @escaping () -> ())'}} // expected-note@-1{{expected an argument list of type '(Int, toGamut: [Int])'}} // <rdar://problem/23036383> QoI: Invalid trailing closures in stmt-conditions produce lowsy diagnostics func retBool(x: () -> Int) -> Bool {} func maybeInt(_: () -> Int) -> Int? {} class Foo23036383 { init() {} func map(_: (Int) -> Int) -> Int? {} func meth1(x: Int, _: () -> Int) -> Bool {} func meth2(_: Int, y: () -> Int) -> Bool {} func filter(by: (Int) -> Bool) -> [Int] {} } enum MyErr : Error { case A } func r23036383(foo: Foo23036383?, obj: Foo23036383) { if retBool(x: { 1 }) { } // OK if (retBool { 1 }) { } // OK if retBool{ 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{13-13=(x: }} {{18-18=)}} } if retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{13-14=(x: }} {{19-19=)}} } if retBool() { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{14-16=x: }} {{21-21=)}} } else if retBool( ) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{21-24=x: }} {{29-29=)}} } if let _ = maybeInt { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}} } if let _ = maybeInt { 1 } , true { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}} } if let _ = foo?.map {$0+1} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{29-29=)}} } if let _ = foo?.map() {$0+1} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{23-25=}} {{31-31=)}} } if let _ = foo, retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{26-27=(x: }} {{32-32=)}} } if obj.meth1(x: 1) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{20-22=, }} {{27-27=)}} } if obj.meth2(1) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{17-19=, y: }} {{24-24=)}} } for _ in obj.filter {$0 > 4} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(by: }} {{31-31=)}} } for _ in obj.filter {$0 > 4} where true { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(by: }} {{31-31=)}} } for _ in [1,2] where retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{31-32=(x: }} {{37-37=)}} } while retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{16-17=(x: }} {{22-22=)}} } while let _ = foo, retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{29-30=(x: }} {{35-35=)}} } switch retBool { return 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{17-18=(x: }} {{30-30=)}} default: break } do { throw MyErr.A; } catch MyErr.A where retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{32-33=(x: }} {{38-38=)}} } catch { } if let _ = maybeInt { 1 }, retBool { 1 } { } // expected-error@-1 {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}} // expected-error@-2 {{trailing closure requires parentheses for disambiguation in this context}} {{37-38=(x: }} {{43-43=)}} } func overloadOnLabel(a: () -> Void) {} func overloadOnLabel(b: () -> Void) {} func overloadOnLabel(c: () -> Void) {} func overloadOnLabel2(a: () -> Void) {} func overloadOnLabel2(_: () -> Void) {} func overloadOnLabelArgs(_: Int, a: () -> Void) {} func overloadOnLabelArgs(_: Int, b: () -> Void) {} func overloadOnLabelArgs2(_: Int, a: () -> Void) {} func overloadOnLabelArgs2(_: Int, _: () -> Void) {} func overloadOnLabelDefaultArgs(x: Int = 0, a: () -> Void) {} func overloadOnLabelDefaultArgs(x: Int = 1, b: () -> Void) {} func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 0, a: () -> Void) {} func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 1, b: () -> Void) {} func overloadOnDefaultArgsOnly(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly(y: Int = 1, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly2(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly2(y: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly3(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly3(x: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnSomeDefaultArgsOnly(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly(_: Int, y: Int = 1, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly2(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly2(_: Int, y: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly3(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly3(_: Int, x: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}} func testOverloadAmbiguity() { overloadOnLabel {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{18-19=(a: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{18-19=(b: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{18-19=(c: }} {{21-21=)}} overloadOnLabel() {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{19-21=a: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{19-21=b: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{19-21=c: }} {{23-23=)}} overloadOnLabel2 {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{19-20=(a: }} {{22-22=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{19-20=(}} {{22-22=)}} overloadOnLabel2() {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{20-22=a: }} {{24-24=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{20-22=}} {{24-24=)}} overloadOnLabelArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:a:)'}} {{24-26=, a: }} {{28-28=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:b:)'}} {{24-26=, b: }} {{28-28=)}} overloadOnLabelArgs2(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs2(_:a:)'}} {{25-27=, a: }} {{29-29=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabelArgs2'}} {{25-27=, }} {{29-29=)}} overloadOnLabelDefaultArgs {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{29-30=(a: }} {{32-32=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{29-30=(b: }} {{32-32=)}} overloadOnLabelDefaultArgs() {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{30-32=a: }} {{34-34=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{30-32=b: }} {{34-34=)}} overloadOnLabelDefaultArgs(x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{34-36=, a: }} {{38-38=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{34-36=, b: }} {{38-38=)}} overloadOnLabelSomeDefaultArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{35-37=, a: }} {{39-39=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{35-37=, b: }} {{39-39=)}} overloadOnLabelSomeDefaultArgs(1, x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{41-43=, a: }} {{45-45=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{41-43=, b: }} {{45-45=)}} overloadOnLabelSomeDefaultArgs( // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{12-5=, a: }} {{4-4=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{12-5=, b: }} {{4-4=)}} 1, x: 2 ) { // some } overloadOnDefaultArgsOnly {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}} overloadOnDefaultArgsOnly() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}} overloadOnDefaultArgsOnly2 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}} overloadOnDefaultArgsOnly2() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}} overloadOnDefaultArgsOnly3 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}} overloadOnDefaultArgsOnly3() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}} overloadOnSomeDefaultArgsOnly(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly'}} overloadOnSomeDefaultArgsOnly2(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly2'}} overloadOnSomeDefaultArgsOnly3(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly3(_:x:a:)'}} } func overloadMismatch(a: () -> Void) -> Bool { return true} func overloadMismatch(x: Int = 0, a: () -> Void) -> Int { return 0 } func overloadMismatchLabel(a: () -> Void) -> Bool { return true} func overloadMismatchLabel(x: Int = 0, b: () -> Void) -> Int { return 0 } func overloadMismatchArgs(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchArgs(_: Int, x: Int = 0, a: () -> Void) -> Int { return 0 } func overloadMismatchArgsLabel(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchArgsLabel(_: Int, x: Int = 0, b: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgs(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgs(_: Int, x: Int = 0, y: Int = 1, a: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgsLabel(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgsLabel(_: Int, x: Int = 0, y: Int = 1, b: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgs2(_: Int, z: Int = 0, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgs2(_: Int, x: Int = 0, y: Int = 1, a: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgs2Label(_: Int, z: Int = 0, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgs2Label(_: Int, x: Int = 0, y: Int = 1, b: () -> Void) -> Int { return 0 } func testOverloadDefaultArgs() { let a = overloadMismatch {} _ = a as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let b = overloadMismatch() {} _ = b as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let c = overloadMismatchLabel {} _ = c as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let d = overloadMismatchLabel() {} _ = d as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let e = overloadMismatchArgs(0) {} _ = e as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let f = overloadMismatchArgsLabel(0) {} _ = f as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let g = overloadMismatchMultiArgs(0) {} _ = g as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let h = overloadMismatchMultiArgsLabel(0) {} _ = h as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let i = overloadMismatchMultiArgs2(0) {} _ = i as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let j = overloadMismatchMultiArgs2Label(0) {} _ = j as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} } func variadic(_: (() -> Void)...) {} func variadicLabel(closures: (() -> Void)...) {} func variadicOverloadMismatch(_: (() -> Void)...) -> Bool { return true } func variadicOverloadMismatch(x: Int = 0, _: (() -> Void)...) -> Int { return 0 } func variadicOverloadMismatchLabel(a: (() -> Void)...) -> Bool { return true } func variadicOverloadMismatchLabel(x: Int = 0, b: (() -> Void)...) -> Int { return 0 } func variadicAndNonOverload(_: (() -> Void)) -> Bool { return false } func variadicAndNonOverload(_: (() -> Void)...) -> Int { return 0 } func variadicAndNonOverloadLabel(a: (() -> Void)) -> Bool { return false } func variadicAndNonOverloadLabel(b: (() -> Void)...) -> Int { return 0 } func testVariadic() { variadic {} variadic() {} variadic({}) {} // expected-error {{extra argument in call}} variadicLabel {} variadicLabel() {} variadicLabel(closures: {}) {} // expected-error {{extra argument 'closures' in call}} let a1 = variadicOverloadMismatch {} _ = a1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let a2 = variadicOverloadMismatch() {} _ = a2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let b1 = variadicOverloadMismatchLabel {} _ = b1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let b2 = variadicOverloadMismatchLabel() {} _ = b2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let c1 = variadicAndNonOverloadLabel {} _ = c1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let c2 = variadicAndNonOverload {} _ = c2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} } // rdar://18426302 class TrailingBase { init(fn: () -> ()) {} init(x: Int, fn: () -> ()) {} convenience init() { self.init {} } convenience init(x: Int) { self.init(x: x) {} } } class TrailingDerived : TrailingBase { init(foo: ()) { super.init {} } init(x: Int, foo: ()) { super.init(x: x) {} } }
apache-2.0
1e58a8a490aa13203847dbfd3d68511d
52.936548
485
0.657193
3.889987
false
false
false
false
sora0077/DribbbleKit
DribbbleKit/Sources/Shots/Comments/Comments.swift
1
1778
// // Comments.swift // DribbbleKit // // Created by 林 達也 on 2017/04/26. // Copyright © 2017年 jp.sora0077. All rights reserved. // import Foundation import Alter public struct Comment { public struct Identifier: Decodable, Hashable, ExpressibleByIntegerLiteral { let value: Int public var hashValue: Int { return value.hashValue } public init(integerLiteral value: Int) { self.value = value } public init(_ value: Int) { self.value = value } public static func decode(_ decoder: Decoder) throws -> Comment.Identifier { return try self.init(integerLiteral: Int.decode(decoder)) } public static func == (lhs: Identifier, rhs: Identifier) -> Bool { return lhs.value == rhs.value } } } extension Int { public init(_ commentId: Comment.Identifier) { self = commentId.value } } // MARK: - CommentData public protocol CommentData: Decodable { typealias Identifier = Comment.Identifier init( id: Comment.Identifier, body: String, likesCount: Int, likesURL: URL, createdAt: Date, updatedAt: Date ) throws } extension CommentData { public static func decode(_ decoder: Decoder) throws -> Self { return try self.init( id: decoder.decode(forKeyPath: "id"), body: decoder.decode(forKeyPath: "body"), likesCount: decoder.decode(forKeyPath: "likes_count"), likesURL: decoder.decode(forKeyPath: "likes_url", Transformer.url), createdAt: decoder.decode(forKeyPath: "created_at", Transformer.date), updatedAt: decoder.decode(forKeyPath: "updated_at", Transformer.date)) } }
mit
5d2dd065919e4674f3ee31fea8ef210b
26.640625
84
0.617298
4.411471
false
false
false
false
hxx0215/VPNOn
VPNOn/Views/LTVPNTableViewCell.swift
1
3366
// // LTVPNTableViewCell.swift // VPNOn // // Created by Lex on 1/16/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit let kLTTableViewCellAccessoryWidth: CGFloat = 16 let kLTTableViewCellRightMargin: CGFloat = 36 class LTVPNTableViewCell: UITableViewCell { var IKEv2: Bool = false { didSet { self.setNeedsDisplay() } } var current: Bool = false { didSet { self.setNeedsDisplay() } } override func drawRect(rect: CGRect) { if IKEv2 { let tagWidth: CGFloat = 34 let tagHeight: CGFloat = 14 let tagX = CGRectGetWidth(bounds) - tagWidth - kLTTableViewCellAccessoryWidth - kLTTableViewCellRightMargin let tagY = (CGRectGetHeight(bounds) - tagHeight) / 2 let tagRect = CGRectMake(tagX, tagY, tagWidth, tagHeight) drawIKEv2Tag(radius: 2, rect: tagRect, tagText: "IKEv2", color: tintColor) } if current { let context = UIGraphicsGetCurrentContext() let currentIndicatorRect = CGRect(x: 0, y: 0, width: 7, height: rect.size.height) let rectanglePath = UIBezierPath(rect: currentIndicatorRect) LTThemeManager.sharedManager.currentTheme!.tintColor.setFill() rectanglePath.fill() } } func drawIKEv2Tag(#radius: CGFloat, rect: CGRect, tagText: String, color: UIColor) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Variable Declarations let height: CGFloat = rect.size.height / 1.20 //// Rectangle Drawing let rectanglePath = UIBezierPath(roundedRect: rect, cornerRadius: radius) color.setStroke() rectanglePath.lineWidth = 1 rectanglePath.stroke() //// Text Drawing let textRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height) let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle textStyle.alignment = NSTextAlignment.Center let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(height - 1), NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: textStyle] let textTextHeight: CGFloat = NSString(string: tagText).boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height CGContextSaveGState(context) CGContextClipToRect(context, textRect); NSString(string: tagText).drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes) CGContextRestoreGState(context) } override func willMoveToSuperview(newSuperview: UIView?) { if newSuperview != nil { if accessoryType == .DisclosureIndicator { if accessoryView == nil { accessoryView = LTTableViewCellDeclosureIndicator() accessoryView!.frame = CGRectMake(0, 0, kLTTableViewCellAccessoryWidth, kLTTableViewCellAccessoryWidth) } } } } }
mit
f5d8dec0d89475aa8c79409f80dc63b1
39.071429
244
0.653595
5.154671
false
false
false
false
andrzejsemeniuk/ASToolkit
ASToolkit/ExtensionForUIKitUIColor.swift
1
15124
// // ExtensionForUIKitUIColor.swift // ASToolkit // // Created by andrzej semeniuk on 10/9/16. // Copyright © 2017 Andrzej Semeniuk. All rights reserved. // import Foundation import UIKit extension UIColor { public convenience init(white:CGFloat) { self.init(white:white, alpha:1) } public convenience init(gray:CGFloat,alpha:CGFloat = 1) { self.init(red:gray, green:gray, blue:gray, alpha:alpha) } public convenience init(red:CGFloat,green:CGFloat,blue:CGFloat) { self.init(red:red, green:green, blue:blue, alpha:1) } public convenience init(hue:CGFloat,saturation:CGFloat = 1,brightness:CGFloat = 1) { self.init(hue:hue, saturation:saturation, brightness:brightness, alpha:1) } public convenience init(hsb:[CGFloat],alpha:CGFloat = 1) { self.init(hue:hsb[safe:0] ?? 0, saturation:hsb[safe:1] ?? 0, brightness:hsb[safe:2] ?? 0, alpha:alpha) } public convenience init(hsba:[CGFloat]) { self.init(hue:hsba[safe:0] ?? 0, saturation:hsba[safe:1] ?? 0, brightness:hsba[safe:2] ?? 0, alpha:hsba[safe:3] ?? 0) } public convenience init(rgb:[CGFloat],alpha:CGFloat = 1) { self.init(red:rgb[safe:0] ?? 0, green:rgb[safe:1] ?? 0, blue:rgb[safe:2] ?? 0, alpha:alpha) } public convenience init(rgba:[CGFloat]) { self.init(red:rgba[safe:0] ?? 0, green:rgba[safe:1] ?? 0, blue:rgba[safe:2] ?? 0, alpha:rgba[safe:3] ?? 0) } public convenience init(r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat = 1) { self.init(red:r, green:g, blue:b, alpha:a) } public convenience init(h:CGFloat,s:CGFloat,b:CGFloat,a:CGFloat = 1) { self.init(hue:h, saturation:s, brightness:b, alpha:a) } public typealias Components_RGBA_UInt8 = (red:UInt8,green:UInt8,blue:UInt8,alpha:UInt8) public func components_RGBA_UInt8() -> Components_RGBA_UInt8 { let components = RGBA let maximum:CGFloat = 256 let r = Float(components.red*maximum).clampedTo0255 let g = Float(components.green*maximum).clampedTo0255 let b = Float(components.blue*maximum).clampedTo0255 let a = Float(components.alpha*maximum).clampedTo0255 let result = ( UInt8(r), UInt8(g), UInt8(b), UInt8(a) ) return result } public func components_RGBA_UInt8_equals(_ b:Components_RGBA_UInt8) -> Bool { let a = components_RGBA_UInt8() return a.red==b.red && a.green==b.green && a.blue==b.blue && a.alpha==b.alpha } public func components_RGBA_UInt8_equals(_ another:UIColor) -> Bool { return components_RGBA_UInt8_equals(another.components_RGBA_UInt8()) } public func components_RGB_UInt8_equals(_ b:Components_RGBA_UInt8) -> Bool { let a = components_RGBA_UInt8() return a.red==b.red && a.green==b.green && a.blue==b.blue } public func components_RGB_UInt8_equals(_ another:UIColor) -> Bool { return components_RGB_UInt8_equals(another.components_RGBA_UInt8()) } public typealias RGBATuple = (red:CGFloat,green:CGFloat,blue:CGFloat,alpha:CGFloat) public var RGBA : RGBATuple { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 1 self.getRed(&r,green:&g,blue:&b,alpha:&a) return (r,g,b,a) } public var arrayOfRGBA : [CGFloat] { let v = RGBA return [v.red, v.green, v.blue, v.alpha] } public convenience init(RGBA:RGBATuple) { self.init(red:RGBA.red, green:RGBA.green, blue:RGBA.blue, alpha:RGBA.alpha) } public typealias HSBATuple = (hue:CGFloat,saturation:CGFloat,brightness:CGFloat,alpha:CGFloat) public var HSBA : HSBATuple { var h:CGFloat = 0 var s:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 1 self.getHue(&h,saturation:&s,brightness:&b,alpha:&a) return (h,s,b,a) } public var arrayOfHSBA : [CGFloat] { let v = HSBA return [v.hue, v.saturation, v.brightness, v.alpha] } public convenience init(HSBA:HSBATuple) { self.init(hue:HSBA.hue, saturation:HSBA.saturation, brightness:HSBA.brightness, alpha:HSBA.alpha) } public var RGBAred :CGFloat { return RGBA.red } public var RGBAgreen :CGFloat { return RGBA.green } public var RGBAblue :CGFloat { return RGBA.blue } public var RGBAalpha :CGFloat { return RGBA.alpha } public var HSBAhue :CGFloat { return HSBA.hue } public var HSBAsaturation :CGFloat { return HSBA.saturation } public var HSBAbrightness :CGFloat { return HSBA.brightness } open class func GRAY(_ v:Float, _ a:Float = 1.0) -> UIColor { return UIColor(white:CGFloat(v),alpha:CGFloat(a)) } open class func RGBA(_ r:Float, _ g:Float, _ b:Float, _ a:Float = 1.0) -> UIColor { return UIColor(red:CGFloat(r),green:CGFloat(g),blue:CGFloat(b),alpha:CGFloat(a)) } open class func HSBA(_ h:Float, _ s:Float, _ b:Float, _ a:Float = 1.0) -> UIColor { return UIColor(hue:CGFloat(h),saturation:CGFloat(s),brightness:CGFloat(b),alpha:CGFloat(a)) } open func multiply (byRatio ratio:CGFloat) -> UIColor { let RGBA = self.RGBA return UIColor(red : CGFloat(ratio * RGBA.red).clampedTo01, green : CGFloat(ratio * RGBA.green).clampedTo01, blue : CGFloat(ratio * RGBA.blue).clampedTo01, alpha : RGBA.alpha) } open func higher (byRatio ratio:CGFloat) -> UIColor { let RGBA = self.RGBA return UIColor(red : CGFloat(RGBA.red + (1.0 - RGBA.red) * ratio).clampedTo01, green : CGFloat(RGBA.green + (1.0 - RGBA.green) * ratio).clampedTo01, blue : CGFloat(RGBA.blue + (1.0 - RGBA.blue) * ratio).clampedTo01, alpha : RGBA.alpha) } open func lower (byRatio ratio:CGFloat) -> UIColor { let RGBA = self.RGBA return UIColor(red : CGFloat(RGBA.red - RGBA.red * ratio).clampedTo01, green : CGFloat(RGBA.green - RGBA.green * ratio).clampedTo01, blue : CGFloat(RGBA.blue - RGBA.blue * ratio).clampedTo01, alpha : RGBA.alpha) } } extension UIColor { public typealias CMYKTuple = (cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, key: CGFloat) public typealias CMYKATuple = (cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, key: CGFloat, alpha: CGFloat) public var CMYK:CMYKTuple { // r = (1-c)(1-k) ?? // c = 1-r/(1-k) ?? let RGB = self.RGBA if RGB.red < 0.001 && RGB.green < 0.001 && RGB.blue < 0.001 { return (0,0,0,1) } let computedC = 1 - RGB.red.clampedTo01 let computedM = 1 - RGB.green.clampedTo01 let computedY = 1 - RGB.blue.clampedTo01 let minCMY : CGFloat = min(computedC, computedM, computedY) let denominator : CGFloat = 1 - minCMY return ( (computedC - minCMY) / denominator, (computedM - minCMY) / denominator, (computedY - minCMY) / denominator, minCMY ) } public var CMYKA : CMYKATuple { let CMYK = self.CMYK return (CMYK.cyan, CMYK.magenta, CMYK.yellow, CMYK.key, RGBAalpha) } public convenience init(cyan:CGFloat, magenta:CGFloat, yellow:CGFloat, key:CGFloat, alpha:CGFloat = 1) { // r = (1 - c) * (1 - k) let multiplier : CGFloat = 1.0 - key.clampedTo01 self.init( r: (1.0 - cyan.clampedTo01) * multiplier, g: (1.0 - magenta.clampedTo01) * multiplier, b: (1.0 - yellow.clampedTo01) * multiplier, a: alpha ) } public convenience init(c:CGFloat, m:CGFloat, y:CGFloat, k:CGFloat, a:CGFloat = 1) { self.init(cyan:c, magenta:m, yellow:y, key:k, alpha:a) } public convenience init(cmyk:[CGFloat]) { self.init(cyan:cmyk[0], magenta:cmyk[1], yellow:cmyk[2], key:cmyk[3]) } public convenience init(cmyka:[CGFloat]) { self.init(cyan:cmyka[0], magenta:cmyka[1], yellow:cmyka[2], key:cmyka[3], alpha:cmyka[4]) } public convenience init(CMYK:CMYKTuple, alpha:CGFloat = 1) { self.init(cyan:CMYK.cyan, magenta:CMYK.magenta, yellow:CMYK.yellow, key:CMYK.key, alpha:alpha) } public convenience init(CMYKA:CMYKATuple) { self.init(cyan:CMYKA.cyan, magenta:CMYKA.magenta, yellow:CMYKA.yellow, key:CMYKA.key, alpha:CMYKA.alpha) } } extension UIColor { static open func generateListOfDefaultColors() -> [UIColor] { var colors = [ UIColor.GRAY(1.00,1), UIColor.GRAY(0.90,1), UIColor.GRAY(0.80,1), UIColor.GRAY(0.70,1), UIColor.GRAY(0.60,1), UIColor.GRAY(0.50,1), UIColor.GRAY(0.40,1), UIColor.GRAY(0.30,1), UIColor.GRAY(0.20,1), UIColor.GRAY(0.10,1), UIColor.GRAY(0.00,1), ] let hues : [Float] = [0,0.06,0.1,0.14,0.2,0.3,0.4,0.53,0.6,0.7,0.8,0.9] let saturations : [Float] = [0.4,0.6,0.8,1] let values : [Float] = [1] for h in hues { for v in values { for s in saturations { colors.append(UIColor.HSBA(h,s,v,1)) } } } return colors } static open func generateMatrixOfColors(columns : Int = 7, rowsOfGray : Int = 2, rowsOfHues : Int = 20) -> [[UIColor]] { var delta:Double var colors:[[UIColor]] = [] if 0 < rowsOfGray { delta = 1.0/Double(columns * rowsOfGray - 1) colors = stride(from:1.0,to:delta-0.001,by:-delta).asArray.asArrayOfCGFloat.map { UIColor(white:$0) }.appended(.black).split(by:columns) } if 0 < rowsOfHues { delta = 1.0/Double(rowsOfHues) let hues : [Float] = stride(from:0.0,to:1.0001-delta,by:delta).asArray.asArrayOfFloat delta = 1.0/Double(columns+1) let saturations : [Float] = stride(from:delta,to:1.0,by:delta).asArray.asArrayOfFloat let values : [Float] = [1] for h in hues { var row:[UIColor] = [] for v in values { for s in saturations { row.append(UIColor.HSBA(h,s,v,1)) } } colors.append(row) } } return colors } } extension UIColor { open var descriptionAsRGB : String { let v = RGBA return "UIColor(rgb:[\(v.red),\(v.green),\(v.blue)])" } open var descriptionAsRGBA : String { let v = RGBA return "UIColor(rgba:[\(v.red),\(v.green),\(v.blue),\(v.alpha)])" } open var descriptionAsHSB : String { let v = HSBA return "UIColor(hsb:[\(v.hue),\(v.saturation),\(v.brightness)])" } open var descriptionAsHSBA : String { let v = HSBA return "UIColor(hsba:[\(v.hue),\(v.saturation),\(v.brightness),\(v.alpha)])" } open var representationOfRGBAasHexadecimal : [String] { let v = components_RGBA_UInt8() return [ String(format:"%02X",v.red), String(format:"%02X",v.green), String(format:"%02X",v.blue), String(format:"%02X",v.alpha), ] // return String(format:"0x%02X%02X%02X%02X", v.red, v.green, v.blue, v.alpha) } public convenience init?(RGBA:String) { // print(RGBA) guard 8 <= RGBA.length else { return nil } let R = RGBA.substring(from: 0, to: 2) let G = RGBA.substring(from: 2, to: 4) let B = RGBA.substring(from: 4, to: 6) let A = RGBA.substring(from: 6, to: 8) guard let R256 = UInt8(R,radix:16), let G256 = UInt8(G,radix:16), let B256 = UInt8(B,radix:16), let A256 = UInt8(A,radix:16) else { return nil } let rgba : [CGFloat] = [ CGFloat(R256)/255, CGFloat(G256)/255, CGFloat(B256)/255, CGFloat(A256)/255 ] self.init(rgba:rgba) // print([R,G,B,A]) // print([R256,G256,B256,A256]) // print(rgba) // print(self.representationOfRGBAasHexadecimal) } } extension UIColor { open func withHue(_ value:CGFloat) -> UIColor { var HSBA = self.HSBA HSBA.hue = value return UIColor(HSBA:HSBA) } open func withSaturation(_ value:CGFloat) -> UIColor { var HSBA = self.HSBA HSBA.saturation = value return UIColor(HSBA:HSBA) } open func withBrightness(_ value:CGFloat) -> UIColor { var HSBA = self.HSBA HSBA.brightness = value return UIColor(HSBA:HSBA) } open func withRed(_ value:CGFloat) -> UIColor { var RGBA = self.RGBA RGBA.red = value return UIColor(RGBA:RGBA) } open func withGreen(_ value:CGFloat) -> UIColor { var RGBA = self.RGBA RGBA.green = value return UIColor(RGBA:RGBA) } open func withBlue(_ value:CGFloat) -> UIColor { var RGBA = self.RGBA RGBA.blue = value return UIColor(RGBA:RGBA) } open func withCyan(_ value:CGFloat) -> UIColor { var CMYKA = self.CMYKA CMYKA.cyan = value return UIColor(CMYKA:CMYKA) } open func withMagenta(_ value:CGFloat) -> UIColor { var CMYKA = self.CMYKA CMYKA.magenta = value return UIColor(CMYKA:CMYKA) } open func withYellow(_ value:CGFloat) -> UIColor { var CMYKA = self.CMYKA CMYKA.yellow = value return UIColor(CMYKA:CMYKA) } open func withKey(_ value:CGFloat) -> UIColor { var CMYKA = self.CMYKA CMYKA.key = value return UIColor(CMYKA:CMYKA) } } extension UIColor { open class var aqua : UIColor { return UIColor(hsb:[0.51,1,1]) } open class var pink : UIColor { return UIColor(rgb:[1,0.80,0.90]) } }
mit
b18f11faf75f37a8f2940366316d78ca
30.053388
148
0.54103
3.674198
false
false
false
false
curious-inc/dry-api-swift
lib/DryApiClient.small.swift
1
27956
import Foundation; public class DryApiError: NSObject { public let code: String; public let message: String; init(_ code: String, _ message: String){ self.code = code; self.message = message; } class func withError(error: NSError) -> DryApiError { return(DryApiError("NSError.\(error.code)", error.localizedDescription)); } class func withDictionary(dictionary: NSDictionary) -> DryApiError { var code = "no_code"; var message = "no_message"; if let c = dictionary["code"] as? NSString { code = c as String; } if let m = dictionary["message"] as? NSString { message = m as String; } return(DryApiError(code, message)); } public override var description: String { return("code: \(self.code) message: \(self.message)"); } } public class DryApiClientBase : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { var _endpoint = ""; public var debug = false; public let null = NSNull(); init(_ endpoint: String){ _endpoint = endpoint; } var _tags = NSMutableDictionary(); func tags() -> NSDictionary { return(_tags.copy() as! NSDictionary); } func tags(key: String) -> String? { return(_tags[key] as! String?); } func tags(key: String, _ val: String) -> DryApiClientBase { _tags[key] = val; return (self); } var _unsafeDomains: Array<String> = []; func addUnsafeDomain(domain: String) { _unsafeDomains.append(domain); } public func URLSession(_ session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust){ // print("https circumvent test host: \(challenge.protectionSpace.host)"); if(_unsafeDomains.indexOf(challenge.protectionSpace.host) != nil){ var credential: NSURLCredential = NSURLCredential(trust: challenge.protectionSpace.serverTrust!); completionHandler(.UseCredential, credential); }else{ completionHandler(.CancelAuthenticationChallenge, nil); } } } var _session: NSURLSession?; func session() -> NSURLSession { if(_session != nil){ return(_session!); } var configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration(); configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Never if(_unsafeDomains.count > 0){ _session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil); }else{ _session = NSURLSession(configuration: configuration); } return(_session!); } func postRequest(url: String, _ data: NSData, _ callback: ((error: DryApiError?, data: NSData?)->())){ let session = self.session(); let nsurl = NSURL(string: url); let request = NSMutableURLRequest(URL: nsurl!); request.HTTPMethod = "POST"; request.HTTPBody = data; // request.setValue("text/plain", forHTTPHeaderField: "Content-Type") let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in if(error != nil){ return callback(error: DryApiError.withError(error!), data: nil); } if let response = response as? NSHTTPURLResponse { if response.statusCode != 200 { return callback(error: DryApiError("not_200", "The server reply was: \(response.statusCode), we only accept 200"), data: nil); } } return callback(error: nil, data: data); }); task.resume() } func postRequestWithString(url: String, _ data: String, _ callback: ((error: DryApiError?, data: NSData?)->())){ return postRequest(url, data.dataUsingEncoding(NSUTF8StringEncoding)!, callback); } func dataToString(data: NSData) -> String{ if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return(string as String); }else{ return(""); } } func responseToArgs(data: NSData?, _ callback: ((error: DryApiError?, args: [AnyObject?]?)->())){ var args: [AnyObject?] = []; if(data == nil){ callback(error: DryApiError("no_data", "No data received."), args: nil); } let data = data!; self.parse(data, { (error, response) in if(error != nil){ return callback(error: error, args: nil); } let response = response! if(self.debug){ print("reponse json: \(response)"); print("reponse string: \(self.dataToString(data))"); } if let params = response["params"] as? NSArray { let error:AnyObject? = response["error"]; if(!(error is NSNull)){ if let error = error as? NSDictionary? { if let error = error { return callback(error: DryApiError.withDictionary(error), args: nil); } } return callback(error: DryApiError("no_code", "object: \(error)"), args: nil); } for key in params { if let key = key as? String { if(key == "error"){ continue; } if let val = response[key] as? NSNull { args.append(nil); }else{ args.append(response[key]); } }else{ return callback(error: DryApiError("malformed_response", "Params contained non string. params: \(params)"), args: nil); } } if(self.debug){ print("processed args: \(args)"); } return callback(error: nil, args: args); }else{ return callback(error: DryApiError("malformed_response", "Response was missing params."), args: nil); } }); } func parse(data: NSData, _ callback: ((error: DryApiError?, response: NSDictionary?)->())){ do { // let result = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue: 0)) as? NSDictionary let result = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? NSDictionary callback(error: nil, response: result); } catch let error as NSError { callback(error: DryApiError.withError(error), response: nil); } // var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError) as? NSDictionary } func dataify(value: AnyObject, _ callback: ((error: DryApiError?, response: NSData?)->())){ do { let data = try NSJSONSerialization.dataWithJSONObject(value, options: NSJSONWritingOptions()) callback(error: nil, response: data); } catch let error as NSError { callback(error: DryApiError.withError(error), response: nil); } } func getValue(dict: [String: AnyObject?], _ key: String) -> AnyObject? { if let x:AnyObject? = dict[key] { return(x); }else{ return(nil); } } func logOutgoingMessage(data: NSData?){ if let data = data { if let str = NSString(data: data, encoding: NSUTF8StringEncoding) { print("outgoingMessage data(string): \(str)"); } } } func callEndpointGetArgs(outgoingMessage: NSDictionary, _ callback: ((error: DryApiError?, args: [AnyObject?]?)->())){ self.dataify(outgoingMessage, { (error, data) in if(error != nil){ return callback(error: error, args: nil); } if(self.debug){ self.logOutgoingMessage(data); } self.postRequest(self._endpoint, data!, { (error, response) in if(error != nil){ return callback(error: error, args: nil); } self.responseToArgs(response, { (error, args) in if(error != nil){ return callback(error: error, args: nil); } else{ callback(error: nil, args: args); } }); }); }); } func badSignatureError(index: Int, _ val: AnyObject?) -> DryApiError{ let error: DryApiError = DryApiError("bad_signature", "Your callback didn't match the request format for arg[\(index)]. value: (\(val))"); return(error); } } public class DryApiClient : DryApiClientBase { func call(methodName: String, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<OA>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<OA, OB>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<OA, OB, OC>(methodName: String, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": [], ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, OA>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0"], "0": inArg0 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1"], "0": inArg0, "1": inArg1 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error); } var args = args!; return callback(error: nil); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } return callback(error: nil, outArg0: args[0] as! OA?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?); }); } func call<IA: NSObject, IB: NSObject, IC: NSObject, OA, OB, OC>(methodName: String, _ inArg0: IA, _ inArg1: IB, _ inArg2: IC, _ callback: ((error: DryApiError?, outArg0: OA?, outArg1: OB?, outArg2: OC?)->())) { var outgoingMessage: NSMutableDictionary = [ "id": NSUUID().UUIDString, "method": methodName, "tags": self.tags(), "params": ["0","1","2"], "0": inArg0, "1": inArg1, "2": inArg2 ]; self.callEndpointGetArgs(outgoingMessage, { (error, args) in if(error != nil){ return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } func errorOut(i: Int, _ e: AnyObject?){ let error = self.badSignatureError(i, e); return callback(error: error, outArg0: nil, outArg1: nil, outArg2: nil); } var args = args!; if(args.count <= 0){ args.append(nil); } if(args[0] != nil && ((args[0] as? OA) == nil)){ return errorOut(0, args[0]); } if(args.count <= 1){ args.append(nil); } if(args[1] != nil && ((args[1] as? OB) == nil)){ return errorOut(1, args[1]); } if(args.count <= 2){ args.append(nil); } if(args[2] != nil && ((args[2] as? OC) == nil)){ return errorOut(2, args[2]); } return callback(error: nil, outArg0: args[0] as! OA?, outArg1: args[1] as! OB?, outArg2: args[2] as! OC?); }); } }
apache-2.0
684799d221e245d55abd138025307365
35.025773
217
0.494312
4.15332
false
false
false
false
mathiasquintero/Sweeft
Sources/Sweeft/UserDefaults/Keychain.swift
1
2553
// // Keychain.swift // Pods // // Created by Mathias Quintero on 4/29/17. // // import Foundation import Security struct Keychain: StorageItem { static let standard = Keychain() func delete(at key: String) { let query: [String : Any] = [ kSecClass as String : kSecClassGenericPassword, kSecAttrService as String : key, ] SecItemDelete(query as CFDictionary) } func set<C>(_ value: C?, forKey defaultName: String) where C : Codable { guard let value = value else { return delete(at: defaultName) } let encoder = PropertyListEncoder() guard let data = try? encoder.encode(value) else { return delete(at: defaultName) } let query: [String : Any] = [ kSecClass as String : kSecClassGenericPassword, kSecAttrService as String : defaultName, ] let dataQuery: [String : Any] = [ kSecAttrService as String : defaultName, kSecValueData as String : data, ] let status = SecItemUpdate(query as CFDictionary, dataQuery as CFDictionary) if status == errSecItemNotFound { let createQuery: [String : Any] = [ kSecClass as String : kSecClassGenericPassword, kSecAttrService as String : defaultName, kSecValueData as String : data, kSecAttrAccessible as String : kSecAttrAccessibleWhenUnlocked, ] SecItemAdd(createQuery as CFDictionary, nil) } } func object<C>(forKey defaultName: String) -> C? where C : Codable { var result: CFTypeRef? let query: [String : Any] = [ kSecClass as String : kSecClassGenericPassword, kSecAttrService as String : defaultName, kSecMatchLimit as String : kSecMatchLimitOne, kSecReturnData as String : kCFBooleanTrue, ] let status = withUnsafeMutablePointer(to: &result) { pointer in return SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer(pointer)) } guard status == errSecSuccess, let data = result as? Data else { return nil } let decoder = PropertyListDecoder() return try? decoder.decode(C.self, from: data) } }
mit
a180644d1731d185a53b116111e1913d
27.685393
92
0.550725
5.776018
false
false
false
false
briancroom/XcodeUITestingExperiments
Swift/SystemLogQuery/LogDumper/LogDumper.swift
1
1851
import Foundation @objc public class LogDumper: NSObject { private static let NotificationKey = "com.briancroom.LogDumper.LogSomeStuff" private static let NotificationAcknowledgementKey = "com.briancroom.LogDumper.Acknowledgement" private static var didReceiveAcknowledgement = false /// Calling this method posts a system-wide notification which will cause any other /// process which links with LogDumper to dump a bunch of internal state into the /// system log public static func sendLogDumpRequest() { didReceiveAcknowledgement = false let center = CFNotificationCenterGetDarwinNotifyCenter() CFNotificationCenterPostNotification(center, NotificationKey, nil, nil, true) } public static func sendLogDumpRequestAndWaitForAcknowledgement() { sendLogDumpRequest() while !didReceiveAcknowledgement { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.1)) } } @objc public static func registerForDumpNotification() { print("** Registering for log dumper notifications") let callBack: CFNotificationCallback = { center, _, name, _, _ in if name as String == LogDumper.NotificationKey { NSLog("** Dumping NSUserDefaults:\n\n%@\n\n", NSUserDefaults.standardUserDefaults().dictionaryRepresentation()) CFNotificationCenterPostNotification(center, LogDumper.NotificationAcknowledgementKey, nil, nil, true) } else { LogDumper.didReceiveAcknowledgement = true } } let center = CFNotificationCenterGetDarwinNotifyCenter() for name in [NotificationKey, NotificationAcknowledgementKey] { CFNotificationCenterAddObserver(center, nil, callBack, name, nil, .DeliverImmediately) } } }
mit
c88894d6e00bd029d86a28cf0bbb650d
41.068182
127
0.703404
5.141667
false
false
false
false
ReticentJohn/Amaroq
Amaroq Push/NotificationService.swift
1
2998
// // NotificationService.swift // Amaroq Push // // Created by John Gabelmann on 2/24/19. // Copyright © 2019 Keyboard Floofs. All rights reserved. // import UserNotifications let MS_CLIENT_NOTIFICATION_STATE_KEY = "MS_CLIENT_NOTIFICATION_STATE_KEY" class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { guard let notificationState = UserDefaults(suiteName: "group.keyboardfloofs.amarok")?.retrieve(object: PushNotificationState.self, fromKey: MS_CLIENT_NOTIFICATION_STATE_KEY), let content = try? bestAttemptContent.decrypt(state: notificationState) else { contentHandler(bestAttemptContent) return } // Modify the notification content here... bestAttemptContent.title = content.title bestAttemptContent.body = content.body bestAttemptContent.badge = 1 bestAttemptContent.sound = UNNotificationSound.default if let strippedTitle = (content.title as NSString).removeHTML() { bestAttemptContent.title = strippedTitle } if let strippedBody = (content.body as NSString).removeHTML() { bestAttemptContent.body = strippedBody } contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } extension UserDefaults { func save<T:Encodable>(customObject object: T, inKey key: String) { let encoder = JSONEncoder() if let encoded = try? encoder.encode(object) { self.set(encoded, forKey: key) } } func retrieve<T:Decodable>(object type:T.Type, fromKey key: String) -> T? { if let data = self.data(forKey: key) { let decoder = JSONDecoder() if let object = try? decoder.decode(type, from: data) { return object }else { print("Couldnt decode object") return nil } }else { print("Couldnt find key") return nil } } }
mpl-2.0
8a65d80bd36ce8e0ddc71200e7f4dfbd
35.54878
265
0.630964
5.370968
false
false
false
false
JGiola/swift-package-manager
Sources/POSIX/stat.swift
2
2566
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import SPMLibc /// File system information for a particular file. public struct FileInfo: Equatable, Codable { /// File timestamp wrapper. public struct FileTimestamp: Equatable, Codable { public let seconds: UInt64 public let nanoseconds: UInt64 } /// File system entity kind. public enum Kind { case file, directory, symlink, blockdev, chardev, socket, unknown fileprivate init(mode: mode_t) { switch mode { case S_IFREG: self = .file case S_IFDIR: self = .directory case S_IFLNK: self = .symlink case S_IFBLK: self = .blockdev case S_IFCHR: self = .chardev case S_IFSOCK: self = .socket default: self = .unknown } } } /// The device number. public let device: UInt64 /// The inode number. public let inode: UInt64 /// The mode flags of the file. public let mode: UInt64 /// The size of the file. public let size: UInt64 /// The modification time of the file. public let modTime: FileTimestamp /// Kind of file system entity. public var kind: Kind { return Kind(mode: mode_t(mode) & S_IFMT) } public init(_ buf: SPMLibc.stat) { self.device = UInt64(buf.st_dev) self.inode = UInt64(buf.st_ino) self.mode = UInt64(buf.st_mode) self.size = UInt64(buf.st_size) #if os(macOS) let seconds = buf.st_mtimespec.tv_sec let nanoseconds = buf.st_mtimespec.tv_nsec #else let seconds = buf.st_mtim.tv_sec let nanoseconds = buf.st_mtim.tv_nsec #endif self.modTime = FileTimestamp( seconds: UInt64(seconds), nanoseconds: UInt64(nanoseconds)) } } public func stat(_ path: String) throws -> SPMLibc.stat { var sbuf = SPMLibc.stat() let rv = stat(path, &sbuf) guard rv == 0 else { throw SystemError.stat(errno, path) } return sbuf } public func lstat(_ path: String) throws -> SPMLibc.stat { var sbuf = SPMLibc.stat() let rv = lstat(path, &sbuf) guard rv == 0 else { throw SystemError.stat(errno, path) } return sbuf }
apache-2.0
53e35d699872f240c4f9ce86e6c0d61e
27.197802
73
0.609509
3.841317
false
false
false
false
JGiola/swift-package-manager
Tests/BasicPerformanceTests/OutputByteStreamPerfTests.swift
2
6670
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic import TestSupport struct ByteSequence: Sequence { let bytes16 = [UInt8](repeating: 0, count: 1 << 4) func makeIterator() -> ByteSequenceIterator { return ByteSequenceIterator(bytes16: bytes16) } } extension ByteSequence: ByteStreamable { func write(to stream: OutputByteStream) { stream.write(sequence: self) } } struct ByteSequenceIterator: IteratorProtocol { let bytes16: [UInt8] var index: Int init(bytes16: [UInt8]) { self.bytes16 = bytes16 index = 0 } mutating func next() -> UInt8? { if index == bytes16.count { return nil } defer { index += 1 } return bytes16[index] } } class OutputByteStreamPerfTests: XCTestCasePerf { func test1MBOfSequence_X10() { let sequence = ByteSequence() measure { for _ in 0..<10 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 16) { stream <<< sequence } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOfByte_X10() { let byte = UInt8(0) measure { for _ in 0..<10 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 20) { stream <<< byte } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOfCharacters_X1() { measure { for _ in 0..<1 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 20) { stream <<< Character("X") } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOf16ByteArrays_X100() { // Test writing 1MB worth of 16 byte strings. let bytes16 = [UInt8](repeating: 0, count: 1 << 4) measure { for _ in 0..<100 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 16) { stream <<< bytes16 } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } // This should give same performance as 16ByteArrays_X100. func test1MBOf16ByteArraySlice_X100() { let bytes32 = [UInt8](repeating: 0, count: 1 << 5) // Test writing 1MB worth of 16 byte strings. let bytes16 = bytes32.suffix(from: bytes32.count/2) measure { for _ in 0..<100 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 16) { stream <<< bytes16 } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOf1KByteArrays_X1000() { // Test writing 1MB worth of 1K byte strings. let bytes1k = [UInt8](repeating: 0, count: 1 << 10) measure { for _ in 0..<1000 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 10) { stream <<< bytes1k } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOf16ByteStrings_X10() { // Test writing 1MB worth of 16 byte strings. let string16 = String(repeating: "X", count: 1 << 4) measure { for _ in 0..<10 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 16) { stream <<< string16 } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOf1KByteStrings_X100() { // Test writing 1MB worth of 1K byte strings. let bytes1k = String(repeating: "X", count: 1 << 10) measure { for _ in 0..<100 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 10) { stream <<< bytes1k } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func test1MBOfJSONEncoded16ByteStrings_X10() { // Test writing 1MB worth of JSON encoded 16 byte strings. let string16 = String(repeating: "X", count: 1 << 4) measure { for _ in 0..<10 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 16) { stream.writeJSONEscaped(string16) } XCTAssertEqual(stream.bytes.count, 1 << 20) } } } func testFormattedJSONOutput() { // Test the writing of JSON formatted output using stream operators. struct Thing { var value: String init(_ value: String) { self.value = value } } let listOfStrings: [String] = (0..<10).map { "This is the number: \($0)!\n" } let listOfThings: [Thing] = listOfStrings.map(Thing.init) measure { for _ in 0..<10 { let stream = BufferedOutputByteStream() for _ in 0..<(1 << 10) { for string in listOfStrings { stream <<< Format.asJSON(string) } stream <<< Format.asJSON(listOfStrings) stream <<< Format.asJSON(listOfThings, transform: { $0.value }) } XCTAssertGreaterThan(stream.bytes.count, 1000) } } } func testJSONToString_X100() { let foo = JSON.dictionary([ "foo": .string("bar"), "bar": .int(2), "baz": .array([1, 2, 3].map(JSON.int)), ]) let bar = JSON.dictionary([ "poo": .array([foo, foo, foo]), "foo": .int(1), ]) let baz = JSON.dictionary([ "poo": .array([foo, bar, foo]), "foo": .int(1), ]) let json = JSON.array((0..<100).map { _ in baz }) measure { for _ in 0..<100 { let result = json.toString() XCTAssertGreaterThan(result.utf8.count, 10) } } } }
apache-2.0
16b9286031b5524e47880aca1ffe6574
28.644444
85
0.482459
4.485541
false
true
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartShowCoordsLinesLayer.swift
1
1856
// // ChartShowCoordsLinesLayer.swift // swift_charts // // Created by ischuetz on 19/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit open class ChartShowCoordsLinesLayer<T: ChartPoint>: ChartPointsLayer<T> { fileprivate var view: UIView? public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T]) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints) } open func showChartPointLines(_ chartPoint: T, chart: Chart) { if let view = self.view { for v in view.subviews { v.removeFromSuperview() } let screenLoc = self.chartPointScreenLoc(chartPoint) let hLine = UIView(frame: CGRect(x: screenLoc.x, y: screenLoc.y, width: 0, height: 1)) let vLine = UIView(frame: CGRect(x: screenLoc.x, y: screenLoc.y, width: 0, height: 1)) for lineView in [hLine, vLine] { lineView.backgroundColor = UIColor.black view.addSubview(lineView) } UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in hLine.frame = CGRect(x: self.innerFrame.origin.x, y: screenLoc.y, width: screenLoc.x - self.innerFrame.origin.x, height: 1) vLine.frame = CGRect(x: screenLoc.x, y: screenLoc.y, width: 1, height: self.innerFrame.origin.y + self.innerFrame.height - screenLoc.y) }, completion: nil) } } override func display(chart: Chart) { let view = UIView(frame: chart.bounds) view.isUserInteractionEnabled = true chart.addSubview(view) self.view = view } }
mit
8d86e1caef37b85bf074968576d17432
35.392157
151
0.601832
4.237443
false
false
false
false
antrix1989/ANShareViewController
Pod/Classes/ANShareViewController.swift
1
4999
// // ANShareViewController.swift // Antsquare // // Created by Sergey Demchenko on 8/8/15. // Copyright (c) 2015 Antsquare Technologies Inc. All rights reserved. // import UIKit import FBSDKShareKit import MessageUI class ANShareViewController: UIViewController, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate, FBSDKSharingDelegate { var viewModel = ANShareViewModel() weak var fromViewController: UIViewController! // MARK: - Public func show() -> Bool { if fromViewController == nil { return false } if viewModel.contentURL == nil { return false } var controller = self.navigationController == nil ? self : self.navigationController! controller.modalPresentationStyle = .OverCurrentContext controller.modalTransitionStyle = .CrossDissolve fromViewController.presentViewController(controller, animated: true, completion: nil) return true } // MARK: - IBAction override func onCloseButtonTapped(sender: AnyObject!) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func onFacebookButtonTapped(sender: AnyObject) { if let contentURL = viewModel.contentURL { var content = FBSDKShareLinkContent() content.contentURL = contentURL var dialog = FBSDKShareDialog() dialog.delegate = self dialog.fromViewController = self dialog.shareContent = content dialog.mode = .ShareSheet; dialog.show() } } @IBAction func onEmailButtonTapped(sender: AnyObject) { if (!MFMailComposeViewController.canSendMail()) { if let title = viewModel.title, let url = viewModel.mailToUrl(title, body: viewModel.messageBody()) { UIApplication.sharedApplication().openURL(url) } return } if let contentURL = viewModel.contentURL { var mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self if let title = viewModel.title { mailComposeViewController.setSubject(title) } mailComposeViewController.setMessageBody(viewModel.messageBody(), isHTML: false) self.presentViewController(mailComposeViewController, animated: true, completion: nil) } } @IBAction func onSmsButtonTapped(sender: AnyObject) { if (!MFMessageComposeViewController.canSendText()) { return } if let contentURL = viewModel.contentURL { var messageComposeViewController = MFMessageComposeViewController() messageComposeViewController.body = viewModel.messageBody() messageComposeViewController.messageComposeDelegate = self self.presentViewController(messageComposeViewController, animated: true, completion: nil) } } @IBAction func onCopyLinkButtonTapped(sender: AnyObject) { if let contentURL = viewModel.contentURL { var myView = view as! ANShareView myView.copyLinkButton.setTitle("Copied", forState: .Normal) var pasteboard = UIPasteboard.generalPasteboard() pasteboard.string = contentURL.absoluteString self.dismissViewControllerAnimated(true, completion: { () -> Void in myView.copyLinkButton.setTitle("Copy Link", forState: .Normal) }) } } // MARK: - FBSDKSharingDelegate func sharer(sharer: FBSDKSharing!, didCompleteWithResults results: [NSObject : AnyObject]!) { self.dismissViewControllerAnimated(true, completion: nil) } func sharer(sharer: FBSDKSharing!, didFailWithError error: NSError!) { if let error = error { UIAlertView(title: nil, message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show() } } func sharerDidCancel(sharer: FBSDKSharing!) { } // MARK: - MFMailComposeViewControllerDelegate func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) { controller.dismissViewControllerAnimated(false, completion: nil) if result.value == MFMailComposeResultSaved.value { self.dismissViewControllerAnimated(true, completion: nil) } } // MARK: - MFMessageComposeViewControllerDelegate func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { controller.dismissViewControllerAnimated(false, completion: nil) if result.value == MessageComposeResultSent.value { self.dismissViewControllerAnimated(true, completion: nil) } } }
mit
dfb995e6471229a2bac90c911fc97365
34.453901
144
0.660932
6.030157
false
false
false
false
Sage-Bionetworks/BridgeAppSDK
BridgeAppSDK/SBAShadowGradient.swift
1
3770
// // SBAShadowGradient.swift // BridgeAppSDK // // Created by Michael L DePhillips on 4/8/17. // // Copyright © 2017 Sage Bionetworks. 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(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // 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 OWNER 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 @IBDesignable open class SBAShadowGradient : UIView { /** * The color of the shadow that is drawn as the background of this */ @IBInspectable var shadowColor : UIColor = UIColor.black { didSet { commonInit() } } /** * The alpha value (0.0 to 1.0) that the bototm part of the gradient will be at */ @IBInspectable var bottomAlpha : CGFloat = CGFloat(0.25) { didSet { commonInit() } } /** * The alpha value (0.0 to 1.0) that the top part of the gradient will be at */ @IBInspectable var topAlpha : CGFloat = CGFloat(0.0) { didSet { commonInit() } } let gradientLayer = CAGradientLayer() public init() { super.init(frame: CGRect.zero) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override open func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = self.bounds } func commonInit() { backgroundColor = UIColor.clear gradientLayer.frame = self.bounds let bottomColor = shadowColor.withAlphaComponent(bottomAlpha).cgColor let topColor = shadowColor.withAlphaComponent(topAlpha).cgColor gradientLayer.colors = [topColor, bottomColor] gradientLayer.locations = [0.0, 1.0] if layer.sublayers?.count ?? 0 == 0 { layer.addSublayer(gradientLayer) } } override open func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) gradientLayer.frame = self.bounds } }
bsd-3-clause
8ce787818bd4279b10c563e5c801003a
32.651786
84
0.671
4.776933
false
false
false
false
exponent/exponent
ios/versioned/sdk43/ExpoModulesCore/Swift/Modules/ModuleDefinition.swift
2
1626
/** A protocol that must be implemented to be a part of module's definition and the module definition itself. */ public protocol AnyDefinition {} /** The definition of the module. It is used to define some parameters of the module and what it exports to the JavaScript world. See `ModuleDefinitionBuilder` for more details on how to create it. */ public struct ModuleDefinition: AnyDefinition { let name: String? let methods: [String : AnyMethod] let constants: [String : Any?] let eventListeners: [EventListener] let viewManager: ViewManagerDefinition? init(definitions: [AnyDefinition]) { self.name = definitions .compactMap { $0 as? ModuleNameDefinition } .last? .name self.methods = definitions .compactMap { $0 as? AnyMethod } .reduce(into: [String : AnyMethod]()) { dict, method in dict[method.name] = method } self.constants = definitions .compactMap { $0 as? ConstantsDefinition } .reduce(into: [String : Any?]()) { dict, definition in dict.merge(definition.constants) { $1 } } self.eventListeners = definitions.compactMap { $0 as? EventListener } self.viewManager = definitions .compactMap { $0 as? ViewManagerDefinition } .last } } /** Module's name definition. Returned by `name()` in module's definition. */ internal struct ModuleNameDefinition: AnyDefinition { let name: String } /** A definition for module's constants. Returned by `constants(() -> SomeType)` in module's definition. */ internal struct ConstantsDefinition: AnyDefinition { let constants: [String : Any?] }
bsd-3-clause
0a6fe5432bbeb674e3eb36eddece2bfd
27.526316
106
0.688192
4.245431
false
false
false
false
grimbolt/BaseSwiftProject
BaseSwiftProject/Sources/Types/Currency.swift
1
2125
import Foundation /// A type that can hold value in PLN. /// /// Example usage: /// // Initializing currency from literal as 6zł 55gr /// let applePrice: Currency = 6.55 /// /// // Oranges cost 1zł 28gr /// let orangePrice = Currency(gr: 128) /// /// // You can multiply it by a scalar, or add them together /// let cost = 3*applePrice + 8*orangePrice /// /// // Prints "29,89 zł" /// print(cost) /// public struct Currency: ExpressibleByFloatLiteral, CustomStringConvertible { public typealias FloatLiteralType = Double public var gr: Int public var zł: Double { get { return Double(self.gr)/100 } set { self.gr = Int((newValue*100).rounded(.toNearestOrAwayFromZero)) } } public init(floatLiteral value: Currency.FloatLiteralType) { self.init(zł: value) } public init(gr: Int) { self.gr = gr } public init?(gr: String) { if let grInt = Int(gr) { self.gr = grInt } else { return nil } } public init(zł: Double) { self.gr = 0 self.zł = zł } public init?(zł: String) { self.gr = 0 if let złDouble = Double(zł) { self.zł = złDouble } else { return nil } } public var stringValue: String { let numberString = String(format:"%.2f", self.zł) .replacingOccurrences(of: ".", with: ",") return numberString+" zł" } public var description: String { return self.stringValue } } public extension Currency { public static func +(lhs: Currency, rhs: Currency) -> Currency { return Currency(gr: lhs.gr+rhs.gr) } static func -(lhs: Currency, rhs: Currency) -> Currency { return Currency(gr: lhs.gr-rhs.gr) } static func *(lhs: Currency, rhs: Double) -> Currency { return Currency(gr: Int(Double(lhs.gr)*rhs)) } static func *(lhs: Double, rhs: Currency) -> Currency { return Currency(gr: Int(lhs*Double(rhs.gr))) } }
mit
3356ddc4237d7c4166d344ab5f666936
22.707865
76
0.558294
3.857404
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Chart.swift
1
29561
// // Chart.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /// ChartSettings allows configuration of the visual layout of a chart public struct ChartSettings { /// Empty space in points added to the leading edge of the chart public var leading: CGFloat = 0 /// Empty space in points added to the top edge of the chart public var top: CGFloat = 0 /// Empty space in points added to the trailing edge of the chart public var trailing: CGFloat = 0 /// Empty space in points added to the bottom edge of the chart public var bottom: CGFloat = 0 /// The spacing in points between axis labels when using multiple labels for each axis value. This is currently only supported with an X axis. public var labelsSpacing: CGFloat = 5 /// The spacing in points between X axis labels and the X axis line public var labelsToAxisSpacingX: CGFloat = 5 /// The spacing in points between Y axis labels and the Y axis line public var labelsToAxisSpacingY: CGFloat = 5 public var spacingBetweenAxesX: CGFloat = 15 public var spacingBetweenAxesY: CGFloat = 15 /// The spacing in points between axis title labels and axis labels public var axisTitleLabelsToLabelsSpacing: CGFloat = 5 /// The stroke width in points of the axis lines public var axisStrokeWidth: CGFloat = 1.0 public var zoomPan = ChartSettingsZoomPan() public var clipInnerFrame = true /// Define a custom clipping rect for chart layers that use containerViewUnclipped to display chart points. // TODO (review): this probably should be moved to ChartPointsViewsLayer public var customClipRect: CGRect? = nil public init() {} } public struct ChartSettingsZoomPan { public var panEnabled = false public var zoomEnabled = false public var minZoomX: CGFloat? public var minZoomY: CGFloat? public var maxZoomX: CGFloat? public var maxZoomY: CGFloat? public var gestureMode: ChartZoomPanGestureMode = .max public var elastic: Bool = false } public enum ChartZoomPanGestureMode { case onlyX // Only X axis is zoomed/panned case onlyY // Only Y axis is zoomed/panned case max // Only axis corresponding to dimension with max zoom/pan delta is zoomed/panned case both // Both axes are zoomed/panned } public protocol ChartDelegate { func onZoom(scaleX: CGFloat, scaleY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, centerX: CGFloat, centerY: CGFloat, isGesture: Bool) func onPan(transX: CGFloat, transY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) func onTap(_ models: [TappedChartPointLayerModels<ChartPoint>]) } /// A Chart object is the highest level access to your chart. It has the view where all of the chart layers are drawn, which you can provide (useful if you want to position it as part of a storyboard or XIB), or it can be created for you. open class Chart: Pannable, Zoomable { /// The view that the chart is drawn in public let view: ChartView public let containerView: UIView public let contentView: UIView public let drawersContentView: UIView public let containerViewUnclipped: UIView /// The layers of the chart that are drawn in the view fileprivate let layers: [ChartLayer] open var delegate: ChartDelegate? open var transX: CGFloat { return contentFrame.minX } open var transY: CGFloat { return contentFrame.minY } open var scaleX: CGFloat { return contentFrame.width / containerFrame.width } open var scaleY: CGFloat { return contentFrame.height / containerFrame.height } open var maxScaleX: CGFloat? { return settings.zoomPan.maxZoomX } open var minScaleX: CGFloat? { return settings.zoomPan.minZoomX } open var maxScaleY: CGFloat? { return settings.zoomPan.maxZoomY } open var minScaleY: CGFloat? { return settings.zoomPan.minZoomY } /// Max possible total pan distance with current transformation open var currentMaxPan: CGFloat { return contentView.frame.height - containerView.frame.height } fileprivate var settings: ChartSettings open var zoomPanSettings: ChartSettingsZoomPan { set { settings.zoomPan = newValue configZoomPan(newValue) } get { return settings.zoomPan } } /** Create a new Chart with a frame and layers. A new ChartBaseView will be created for you. - parameter innerFrame: Frame comprised by axes, where the chart displays content - parameter settings: Chart settings - parameter frame: The frame used for the ChartBaseView - parameter layers: The layers that are drawn in the chart - returns: The new Chart */ convenience public init(frame: CGRect, innerFrame: CGRect? = nil, settings: ChartSettings, layers: [ChartLayer]) { self.init(view: ChartBaseView(frame: frame), innerFrame: innerFrame, settings: settings, layers: layers) } /** Create a new Chart with a view and layers. - parameter innerFrame: Frame comprised by axes, where the chart displays content - parameter settings: Chart settings - parameter view: The view that the chart will be drawn in - parameter layers: The layers that are drawn in the chart - returns: The new Chart */ public init(view: ChartView, innerFrame: CGRect? = nil, settings: ChartSettings, layers: [ChartLayer], enableTouchOnUnclippedContainer: Bool = false) { self.layers = layers self.view = view self.settings = settings let containerView = UIView(frame: innerFrame ?? view.bounds) let drawersContentView = ChartContentView(frame: containerView.bounds) drawersContentView.backgroundColor = UIColor.clear containerView.addSubview(drawersContentView) let contentView = ChartContentView(frame: containerView.bounds) contentView.backgroundColor = UIColor.clear containerView.addSubview(contentView) containerView.clipsToBounds = settings.clipInnerFrame view.addSubview(containerView) // TODO consider moving this view to ChartPointsViewsLayer (together with customClipRect setting) and create it on demand. // then `enableTouchOnUnclippedContainer` can also be removed from `Chart` containerViewUnclipped = UIView(frame: containerView.bounds) view.addSubview(containerViewUnclipped) containerViewUnclipped.isUserInteractionEnabled = enableTouchOnUnclippedContainer if let customClipRect = settings.customClipRect { let shape = CAShapeLayer() shape.path = UIBezierPath(rect: customClipRect).cgPath containerViewUnclipped.layer.mask = shape } self.contentView = contentView self.drawersContentView = drawersContentView self.containerView = containerView contentView.chart = self drawersContentView.chart = self self.view.chart = self for layer in self.layers { layer.chartInitialized(chart: self) } self.view.setNeedsDisplay() #if !os(tvOS) view.initRecognizers(settings) #endif configZoomPan(settings.zoomPan) } fileprivate func configZoomPan(_ settings: ChartSettingsZoomPan) { if settings.minZoomX != nil || settings.minZoomY != nil { zoom(scaleX: settings.minZoomX ?? 1, scaleY: settings.minZoomY ?? 1, anchorX: 0, anchorY: 0) } } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Adds a subview to the chart's content view - parameter view: The subview to add to the chart's content view */ open func addSubview(_ view: UIView) { contentView.addSubview(view) } open func addSubviewNoTransform(_ view: UIView) { containerView.addSubview(view) } open func addSubviewNoTransformUnclipped(_ view: UIView) { containerViewUnclipped.addSubview(view) } /// The frame of the chart's view open var frame: CGRect { return view.frame } var containerFrame: CGRect { return containerView.frame } // Implementation details free variable name & backwards compatibility open var innerFrame: CGRect { return containerFrame } open var contentFrame: CGRect { return contentView.frame } /// The bounds of the chart's view open var bounds: CGRect { return view.bounds } /** Removes the chart's view from its superview */ open func clearView() { view.removeFromSuperview() } open func update() { for layer in layers { layer.update() } self.view.setNeedsDisplay() } func notifyAxisInnerFrameChange(xLow: ChartAxisLayerWithFrameDelta? = nil, yLow: ChartAxisLayerWithFrameDelta? = nil, xHigh: ChartAxisLayerWithFrameDelta? = nil, yHigh: ChartAxisLayerWithFrameDelta? = nil) { for layer in layers { layer.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh) } handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh) } fileprivate func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) { let previousContentFrame = contentView.frame // Resize container view containerView.frame = containerView.frame.insetBy(dx: yLow.deltaDefault0, dy: xHigh.deltaDefault0, dw: yHigh.deltaDefault0, dh: xLow.deltaDefault0) containerViewUnclipped.frame = containerView.frame // Change dimensions of content view by total delta of container view contentView.frame = CGRect(x: contentView.frame.origin.x, y: contentView.frame.origin.y, width: contentView.frame.width - (yLow.deltaDefault0 + yHigh.deltaDefault0), height: contentView.frame.height - (xLow.deltaDefault0 + xHigh.deltaDefault0)) // Scale contents of content view var widthChangeFactor: CGFloat = 0 if previousContentFrame.width.isZero == false { widthChangeFactor = contentView.frame.width / previousContentFrame.width } var heightChangeFactor: CGFloat = 0 if previousContentFrame.height.isZero == false { heightChangeFactor = contentView.frame.height / previousContentFrame.height } let frameBeforeScale = contentView.frame contentView.transform = CGAffineTransform(scaleX: contentView.transform.a * widthChangeFactor, y: contentView.transform.d * heightChangeFactor) contentView.frame = frameBeforeScale } open func onZoomStart(deltaX: CGFloat, deltaY: CGFloat, centerX: CGFloat, centerY: CGFloat) { for layer in layers { layer.zoom(deltaX, y: deltaY, centerX: centerX, centerY: centerY) } } open func onZoomStart(scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) { for layer in layers { layer.zoom(scaleX, scaleY: scaleY, centerX: centerX, centerY: centerY) } } open func onZoomFinish(scaleX: CGFloat, scaleY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, centerX: CGFloat, centerY: CGFloat, isGesture: Bool) { for layer in layers { layer.handleZoomFinish() } delegate?.onZoom(scaleX: scaleX, scaleY: scaleY, deltaX: deltaX, deltaY: deltaY, centerX: centerX, centerY: centerY, isGesture: isGesture) } open func onPanStart(deltaX: CGFloat, deltaY: CGFloat) { for layer in layers { layer.pan(deltaX, deltaY: deltaY) } } open func onPanStart(location: CGPoint) { for layer in layers { layer.handlePanStart(location) } } open func onPanEnd() { for layer in layers { layer.handlePanEnd() } } open func onZoomEnd() { for layer in layers { layer.handleZoomEnd() } } open func onPanFinish(transX: CGFloat, transY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) { for layer in layers { layer.handlePanFinish() } delegate?.onPan(transX: transX, transY: transY, deltaX: deltaX, deltaY: deltaY, isGesture: isGesture, isDeceleration: isDeceleration) } func onTap(_ location: CGPoint) { var models = [TappedChartPointLayerModels<ChartPoint>]() for layer in layers { if let chartPointsLayer = layer as? ChartPointsLayer { if let tappedModels = chartPointsLayer.handleGlobalTap(location) as? TappedChartPointLayerModels<ChartPoint> { models.append(tappedModels) } } else { layer.handleGlobalTap(location) } } delegate?.onTap(models) } open func resetPanZoom() { zoom(scaleX: minScaleX ?? 1, scaleY: minScaleY ?? 1, anchorX: 0, anchorY: 0) // TODO exact numbers. // Chart needs unified functionality to get/set current transform matrix independently of implementation details like contentView or axes transform, which are separate. // Currently the axes and the content view basically manage the transform separately // For more details, see http://stackoverflow.com/questions/41337146/apply-transform-matrix-to-core-graphics-drawing-and-subview pan(deltaX: 10000, deltaY: 10000, isGesture: false, isDeceleration: false, elastic: false) keepInBoundaries() for layer in layers { layer.keepInBoundaries() } } /** Draws the chart's layers in the chart view - parameter rect: The rect that needs to be drawn */ fileprivate func drawRect(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else {return} for layer in self.layers { layer.chartViewDrawing(context: context, chart: self) } } fileprivate func drawContentViewRect(_ rect: CGRect, sender: ChartContentView) { guard let context = UIGraphicsGetCurrentContext() else {return} if sender == drawersContentView { for layer in layers { layer.chartDrawersContentViewDrawing(context: context, chart: self, view: sender) } } else if sender == contentView { for layer in layers { layer.chartContentViewDrawing(context: context, chart: self) } drawersContentView.setNeedsDisplay() } } func allowPan(location: CGPoint, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) -> Bool { var someLayerProcessedPan = false for layer in layers { if layer.processPan(location: location, deltaX: deltaX, deltaY: deltaY, isGesture: isGesture, isDeceleration: isDeceleration) { someLayerProcessedPan = true } } return !someLayerProcessedPan } func allowZoom(deltaX: CGFloat, deltaY: CGFloat, anchorX: CGFloat, anchorY: CGFloat) -> Bool { var someLayerProcessedZoom = false for layer in layers { if layer.processZoom(deltaX: deltaX, deltaY: deltaY, anchorX: anchorX, anchorY: anchorY) { someLayerProcessedZoom = true } } return !someLayerProcessedZoom } } open class ChartContentView: UIView { weak var chart: Chart? override open func draw(_ rect: CGRect) { self.chart?.drawContentViewRect(rect, sender: self) } } /// A UIView subclass for drawing charts open class ChartBaseView: ChartView { override open func draw(_ rect: CGRect) { self.chart?.drawRect(rect) } } open class ChartView: UIView, UIGestureRecognizerDelegate { /// The chart that will be drawn in this view weak var chart: Chart? fileprivate var lastPanTranslation: CGPoint? fileprivate var isPanningX: Bool? // true: x, false: y override public init(frame: CGRect) { super.init(frame: frame) sharedInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInit() } /** Initialization code shared between all initializers */ func sharedInit() { backgroundColor = UIColor.clear } #if !os(tvOS) // MARK: Interactivity fileprivate var pinchRecognizer: UIPinchGestureRecognizer? fileprivate var panRecognizer: UIPanGestureRecognizer? fileprivate var tapRecognizer: UITapGestureRecognizer? func initRecognizers(_ settings: ChartSettings) { if settings.zoomPan.zoomEnabled { let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(ChartView.onPinch(_:))) pinchRecognizer.delegate = self addGestureRecognizer(pinchRecognizer) self.pinchRecognizer = pinchRecognizer } if settings.zoomPan.panEnabled { let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ChartView.onPan(_:))) panRecognizer.delegate = self addGestureRecognizer(panRecognizer) self.panRecognizer = panRecognizer } let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ChartView.onTap(_:))) tapRecognizer.delegate = self tapRecognizer.cancelsTouchesInView = false addGestureRecognizer(tapRecognizer) self.tapRecognizer = tapRecognizer } fileprivate var zoomCenter: CGPoint? @objc func onPinch(_ sender: UIPinchGestureRecognizer) { guard let chartSettings = chart?.settings, chartSettings.zoomPan.zoomEnabled else {return} switch sender.state { case .began: zoomCenter = nil fallthrough case .changed: guard sender.numberOfTouches > 1 else {return} let center = zoomCenter ?? { let center = sender.location(in: self) zoomCenter = center return center }() let x = abs(sender.location(in: self).x - sender.location(ofTouch: 1, in: self).x) let y = abs(sender.location(in: self).y - sender.location(ofTouch: 1, in: self).y) let (deltaX, deltaY): (CGFloat, CGFloat) = { switch chartSettings.zoomPan.gestureMode { case .onlyX: return (sender.scale, 1) case .onlyY: return (1, sender.scale) case .max: return x > y ? (sender.scale, 1) : (1, sender.scale) case .both: // calculate scale x and scale y let (absMax, absMin) = x > y ? (abs(x), abs(y)) : (abs(y), abs(x)) let minScale = (absMin * (sender.scale - 1) / absMax) + 1 return x > y ? (sender.scale, minScale) : (minScale, sender.scale) } }() chart?.zoom(deltaX: deltaX, deltaY: deltaY, centerX: center.x, centerY: center.y, isGesture: true) case .ended: guard let center = zoomCenter, let chart = chart else {print("No center or chart"); return} let adjustBoundsVelocity: CGFloat = 0.2 let minScaleX = chart.settings.zoomPan.minZoomX ?? 1 let minScaleY = chart.settings.zoomPan.minZoomY ?? 1 func outOfBoundsOffsets(_ limit: Bool) -> (x: CGFloat, y: CGFloat) { let scaleX = chart.scaleX var x: CGFloat? if scaleX < minScaleX { x = limit ? min(1 + adjustBoundsVelocity, minScaleX / scaleX) : minScaleX / scaleX } if x == minScaleX { x = nil } let scaleY = chart.scaleY var y: CGFloat? if scaleY < minScaleY { y = limit ? min(1 + adjustBoundsVelocity, minScaleY / scaleY) : minScaleY / scaleY } if y == minScaleY { y = nil } return (x ?? 1, y ?? 1) } func adjustBoundsRec(_ counter: Int) { // FIXME if counter > 400 { let (xOffset, yOffset) = outOfBoundsOffsets(false) chart.zoom(deltaX: xOffset, deltaY: yOffset, centerX: center.x, centerY: center.y, isGesture: true) return } DispatchQueue.main.async { let (xOffset, yOffset) = outOfBoundsOffsets(true) if xOffset != 1 || yOffset != 1 { chart.zoom(deltaX: xOffset, deltaY: yOffset, centerX: center.x, centerY: center.y, isGesture: true) adjustBoundsRec(counter + 1) } } } @discardableResult func adjustBounds() -> Bool { let (xOffset, yOffset) = outOfBoundsOffsets(true) guard (xOffset != 1 || yOffset != 1) else { if chart.scaleX =~ minScaleX || chart.scaleY =~ minScaleY { chart.pan(deltaX: chart.scaleX =~ minScaleY ? -chart.contentView.frame.minX : 0, deltaY: chart.scaleY =~ minScaleY ? -chart.contentView.frame.minY : 0, isGesture: false, isDeceleration: false, elastic: chart.zoomPanSettings.elastic) } return false } adjustBoundsRec(0) return true } if chart.zoomPanSettings.elastic { adjustBounds() } chart.onZoomEnd() case .cancelled: chart?.onZoomEnd() case .failed: fallthrough default: break } sender.scale = 1.0 } @objc func onPan(_ sender: UIPanGestureRecognizer) { guard let chartSettings = chart?.settings , chartSettings.zoomPan.panEnabled else {return} func finalPanDelta(deltaX: CGFloat, deltaY: CGFloat) -> (deltaX: CGFloat, deltaY: CGFloat) { switch chartSettings.zoomPan.gestureMode { case .onlyX: return (deltaX, 0) case .onlyY: return (0, deltaY) case .max: if isPanningX == nil { isPanningX = abs(deltaX) > abs(deltaY) } return isPanningX! ? (deltaX, 0) : (0, deltaY) case .both: return (deltaX, deltaY) } } switch sender.state { case .began: lastPanTranslation = nil isPanningX = nil chart?.onPanStart(location: sender.location(in: self)) case .changed: let trans = sender.translation(in: self) let location = sender.location(in: self) var deltaX = lastPanTranslation.map{trans.x - $0.x} ?? trans.x let deltaY = lastPanTranslation.map{trans.y - $0.y} ?? trans.y var (finalDeltaX, finalDeltaY) = finalPanDelta(deltaX: deltaX, deltaY: deltaY) lastPanTranslation = trans if (chart?.allowPan(location: location, deltaX: finalDeltaX, deltaY: finalDeltaY, isGesture: true, isDeceleration: false)) ?? false { chart?.pan(deltaX: finalDeltaX, deltaY: finalDeltaY, isGesture: true, isDeceleration: false, elastic: chart?.zoomPanSettings.elastic ?? false) } case .ended: guard let view = sender.view, let chart = chart else {print("No view or chart"); return} let velocityX = sender.velocity(in: sender.view).x let velocityY = sender.velocity(in: sender.view).y let (finalDeltaX, finalDeltaY) = finalPanDelta(deltaX: velocityX, deltaY: velocityY) let location = sender.location(in: self) func next(_ velocityX: CGFloat, velocityY: CGFloat) { DispatchQueue.main.async { chart.pan(deltaX: velocityX, deltaY: velocityY, isGesture: true, isDeceleration: true, elastic: chart.zoomPanSettings.elastic) if abs(velocityX) > 0.1 || abs(velocityY) > 0.1 { let friction: CGFloat = 0.9 next(velocityX * friction, velocityY: velocityY * friction) } else { if chart.zoomPanSettings.elastic { adjustBounds() } } } } let adjustBoundsVelocity: CGFloat = 20 func outOfBoundsOffsets(_ limit: Bool) -> (x: CGFloat, y: CGFloat) { var x: CGFloat? if chart.contentView.frame.minX > 0 { x = limit ? max(-adjustBoundsVelocity, -chart.contentView.frame.minX) : -chart.contentView.frame.minX } else { let offset = chart.contentView.frame.maxX - chart.containerView.frame.width if offset < 0 { x = limit ? min(adjustBoundsVelocity, -offset) : -offset } } var y: CGFloat? if chart.contentView.frame.minY > 0 { y = limit ? max(-adjustBoundsVelocity, -chart.contentView.frame.minY) : -chart.contentView.frame.minY } else { let offset = chart.contentView.frame.maxY - chart.containerView.frame.height if offset < 0 { y = limit ? min(adjustBoundsVelocity, -offset) : -offset } } // Drop possile values < epsilon, this causes endless loop since adding them to the view translation apparently is a no-op let roundDecimals: CGFloat = 1000000000 x = x.map{($0 * roundDecimals) / roundDecimals}.flatMap{$0 =~ 0 ? 0 : x} y = y.map{($0 * roundDecimals) / roundDecimals}.flatMap{$0 =~ 0 ? 0 : y} return (x ?? 0, y ?? 0) } func adjustBoundsRec(_ counter: Int) { // FIXME if counter > 400 { let (xOffset, yOffset) = outOfBoundsOffsets(false) chart.pan(deltaX: xOffset, deltaY: yOffset, isGesture: true, isDeceleration: false, elastic: chart.zoomPanSettings.elastic) return } DispatchQueue.main.async { let (xOffset, yOffset) = outOfBoundsOffsets(true) if xOffset != 0 || yOffset != 0 { chart.pan(deltaX: xOffset, deltaY: yOffset, isGesture: true, isDeceleration: false, elastic: chart.zoomPanSettings.elastic) adjustBoundsRec(counter + 1) } } } @discardableResult func adjustBounds() -> Bool { let (xOffset, yOffset) = outOfBoundsOffsets(true) guard (xOffset != 0 || yOffset != 0) else {return false} adjustBoundsRec(0) return true } let initFriction: CGFloat = 50 if (chart.allowPan(location: location, deltaX: finalDeltaX, deltaY: finalDeltaY, isGesture: true, isDeceleration: false)) { if (chart.zoomPanSettings.elastic && !adjustBounds()) || !chart.zoomPanSettings.elastic { next(finalDeltaX / initFriction, velocityY: finalDeltaY / initFriction) } } chart.onPanEnd() case .cancelled, .failed: fallthrough case .possible: // sender.state = UIGestureRecognizerState.Changed fallthrough @unknown default: break } } @objc func onTap(_ sender: UITapGestureRecognizer) { chart?.onTap(sender.location(in: self)) } #endif }
apache-2.0
d275b38ba5e519f7f80916dec77b3e35
35.630731
256
0.58929
4.952421
false
false
false
false
inkCrazy/DouyuLive
GWDouyuLive/GWDouyuLive/Classes/Main/View/PageTitleView.swift
1
5326
// // PageTitleView.swift // GWDouyuLive // // Created by 墨狂之逸才 on 16/10/6. // Copyright © 2016年 墨狂之逸才. All rights reserved. // import UIKit protocol pageTitleViewDelegate: class { func pageTitleView(titleView : PageTitleView, selectedIndex index : Int) } class PageTitleView: UIView { var titles: [String]//这里为什么没有初始化也可以???? var currentIndex: Int = 0 var labelArray: [UILabel] = [UILabel]() weak var delegate: pageTitleViewDelegate? var sourceColor: (CGFloat,CGFloat,CGFloat) = (85,85,85) var selectedColor: (CGFloat,CGFloat,CGFloat) = (255,85,0) lazy var bottomLine: UIView = { let view = UIView() view.backgroundColor = UIColor.grayColor() return view }() lazy var scrollLine: UIView = { let view = UIView() view.backgroundColor = UIColor.orangeColor() return view }() lazy var scrollView: UIScrollView = { let scrollView = UIScrollView.init() scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() init(frame: CGRect,titles: [String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { func setupUI() { scrollView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) addSubview(scrollView) let scrollLineH: CGFloat = 3 let labelY: CGFloat = 0 let labelW: CGFloat = frame.width / CGFloat(titles.count) let labelH: CGFloat = frame.height - scrollLineH - 0.5 for (index,item) in titles.enumerate() { let label = UILabel.init() let labelX: CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) label.textAlignment = .Center label.font = UIFont.systemFontOfSize(16) label.textColor = UIColor.init(r: sourceColor.0, g: sourceColor.1, b: sourceColor.2) label.text = item label.tag = index label.userInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(PageTitleView.labelClick(_:))) label.addGestureRecognizer(tap) scrollView.addSubview(label) labelArray.append(label) } scrollLine.frame = CGRect(x: 0, y: labelH, width: labelW, height: 3) scrollView.addSubview(scrollLine) bottomLine.frame = CGRect(x: 0, y: frame.height - 0.5, width: kScreenW, height: 0.5) addSubview(bottomLine) } @objc private func labelClick(tapGesture: UITapGestureRecognizer) { //设置字体颜色的变化 guard let label = tapGesture.view as? UILabel else {return} label.textColor = UIColor.init(r: selectedColor.0, g: selectedColor.1, b: selectedColor.2) let oldLabel = labelArray[currentIndex] oldLabel.textColor = UIColor.init(r: sourceColor.0, g: sourceColor.1, b: sourceColor.2) currentIndex = label.tag //scrollLine的滚动变化 UIView.animateWithDuration(0.15) { self.scrollLine.frame.origin.x = CGFloat(self.currentIndex) * label.frame.width } delegate?.pageTitleView(self, selectedIndex: currentIndex) } } //MARK: 暴露在外的方法 extension PageTitleView { func setTitleViewWithProgress(progress: CGFloat,sourceIndex: Int,targetIndex: Int) { print("progress:\(progress),sourceIndex:\(sourceIndex),targetIndex:\(targetIndex)") //取出label let sourceLabel = labelArray[sourceIndex] let targetLabel = labelArray[targetIndex] //计算scrollLine滑动的距离 let moveTotal = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveDistance = moveTotal * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveDistance //颜色渐变 let changeColor: (CGFloat,CGFloat,CGFloat) = ((selectedColor.0 - sourceColor.0) * progress,(selectedColor.1 - sourceColor.1) * progress,(selectedColor.2 - sourceColor.2) * progress) sourceLabel.textColor = UIColor.init(r: selectedColor.0 - changeColor.0, g: selectedColor.1 - changeColor.1, b: selectedColor.2 - changeColor.2) targetLabel.textColor = UIColor.init(r: sourceColor.0 + changeColor.0, g: sourceColor.1 + changeColor.1, b: sourceColor.2 + changeColor.2) //原来这么写的,当完全滑到时,我设置sourceIndex == targetIndex,然后启示取出来同一个label,这样颜色就设置两遍了,然后这里就出现问题了。 // targetLabel.textColor = UIColor.init(r: sourceColor.0 + changeColor.0, g: sourceColor.1 + changeColor.1, b: sourceColor.2 + changeColor.2) // sourceLabel.textColor = UIColor.init(r: selectedColor.0 - changeColor.0, g: selectedColor.1 - changeColor.1, b: selectedColor.2 - changeColor.2) currentIndex = targetIndex } }
mit
ea9785d4fb60d3633ce621d6f4b075ae
36.463235
189
0.633759
4.193416
false
false
false
false
nickygerritsen/Timepiece
Timepiece.playground/Contents.swift
2
1154
import Foundation import Timepiece //: ### Add durations to date let now = NSDate() let nextWeek = now + 1.week let dayAfterTomorrow = now + 2.days // shortcuts #1 let today = NSDate.today() let tomorrow = NSDate.tomorrow() let yesterday = NSDate.yesterday() // shortcuts #2 let dayBeforeYesterday = 2.days.ago let tokyoOlympicYear = 5.years.later //: ### Initialize by specifying date components let birthday = NSDate.date(year: 1987, month: 6, day: 2) let firstCommitDate = NSDate.date(year: 2014, month: 8, day: 15, hour: 20, minute: 25, second: 43) //: ### Initialize by changing date components let christmas = now.change(month: 12, day: 25) let thisSunday = now.change(weekday: 1) // shortcuts let newYearDay = now.beginningOfYear let timeLimit = now.endOfHour //: ### Time zone let cst = NSTimeZone(abbreviation: "CST")! let dateInCST = now.beginningOfDay.change(timeZone: cst) dateInCST.timeZone //: ### Format and parse 5.minutes.later.stringFromFormat("yyyy-MM-dd HH:mm:SS") "1987-06-02".dateFromFormat("yyyy-MM-dd") //: ### Compare dates firstCommitDate < 1.year.ago (1.year.ago...now).contains(firstCommitDate) firstCommitDate > now
mit
8a87315a163a4ce5f0371d6226481741
26.47619
98
0.72617
3.297143
false
false
false
false
SoneeJohn/WWDC
WWDC/VideoPlayerViewController.swift
1
11857
// // VideoPlayerViewController.swift // WWDC // // Created by Guilherme Rambo on 04/06/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Cocoa import AVFoundation import PlayerUI import RxSwift import RxCocoa import RealmSwift import RxRealm import ConfCore extension Notification.Name { static let HighlightTranscriptAtCurrentTimecode = Notification.Name("HighlightTranscriptAtCurrentTimecode") } protocol VideoPlayerViewControllerDelegate: class { func createBookmark(at timecode: Double, with snapshot: NSImage?) } final class VideoPlayerViewController: NSViewController { private var disposeBag = DisposeBag() weak var delegate: VideoPlayerViewControllerDelegate? var playbackViewModel: PlaybackViewModel? var sessionViewModel: SessionViewModel { didSet { disposeBag = DisposeBag() updateUI() resetAppearanceDelegate() } } weak var player: AVPlayer! { didSet { reset(oldValue: oldValue) } } var detached = false var playerWillExitPictureInPicture: ((Bool) -> Void)? init(player: AVPlayer, session: SessionViewModel) { sessionViewModel = session self.player = player super.init(nibName: nil, bundle: nil) } required public init?(coder: NSCoder) { fatalError("VideoPlayerViewController can't be initialized with a coder") } lazy var playerView: PUIPlayerView = { return PUIPlayerView(player: self.player) }() fileprivate lazy var progressIndicator: NSProgressIndicator = { let p = NSProgressIndicator(frame: NSZeroRect) p.controlSize = .regular p.style = .spinning p.isIndeterminate = true p.translatesAutoresizingMaskIntoConstraints = false p.appearance = NSAppearance(named: NSAppearance.Name(rawValue: "WhiteSpinner")) p.sizeToFit() return p }() override func loadView() { view = NSView(frame: NSZeroRect) view.wantsLayer = true view.layer?.backgroundColor = NSColor.black.cgColor playerView.translatesAutoresizingMaskIntoConstraints = false playerView.frame = view.bounds view.addSubview(playerView) playerView.registerExternalPlaybackProvider(ChromeCastPlaybackProvider.self) playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true playerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true view.addSubview(progressIndicator) view.addConstraints([ NSLayoutConstraint(item: progressIndicator, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: progressIndicator, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0), ]) progressIndicator.layer?.zPosition = 999 } override func viewDidLoad() { super.viewDidLoad() playerView.delegate = self resetAppearanceDelegate() reset(oldValue: nil) updateUI() NotificationCenter.default.addObserver(self, selector: #selector(annotationSelected(notification:)), name: .TranscriptControllerDidSelectAnnotation, object: nil) NotificationCenter.default.addObserver(forName: .SkipBackAndForwardBy30SecondsPreferenceDidChange, object: nil, queue: OperationQueue.main) { _ in Swift.print("hello there!") self.playerView.invalidateAppearance() } } func resetAppearanceDelegate() { playerView.appearanceDelegate = self } func reset(oldValue: AVPlayer?) { if let oldPlayer = oldValue { if let boundaryObserver = boundaryObserver { oldPlayer.removeTimeObserver(boundaryObserver) self.boundaryObserver = nil } playerView.player = nil oldPlayer.pause() oldPlayer.cancelPendingPrerolls() oldPlayer.removeObserver(self, forKeyPath: #keyPath(AVPlayer.status)) oldPlayer.removeObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.presentationSize)) } player.addObserver(self, forKeyPath: #keyPath(AVPlayer.status), options: [.initial, .new], context: nil) player.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.presentationSize), options: [.initial, .new], context: nil) player.play() progressIndicator.startAnimation(nil) playerView.player = player if let playbackViewModel = playbackViewModel { playerView.remoteMediaUrl = playbackViewModel.remoteMediaURL playerView.mediaTitle = playbackViewModel.title playerView.mediaPosterUrl = playbackViewModel.imageURL playerView.mediaIsLiveStream = playbackViewModel.isLiveStream } setupTranscriptSync() } func updateUI() { let bookmarks = sessionViewModel.session.bookmarks.sorted(byKeyPath: "timecode") Observable.collection(from: bookmarks).observeOn(MainScheduler.instance).subscribe(onNext: { [weak self] bookmarks in self?.playerView.annotations = bookmarks.toArray() }).disposed(by: disposeBag) } @objc private func annotationSelected(notification: Notification) { guard let (transcript, annotation) = notification.object as? (Transcript, TranscriptAnnotation) else { return } guard transcript.identifier == sessionViewModel.session.transcriptIdentifier else { return } let time = CMTimeMakeWithSeconds(annotation.timecode, 90000) player.seek(to: time) } // MARK: - Player Observation override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } if keyPath == #keyPath(AVPlayer.currentItem.presentationSize) { DispatchQueue.main.async(execute: playerItemPresentationSizeDidChange) } else if keyPath == #keyPath(AVPlayer.status) { DispatchQueue.main.async(execute: playerStatusDidChange) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } private func playerItemPresentationSizeDidChange() { guard let size = player.currentItem?.presentationSize, size != NSZeroSize else { return } (view.window as? PUIPlayerWindow)?.aspectRatio = size } private func playerStatusDidChange() { switch player.status { case .readyToPlay, .failed: progressIndicator.stopAnimation(nil) progressIndicator.isHidden = true default: break } } // MARK: - Transcript sync private var boundaryObserver: Any? private func setupTranscriptSync() { guard let player = player else { return } guard let transcript = sessionViewModel.session.transcript() else { return } let timecodes = transcript.timecodesWithTimescale(9000) guard timecodes.count > 0 else { return } boundaryObserver = player.addBoundaryTimeObserver(forTimes: timecodes, queue: DispatchQueue.main) { [unowned self] in guard !transcript.isInvalidated, self.player != nil else { return } let ct = CMTimeGetSeconds(self.player.currentTime()) let roundedTimecode = Transcript.roundedStringFromTimecode(ct) NotificationCenter.default.post(name: .HighlightTranscriptAtCurrentTimecode, object: roundedTimecode) } } // MARK: - Detach var detachedWindowController: VideoPlayerWindowController! func detach(forEnteringFullscreen fullscreen: Bool = false) { view.translatesAutoresizingMaskIntoConstraints = true detachedWindowController = VideoPlayerWindowController(playerViewController: self, fullscreenOnly: fullscreen, originalContainer: view.superview) detachedWindowController.contentViewController = self detachedWindowController.actionOnWindowClosed = { [weak self] in self?.detachedWindowController = nil } detachedWindowController.showWindow(self) detached = true } deinit { #if DEBUG Swift.print("VideoPlayerViewController is gone") #endif player.removeObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.presentationSize)) player.removeObserver(self, forKeyPath: #keyPath(AVPlayer.status)) } } extension VideoPlayerViewController: PUIPlayerViewDelegate { func playerViewDidSelectToggleFullScreen(_ playerView: PUIPlayerView) { if let playerWindow = playerView.window as? PUIPlayerWindow { playerWindow.toggleFullScreen(self) } else { detach(forEnteringFullscreen: true) } } func playerViewDidSelectAddAnnotation(_ playerView: PUIPlayerView, at timestamp: Double) { snapshotPlayer { snapshot in self.delegate?.createBookmark(at: timestamp, with: snapshot) } } private func snapshotPlayer(completion: @escaping (NSImage?) -> Void) { playerView.snapshotPlayer(completion: completion) } func playerViewWillExitPictureInPictureMode(_ playerView: PUIPlayerView, isReturningFromPiP: Bool) { playerWillExitPictureInPicture?(isReturningFromPiP) } func playerViewWillEnterPictureInPictureMode(_ playerView: PUIPlayerView) { } } extension VideoPlayerViewController: PUIPlayerViewAppearanceDelegate { func playerViewShouldShowSubtitlesControl(_ playerView: PUIPlayerView) -> Bool { return true } func playerViewShouldShowPictureInPictureControl(_ playerView: PUIPlayerView) -> Bool { return true } func playerViewShouldShowSpeedControl(_ playerView: PUIPlayerView) -> Bool { return !sessionViewModel.sessionInstance.isCurrentlyLive } func playerViewShouldShowAnnotationControls(_ playerView: PUIPlayerView) -> Bool { return !sessionViewModel.sessionInstance.isCurrentlyLive } func playerViewShouldShowBackAndForwardControls(_ playerView: PUIPlayerView) -> Bool { return !sessionViewModel.sessionInstance.isCurrentlyLive } func playerViewShouldShowExternalPlaybackControls(_ playerView: PUIPlayerView) -> Bool { return true } func playerViewShouldShowFullScreenButton(_ playerView: PUIPlayerView) -> Bool { return true } func playerViewShouldShowTimelineView(_ playerView: PUIPlayerView) -> Bool { return !sessionViewModel.sessionInstance.isCurrentlyLive } func playerViewShouldShowTimestampLabels(_ playerView: PUIPlayerView) -> Bool { return !sessionViewModel.sessionInstance.isCurrentlyLive } func PlayerViewShouldShowBackAndForward30SecondsButtons(_ playerView: PUIPlayerView) -> Bool { return Preferences.shared.skipBackAndForwardBy30Seconds } } extension Transcript { func timecodesWithTimescale(_ timescale: Int32) -> [NSValue] { return annotations.map { annotation -> NSValue in let time = CMTimeMakeWithSeconds(annotation.timecode, timescale) return NSValue(time: time) } } class func roundedStringFromTimecode(_ timecode: Float64) -> String { let formatter = NumberFormatter() formatter.positiveFormat = "0.#" return formatter.string(from: NSNumber(value: timecode)) ?? "0.0" } }
bsd-2-clause
41dd53ba11ecf23fd4ef74427e944608
33.068966
169
0.691464
5.350181
false
false
false
false
Luavis/Kasa
Kasa.swift/LyricWindowController.swift
1
2087
// // LyricWindowController.swift // Kasa.swift // // Created by Luavis Kang on 12/2/15. // Copyright © 2015 Luavis. All rights reserved. // import Cocoa class LyricWindowController: NSWindowController, iTunesConnectionDelegate { static let lyricNotFoundMsg = "가사가 없습니다." var lyrics:Lyrics = Lyrics.empty init() { super.init(window: nil) NSBundle.mainBundle().loadNibNamed("MainWindow", owner: self, topLevelObjects: nil) iTunesConnection.connection.delegate = self iTunesConnection.connection.listen() dispatch_async(dispatch_queue_create("com.luavis.kasa.updater", nil)) { while true { self.iTunesTimer() NSThread.sleepForTimeInterval(NSTimeInterval(0.001)) } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func musicChanged(path: String?) { print(path) let window = self.window as! LyricWindow if let path = path { LyricManager.manager.getLyric(path) { lyrics in if lyrics.isEmpty { self.changeLyrics(Lyrics.empty) window.setLyricText(LyricWindowController.lyricNotFoundMsg) } else { self.changeLyrics(lyrics) } } } else { self.changeLyrics(Lyrics.empty) window.setLyricText(LyricWindowController.lyricNotFoundMsg) } } func changeLyrics(lyrics:Lyrics) { self.lyrics = lyrics } func iTunesTimer() { if self.lyrics.isEmpty { return } let window = self.window as! LyricWindow let position = iTunesConnection.connection.playingPosition let lyric = self.lyrics[position] if let lyric = lyric { window.setLyricText(lyric.lyric) } else { window.setLyricText(LyricWindowController.lyricNotFoundMsg) } } }
mit
8c74ee694da1b434762f5955555dfca6
23.963855
91
0.582046
4.54386
false
false
false
false
lanjing99/iOSByTutorials
iOS Apprentice V4/Tutorial 2 Checklists/Checklists/Checklists/ChecklistsTableViewController.swift
1
6547
// // ChecklistsTableViewController.swift // Checklists // // Created by lanjing on 11/8/15. // Copyright © 2015 lanjing. All rights reserved. // import UIKit class ChecklistsTableViewController: UITableViewController, ItemDetailViewControllerDelegate { var checklist : Checklist? // var items = Array<ChecklistItem>() //MARK: - life cycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let checklist = self.checklist { title = checklist.name } // 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 { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return checklist?.items.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("checklistItem", forIndexPath: indexPath) configCell(cell, forItem: itemAtIndexPath(indexPath)!) 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 checklist!.items.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // 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: - tableview delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath){ let item = itemAtIndexPath(indexPath)! item.checked = !item.checked configCell(cell, forItem: item) } // saveChecklistItem() tableView .deselectRowAtIndexPath(indexPath, animated: 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. if segue.identifier == "addItem" { let navigationController = segue.destinationViewController as! UINavigationController let controller = navigationController.topViewController as! ItemDetailViewController controller.delegate = self }else if segue.identifier == "editItem" { let navigationController = segue.destinationViewController as! UINavigationController let controller = navigationController.topViewController as! ItemDetailViewController controller.delegate = self let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)! let item = itemAtIndexPath(indexPath) controller.itemToEdit = item } } //MARK: - private methods func itemAtIndexPath(indexPath:NSIndexPath) -> ChecklistItem?{ if(indexPath.row < 0 || indexPath.row >= checklist?.items.count){ return nil }else{ return checklist?.items[indexPath.row] } } private func configCell(cell:UITableViewCell, forItem item:ChecklistItem){ cell.accessoryType = .DetailDisclosureButton if let textLabel = cell.viewWithTag(1000) as! UILabel?{ textLabel.text = item.text } let checkLabel = cell.viewWithTag(1001) as! UILabel if item.checked { checkLabel.text = "✅" }else{ checkLabel.text = "" } } //MARK: - ItemDetailViewController Delegae func itemDetailViewController(controller: ItemDetailViewController, didFinishEditingItem item: ChecklistItem) { let index = checklist?.items.indexOf(item) let indexPath = NSIndexPath(forRow: index!, inSection: 0) tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation:.Fade) dismissViewControllerAnimated(true, completion: nil) } func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item: ChecklistItem) { let newRowIndex = checklist!.items.count let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0) let indexPaths = [indexPath] checklist?.items.append(item) tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic) dismissViewControllerAnimated(true, completion: nil) } func itemDetailViewControllerDidCancel(controller: ItemDetailViewController) { dismissViewControllerAnimated(true, completion: nil) } }
mit
e201308b4195586c060048308a61531c
37.269006
157
0.673441
5.685491
false
false
false
false
chrispix/swift-poloniex-portfolio
Sources/poloniex/HoldingsLoader.swift
1
2113
import Foundation public struct HoldingsLoader { public static func loadHoldings(_ keys: APIKeys) -> [Holding] { let session = URLSession(configuration: URLSessionConfiguration.default) let poloniexRequest = PoloniexRequest(params: ["command": "returnCompleteBalances"], keys: keys) let request = poloniexRequest.urlRequest var finished = false var holdings = [Holding]() let holdingsTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in guard let data = data, let responseBody = String(data: data, encoding: .utf8) else { print("couldn't decode data") finished = true return } guard error == nil else { print("error response") finished = true return } guard !responseBody.isEmpty else { print("empty response") finished = true return } do { let dict: [AnyHashable: Any?] = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as! [AnyHashable: Any?] for (key, value) in dict { guard let key = key as? String, let value = value as? [AnyHashable: Any?], let amount = value["available"] as? String, let available = Double(amount), let bitcoinValue = value["btcValue"] as? String, let bits = Double(bitcoinValue), bits > 0 else { continue } let onOrders: Double = { guard let out = value["onOrders"] as? String else { return 0 } return Double(out) ?? 0 }() let holding = Holding(ticker: key, bitcoinValue: bits, availableAmount: available, onOrders: onOrders) holdings.append(holding) } } catch { print("couldn't decode JSON") finished = true return } finished = true }) holdingsTask.resume() while(!finished) {} return holdings } }
mit
da3edfe3f446f26eea8785553204fdfd
32.015625
140
0.563654
4.813212
false
false
false
false
evestorm/SWWeather
SWWeather/SWWeather/Classes/Home/View/SWLaterCollectionViewCell.swift
1
5070
// // SWLaterCollectionViewCell.swift // SWWeather // // Created by Mac on 16/7/31. // Copyright © 2016年 Mac. All rights reserved. // import UIKit class SWLaterCollectionViewCell: UICollectionViewCell { var data:SWWeatherData? { didSet{ dayLabel.text = data?.date numLabel.text = data?.temperature // ?? 用法,如果为true用前面的,false用后面的 let weather = data?.weather ?? "" //print(weather) // // 根据模型找到对应图片 // let needIconName = stringByWeather(weather) let needIconName = stringByWeather(weather) //print(needIconName) iconImgView.image = UIImage(named: needIconName)?.imageWithColor(UIColor.whiteColor()) } } // /** // 根据天气选择图片名称 // // - parameter name: 天气 // // - returns: 返回对应天气图片名称 // */ // func stringByWeather(name:String) -> String { // // 1. 得到传过来的天气信息 // let getName = name // var needIconName = "" // // 2. 对其进行筛选 // switch getName { // case "晴": // needIconName = "weather_sun" // break // case "多云","阴": // needIconName = "weather_cloud" // break // case "阵雨","雷阵雨","雷阵雨伴有冰雹": // needIconName = "weather_hail" // break // case "雨夹雪": // needIconName = "weather_mistyrain" // break // case "小雨": // needIconName = "weather_mistyrain" // break // case "中雨","冻雨","小雨转中雨": // needIconName = "weather_rain" // break // case "大雨","暴雨","大暴雨","特大暴雨","中雨转大雨","大雨转暴雨","暴雨转大暴雨","大暴雨转特大暴雨": // needIconName = "weather_storm-11" // break // case "阵雪","小雪": // needIconName = "weather_cloud_snowflake" // break // case "中雪","小雪转中雪": // needIconName = "weather_snow" // break // case "大雪","暴雪","中雪转大雪","大雪转暴雪": // needIconName = "weather_snowflake" // break // case "雾": // needIconName = "weather_fog" // break // case "沙尘暴","强沙尘暴": // needIconName = "weather_aquarius" // break // case "浮尘","扬沙": // needIconName = "weather_windgust" // break // case "霾": // needIconName = "weather_cancer" // break // default: // if (getName.rangeOfString("雨") != nil) { // needIconName = "weather_rain" // } else if (getName.rangeOfString("云") != nil) { // needIconName = "weather_cloud" // } else if (getName.rangeOfString("雪") != nil) { // needIconName = "weather_snow" // } else { // needIconName = "weather_aries" // } // } // // //let needIconName = "weather_cloud_drop" // return needIconName // } // 自定义cell override init(frame: CGRect) { super.init(frame: frame) // 初始化UI self.setupUI() } func setupUI() { // 1. 添加子控件 contentView.addSubview(dayLabel) contentView.addSubview(iconImgView) contentView.addSubview(numLabel) // 2. 布局子控件 let imgViewWH = contentView.frame.size.width / 3 iconImgView.xmg_AlignInner(type: XMG_AlignType.Center, referView: contentView, size: CGSize(width: imgViewWH, height: imgViewWH)) dayLabel.xmg_AlignVertical(type: XMG_AlignType.TopCenter, referView: iconImgView, size: nil, offset: CGPoint(x: 0, y: -10)) numLabel.xmg_AlignVertical(type: XMG_AlignType.BottomCenter, referView: iconImgView, size: nil, offset: CGPoint(x: 0, y: 10)) } // MARK: - 懒加载 private lazy var dayLabel:UILabel = { let dayLabel = UILabel() dayLabel.text = "周一" dayLabel.textColor = UIColor.whiteColor() dayLabel.font = UIFont.systemFontOfSize(12) return dayLabel }() private lazy var iconImgView:UIImageView = { // 矢量图颜色改变,扩展类 UIImage+Extension let img = UIImage(named: "weather_cloud_lightning")?.imageWithColor(UIColor.whiteColor()) let iconImgView = UIImageView(image: img) return iconImgView }() private lazy var numLabel:UILabel = { let numLabel = UILabel() numLabel.text = "33°/26°" numLabel.textColor = UIColor.whiteColor() numLabel.font = UIFont.systemFontOfSize(12) return numLabel }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4118dd86cdb73d51acbaaa0b246cd06b
31.608392
137
0.53249
3.562261
false
false
false
false
ahoppen/swift
SwiftCompilerSources/Sources/Optimizer/PassManager/Passes.swift
2
1491
//===--- Passes.swift ---- instruction and function passes ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL struct FunctionPass { let name: String let runFunction: (Function, PassContext) -> () public init(name: String, _ runFunction: @escaping (Function, PassContext) -> ()) { self.name = name self.runFunction = runFunction } func run(_ bridgedCtxt: BridgedFunctionPassCtxt) { let function = bridgedCtxt.function.function let context = PassContext(_bridged: bridgedCtxt.passContext) runFunction(function, context) } } struct InstructionPass<InstType: Instruction> { let name: String let runFunction: (InstType, PassContext) -> () public init(name: String, _ runFunction: @escaping (InstType, PassContext) -> ()) { self.name = name self.runFunction = runFunction } func run(_ bridgedCtxt: BridgedInstructionPassCtxt) { let inst = bridgedCtxt.instruction.getAs(InstType.self) let context = PassContext(_bridged: bridgedCtxt.passContext) runFunction(inst, context) } }
apache-2.0
c26c13b7cbf2cba93ab618ac228f9143
29.428571
80
0.652582
4.688679
false
false
false
false
eoger/firefox-ios
Storage/SQL/SQLiteBookmarksBase.swift
5
2451
/* 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 Deferred import Foundation import Shared private let log = Logger.syncLogger class NoSuchSearchKeywordError: MaybeErrorType { let keyword: String init(keyword: String) { self.keyword = keyword } var description: String { return "No such search keyword: \(keyword)." } } open class SQLiteBookmarks: BookmarksModelFactorySource, KeywordSearchSource { let db: BrowserDB let favicons: SQLiteFavicons static let defaultFolderTitle: String = NSLocalizedString("Untitled", tableName: "Storage", comment: "The default name for bookmark folders without titles.") static let defaultItemTitle: String = NSLocalizedString("Untitled", tableName: "Storage", comment: "The default name for bookmark nodes without titles.") open lazy var modelFactory: Deferred<Maybe<BookmarksModelFactory>> = deferMaybe(SQLiteBookmarksModelFactory(bookmarks: self, direction: .local)) public init(db: BrowserDB) { self.db = db self.favicons = SQLiteFavicons(db: self.db) } open func isBookmarked(_ url: String, direction: Direction) -> Deferred<Maybe<Bool>> { let sql = """ SELECT id FROM ( SELECT id FROM \(direction.valueTable) WHERE bmkUri = ? AND is_deleted IS NOT 1 UNION ALL SELECT id FROM bookmarksMirror WHERE bmkUri = ? AND is_deleted IS NOT 1 AND is_overridden IS NOT 1 LIMIT 1 ) """ let args: Args = [url, url] return self.db.queryReturnsResults(sql, args: args) } open func getURLForKeywordSearch(_ keyword: String) -> Deferred<Maybe<String>> { let sql = "SELECT bmkUri FROM view_bookmarksBuffer_on_mirror WHERE keyword = ?" let args: Args = [keyword] return self.db.runQuery(sql, args: args, factory: { $0["bmkUri"] as! String }) >>== { cursor in if cursor.status == .success { if let str = cursor[0] { return deferMaybe(str) } } return deferMaybe(NoSuchSearchKeywordError(keyword: keyword)) } } }
mpl-2.0
6dd844397927532194326759f1c280dc
34.521739
161
0.614443
4.73166
false
false
false
false
hongxinhope/TBRepeatPicker
TBRepeatPicker/TBRPCollectionViewLayout.swift
1
933
// // TBRPCollectionViewLayout.swift // TBRepeatPicker // // Created by hongxin on 15/9/25. // Copyright © 2015年 Teambition. All rights reserved. // import UIKit class TBRPCollectionViewLayout: UICollectionViewFlowLayout { private var mode: TBRPCollectionMode? convenience init(mode: TBRPCollectionMode) { self.init() self.mode = mode if mode == .Days { itemSize = CGSizeMake(TBRPDaysItemWidth, TBRPDaysItemHeight) } else { itemSize = CGSizeMake(TBRPMonthsItemWidth, TBRPMonthsItemHeight) } minimumInteritemSpacing = 0 minimumLineSpacing = 0 } override func collectionViewContentSize() -> CGSize { if mode == .Days { return CGSizeMake(TBRPScreenWidth, TBRPDaysCollectionHeight) } else { return CGSizeMake(TBRPScreenWidth, TBRPMonthsCollectionHeight) } } }
mit
6140bc9b00d4f82bc17632d8fd6b2242
25.571429
76
0.643011
4.325581
false
false
false
false
daniel-barros/TV-Calendar
TraktKit/Common/TraktShowTranslation.swift
1
733
// // TraktShowTranslation.swift // TraktKit // // Created by Maximilian Litteral on 4/13/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct TraktShowTranslation: TraktProtocol { public let title: String public let overview: String public let language: String // Initialize public init?(json: RawJSON?) { guard let json = json, let title = json["title"] as? String, let overview = json["overview"] as? String, let language = json["language"] as? String else { return nil } self.title = title self.overview = overview self.language = language } }
gpl-3.0
d7a681cd9a92d89bfadf1dabfa45e9af
25.142857
74
0.605191
4.463415
false
false
false
false
theisegeberg/BasicJSON
BasicJSON/JSON.swift
1
1027
// // JSON.swift // BasicJSON // // Created by Theis Egeberg on 01/05/2017. // Copyright © 2017 Theis Egeberg. All rights reserved. // import Foundation public enum JSON { case nothing case object(RawJSON) case list([RawJSON]) public static func buildObject<T: JSONObject>(rawJSON: RawJSON) -> T { return T(json:PureJSON(raw: rawJSON)) } public static func buildList<T: JSONObject>(rawJSON: [RawJSON]) -> [T] { return rawJSON.map({ (rawElement) -> T in return T(json:PureJSON(raw: rawElement)) }) } static func purify(raw: RawJSON) -> PureJSONValue { var retDict = [String: JSONRepresentable]() raw.forEach { (key, value) in if let jsonRepresentable = value as? JSONRepresentable { retDict[key] = jsonRepresentable } if let jsonRepresentable = value as? [JSONRepresentable] { retDict[key] = jsonRepresentable } } return retDict } }
mit
e8700c088e2b022e4c5460fc0b00bd11
25.307692
76
0.593567
3.946154
false
false
false
false
freshteapot/learnalist-ios
learnalist-ios/learnalist-ios/MainViewController.swift
1
2459
// // ViewController.swift // learnalist-ios // // Created by Chris Williams on 29/01/2017. // Copyright © 2017 freshteapot. All rights reserved. // import UIKit import SnapKit class MainViewController: UITabBarController, UITabBarControllerDelegate { private var model:LearnalistModel! func getModel() -> LearnalistModel { return model } init(model:LearnalistModel) { super.init(nibName: nil, bundle: nil) self.model = model } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() //Assign self for delegate for that ViewController can respond to UITabBarControllerDelegate methods self.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.edgesForExtendedLayout = [] // Create Tab one let tabMyList = TabMyListViewController() let tabMyListBarItem = UITabBarItem(title: tabMyList.titleToUse, image: UIImage(named: "defaultImage.png"), selectedImage: UIImage(named: "selectedImage.png")) tabMyList.tabBarItem = tabMyListBarItem // Create Tab two let tabPickForAddEditList = TabPickViewController() let tabPickForAddEditListBarItem = UITabBarItem(title: tabPickForAddEditList.titleToUse, image: UIImage(named: "defaultImage2.png"), selectedImage: UIImage(named: "selectedImage2.png")) tabPickForAddEditList.tabBarItem = tabPickForAddEditListBarItem // Create Tab two let tabLastList = TabLastListViewController() let tabLastListBarItem = UITabBarItem(title: "Last List", image: UIImage(named: "defaultImage2.png"), selectedImage: UIImage(named: "selectedImage2.png")) tabLastList.tabBarItem = tabLastListBarItem // Create Tab two let tabSurf = TabSurfViewController() let tabSurfListBarItem = UITabBarItem(title: "Surf", image: UIImage(named: "defaultImage2.png"), selectedImage: UIImage(named: "selectedImage2.png")) tabSurf.tabBarItem = tabSurfListBarItem self.viewControllers = [tabMyList, tabSurf, tabPickForAddEditList] } // UITabBarControllerDelegate method func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { print("Selected \(viewController.title!)") } }
mit
b28526779b9aaa3e8da98189f4a6ad4d
32.671233
193
0.705452
4.602996
false
false
false
false
rnystrom/GitHawk
Classes/Bookmark/BookmarkMigrationCell.swift
1
1772
// // BookmarkMigrationCell.swift // Freetime // // Created by Ryan Nystrom on 11/23/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit protocol BookmarkMigrationCellDelegate: class { func didTapMigrate(for cell: BookmarkMigrationCell) } final class BookmarkMigrationCell: UICollectionViewCell { weak var delegate: BookmarkMigrationCellDelegate? private let label = UILabel() private let button = UIButton() override init(frame: CGRect) { super.init(frame: frame) accessibilityIdentifier = "bookmark-migration-cell" contentView.addSubview(label) contentView.addSubview(button) label.text = NSLocalizedString( "Bookmarks are now stored and synced in iCloud. Tap below migrate.", comment: "" ) label.font = Styles.Text.secondary.preferredFont label.textColor = Styles.Colors.Gray.medium.color label.numberOfLines = 0 button.setTitle(NSLocalizedString("Migrate", comment: ""), for: .normal) button.setTitleColor(Styles.Colors.Blue.medium.color, for: .normal) button.titleLabel?.font = Styles.Text.secondaryBold.preferredFont label.snp.makeConstraints { make in make.centerX.equalToSuperview() make.centerY.equalTo(-Styles.Sizes.tableCellHeightLarge) make.width.lessThanOrEqualToSuperview().offset(-Styles.Sizes.gutter * 2) } button.snp.makeConstraints { make in make.top.equalTo(label.snp.bottom).offset(Styles.Sizes.rowSpacing * 2) make.centerX.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
c69700a20d8c117439720b717b2328e4
30.070175
84
0.67476
4.624021
false
false
false
false
ben-ng/swift
test/Generics/superclass_constraint.swift
5
2701
// RUN: %target-typecheck-verify-swift // RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump class A { func foo() { } } class B : A { func bar() { } } class Other { } func f1<T : A>(_: T) where T : Other {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'A' and 'Other'}} func f2<T : A>(_: T) where T : B {} class GA<T> {} class GB<T> : GA<T> {} protocol P {} func f3<T, U>(_: T, _: U) where U : GA<T> {} func f4<T, U>(_: T, _: U) where U : GA<T> {} func f5<T, U : GA<T>>(_: T, _: U) {} func f6<U : GA<T>, T : P>(_: T, _: U) {} func f7<U, T>(_: T, _: U) where U : GA<T>, T : P {} func f8<T : GA<A>>(_: T) where T : GA<B> {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'GA<A>' and 'GA<B>'}} func f9<T : GA<A>>(_: T) where T : GB<A> {} func f10<T : GB<A>>(_: T) where T : GA<A> {} func f11<T : GA<T>>(_: T) { } // expected-error{{superclass constraint 'GA<T>' is recursive}} func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } // expected-error{{superclass constraint 'GB<T>' is recursive}} func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{inheritance from non-protocol, non-class type 'U'}} // rdar://problem/24730536 // Superclass constraints can be used to resolve nested types to concrete types. protocol P3 { associatedtype T } protocol P2 { associatedtype T : P3 } class C : P3 { typealias T = Int } class S : P2 { typealias T = C } extension P2 where Self.T : C { // CHECK: superclass_constraint.(file).P2.concreteTypeWitnessViaSuperclass1 // CHECK: Generic signature: <Self where Self : P2, Self.T : C> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P2, τ_0_0.T : C> func concreteTypeWitnessViaSuperclass1(x: Self.T.T) {} } // CHECK: superclassConformance1 // CHECK: Requirements: // CHECK-NEXT: T : C [explicit @ // CHECK-NEXT: T : P3 [inherited @ // CHECK-NEXT: T[.P3].T == C.T [redundant] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C> func superclassConformance1<T>(t: T) where T : C, T : P3 {} // CHECK: superclassConformance2 // CHECK: Requirements: // CHECK-NEXT: T : C [explicit @ // CHECK-NEXT: T : P3 [inherited @ // CHECK-NEXT: T[.P3].T == C.T [redundant] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C> func superclassConformance2<T>(t: T) where T : C, T : P3 {} protocol P4 { } class C2 : C, P4 { } // CHECK: superclassConformance3 // CHECK: Requirements: // CHECK-NEXT: T : C2 [explicit @ // CHECK-NEXT: T : P4 [inherited @ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C2> func superclassConformance3<T>(t: T) where T : C, T : P4, T : C2 {}
apache-2.0
ff885071b1da4e437c8d5c57430a1933
28.911111
135
0.609584
2.746939
false
false
false
false
ennioma/arek
code/Classes/Permissions/Location/ArekLocationWhenInUse.swift
1
1975
// // ArekLocationWhenInUse.swift // Arek // // Copyright (c) 2016 Ennio Masi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import CoreLocation final public class ArekLocationWhenInUse: ArekBaseLocation { override public init() { let identifier = "ArekLocationWhenInUse" super.init(identifier: identifier) self.identifier = identifier } public override init(configuration: ArekConfiguration? = nil, initialPopupData: ArekPopupData? = nil, reEnablePopupData: ArekPopupData? = nil) { super.init(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData) self.identifier = "ArekLocationWhenInUse" } override public func askForPermission(completion: @escaping ArekPermissionResponse) { self.completion = completion self.requestWhenInUseAuthorization() } }
mit
776ed7611bee4ae44e7db8a723f8d2a0
41.021277
148
0.736203
4.759036
false
true
false
false
flashspys/FWSlideMenu
FWSlideMenuDemoApp/FWSlideMenuDemoApp/AppDelegate.swift
1
2877
// // AppDelegate.swift // FWSlideOverDemoApp // // Created by Felix Wehnert on 18.01.16. // Copyright © 2016 Felix Wehnert. All rights reserved. // import UIKit import FWSlideMenu @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let story = UIStoryboard(name: "Main", bundle: nil) let vc = story.instantiateInitialViewController() as! SlideMenu let child1 = story.instantiateViewController(withIdentifier: "child1") child1.view.backgroundColor = UIColor.brown let child2 = story.instantiateViewController(withIdentifier: "child2") child2.view.backgroundColor = UIColor.lightGray self.window?.rootViewController = FWSlideMenuController(childs: [child1, child2], slideMenuController: vc) self.window?.rootViewController?.view.backgroundColor = UIColor(patternImage: UIImage(named: "pattern2")!) 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. } 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. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
03f40f553725c40bbab5cd902c401ce3
46.933333
285
0.737483
5.520154
false
false
false
false
sabensm/playgrounds
some-dictonary-stuff.playground/Contents.swift
1
578
//: Playground - noun: a place where people can play import UIKit var webster: [String: String] = ["krill":"any of the small crustceans","fire":"a burning mass of material"] var anotherDictonary: [Int: String] = [44:"my fav number",349:"i hate this number"] if let krill = webster["krill"] { print(krill) } //CLears dictionary webster = [:] if webster.isEmpty { print("Our dictionary is quite the empty!") } var highScores: [String: Int] = ["spentak": 401, "Player1": 200, "Tomtendo": 1] for (user, score) in highScores { print("\(user): \(score)") }
mit
84e9e5a36e4febc24e764c23de811c99
17.0625
107
0.652249
3.15847
false
false
false
false
honishi/Hakumai
Hakumai/Extensions/NSWindow+Extensions.swift
1
1031
// // NSWindowExtension.swift // Hakumai // // Created by Hiroyuki Onishi on 12/15/14. // Copyright (c) 2014 Hiroyuki Onishi. All rights reserved. // import Foundation import AppKit private let windowLevelKeyForNormal: CGWindowLevelKey = .normalWindow private let windowLevelKeyForAlwaysOnTop: CGWindowLevelKey = .floatingWindow extension NSWindow { // http://qiita.com/rryu/items/04af65d772e81d2beb7a var alwaysOnTop: Bool { get { let windowLevel = Int(CGWindowLevelForKey(windowLevelKeyForAlwaysOnTop)) return level.rawValue == windowLevel } set(newAlwaysOnTop) { let windowLevelKey = newAlwaysOnTop ? windowLevelKeyForAlwaysOnTop : windowLevelKeyForNormal let windowLevel = Int(CGWindowLevelForKey(windowLevelKey)) level = NSWindow.Level(rawValue: windowLevel) // `.managed` to keep window being within spaces(mission control) even if special window level collectionBehavior = .managed } } }
mit
3824a2c0c3711881331d86c51eb42bd8
32.258065
106
0.698351
4.52193
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Picker/View/PhotoPickerView+Asset.swift
1
3658
// // PhotoPickerView+Asset.swift // HXPHPicker // // Created by Slience on 2021/9/17. // import UIKit extension PhotoPickerView { /// 重新加载Asset /// 可以通过获取相册集合 manager.fetchAssetCollections() /// - Parameter assetCollection: 相册 public func reloadAsset(assetCollection: PhotoAssetCollection?) { if assetCollection == nil { if config.allowAddCamera { allowPreview = false } }else { if config.allowAddCamera { allowPreview = true } } if AssetManager.authorizationStatus() != .denied { showLoading() } manager.fetchPhotoAssets(assetCollection: assetCollection) } /// 重新加载相机胶卷相册 public func reloadCameraAsset() { if config.allowAddCamera { allowPreview = true } if AssetManager.authorizationStatus() != .denied { showLoading() }else { if config.allowAddCamera { allowPreview = false } } manager.reloadCameraAsset() } /// 获取相机胶卷相册集合里的Asset public func fetchAsset() { manager.requestAuthorization { [weak self] status in guard let self = self else { return } if status == .denied { self.hideLoading() self.setupDeniedView() return } self.manager.reloadAssetCollection = { self.showLoading() } self.showLoading() self.manager.fetchAssets { self.fetchAssetCompletion($0, $1) } } } /// 取消选择 /// - Parameter index: 对应的索引 public func deselect(at index: Int) { updateCellSelectedState(for: index, isSelected: false) } /// 取消选择 /// - Parameter photoAsset: 对应的 PhotoAsset public func deselect(at photoAsset: PhotoAsset) { if let index = getIndexPath(for: photoAsset)?.item { deselect(at: index) } } /// 全部取消选择 public func deselectAll() { manager.deselectAll() collectionView.reloadData() } /// 移除选择的内容 /// 只是移除的manager里的已选数据 /// cell选中状态需要调用 deselectAll() public func removeSelectedAssets() { manager.removeSelectedAssets() } /// 清空 public func clear() { removeSelectedAssets() didFetchAsset = false allowPreview = false isFirst = true assets.removeAll() collectionView.reloadData() emptyView.removeFromSuperview() } private func showLoading() { loadingView = ProgressHUD.showLoading( addedTo: self, afterDelay: 0.15, animated: true ) } private func hideLoading() { loadingView = nil ProgressHUD.hide(forView: self, animated: false) } private func fetchAssetCompletion( _ photoAssets: [PhotoAsset], _ photoAsset: PhotoAsset? ) { resetScrollCell() if isFirst { didFetchAsset = true allowPreview = true isFirst = false } assets = photoAssets setupEmptyView() collectionView.reloadData() scrollToAppropriatePlace(photoAsset: photoAsset) hideLoading() DispatchQueue.main.async { self.scrollViewDidScroll(self.collectionView) } } }
mit
b03f5734c4e1386b53fdb1bf28da1628
25.180451
69
0.551694
5.150888
false
false
false
false
biohazardlover/NintendoEverything
NintendoEverything/Router/Router.swift
1
4427
// // Router.swift // HuaBan-iOS // // Created by Leon Li on 30/12/2017. // Copyright © 2017 Feiguo. All rights reserved. // import UIKit let router = Router.default class Router { typealias URLHandler = (URL, [String : String]) -> Routing static let `default` = Router() private var patterns = [String : URLHandler]() private init() { } func register(pattern: String, handler: @escaping URLHandler) { patterns[pattern] = handler } private func _route(to routingProtocol: RoutingProtocol) { switch routingProtocol.style { case .navigation: navigate(to: routingProtocol.viewController, animated: routingProtocol.animated) case .presentation: present(routingProtocol.viewController, animated: routingProtocol.animated) } } func route(to prerouting: Prerouting) { _route(to: prerouting) } func route(to routing: Routing) { if let prerouting = routing.prerouting { prerouting.handler { self._route(to: routing) } } else { _route(to: routing) } } func route(to url: URL) { for (pattern, handler) in patterns { let regex = try? NSRegularExpression(pattern: pattern, options: []) let range = NSMakeRange(0, url.absoluteString.utf16.count) let matches = regex?.matches(in: url.absoluteString, options: [], range: range) if let count = matches?.count, count > 0 { let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) let sequence = (urlComponents?.queryItems ?? []).map { ($0.name, $0.value ?? "") } let dictionary = Dictionary<String, String>(uniqueKeysWithValues: sequence) route(to: handler(url, dictionary)) } } } } extension Router { var currentViewController: UIViewController? { let rootViewController = UIApplication.shared.keyWindow?.rootViewController var currentViewController = rootViewController while true { switch currentViewController { case let tabBarController as UITabBarController: currentViewController = tabBarController.selectedViewController case let navigationController as UINavigationController: currentViewController = navigationController.visibleViewController case let viewController where viewController?.presentedViewController != nil: currentViewController = viewController?.presentedViewController default: return currentViewController } } } } extension Router { func navigate(to viewController: UIViewController, animated: Bool = true) { currentViewController?.navigationController?.pushViewController(viewController, animated: animated) } func navigateBack(animated: Bool = true) { currentViewController?.navigationController?.popViewController(animated: animated) } func navigateToRoot(animated: Bool = true) { currentViewController?.navigationController?.popToRootViewController(animated: animated) } } extension Router { func canNavigateBackTo<T: UIViewController>(_ viewControllerType: T.Type) -> Bool { let stack = currentViewController?.navigationController?.viewControllers.reversed() ?? [] for viewController in stack where type(of: viewController) === viewControllerType { return true } return false } func navigateBackTo<T: UIViewController>(_ viewControllerType: T.Type, animated: Bool = true) { let stack = currentViewController?.navigationController?.viewControllers.reversed() ?? [] for viewController in stack where type(of: viewController) === viewControllerType { currentViewController?.navigationController?.popToViewController(viewController, animated: animated) return } } } extension Router { func present(_ viewController: UIViewController, animated: Bool = true) { currentViewController?.present(viewController, animated: animated, completion: nil) } func dismiss(animated: Bool = true) { currentViewController?.dismiss(animated: animated, completion: nil) } }
mit
5dbcd01c1e9ccad5aea4745446078ed8
34.693548
112
0.647537
5.326113
false
false
false
false
picmuse/MyHumbleFrame
MyHumbleFrame/MyHumbleFrame.swift
1
1327
// // MyHumbleFrame.swift // MyHumbleFrame // // Created by Dongseop Lim on 29/03/2017. // Copyright © 2017 Dongseop Lim. All rights reserved. // import UIKit extension UIView { public var width: CGFloat { get { return self.frame.size.width } set { self.frame.size.width = newValue } } public var height: CGFloat { get { return self.frame.size.height } set { self.frame.size.height = newValue } } public var top: CGFloat { get { return self.frame.origin.y } set { self.frame.origin.y = newValue } } public var left: CGFloat { get { return self.frame.origin.x } set { self.frame.origin.x = newValue } } public var right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set { self.frame.size.width = newValue - self.frame.origin.x } } public var bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set { self.frame.size.height = newValue - self.frame.origin.y } } }
mit
47950f70796b31ff77c4682f3533a10c
19.4
67
0.489442
4.092593
false
false
false
false
mrchenhao/Cheater
Cheater/Cheater/Stub.swift
1
988
// // StuRequestDSL.swift // Cheater // // Created by ChenHao on 16/3/26. // Copyright © 2016年 HarriesChen. All rights reserved. // import Foundation public class Stub { var request: StubRequest public init(method: String, url: String) { request = StubRequest(method: method, url: url) Cheater.shareInstance.addStubRequest(request) } public func withHeaders(headers: [String: String]) -> Stub { headers.forEach { (key, value) in request.setHeader(key, value: value) } return self } public func addReuren(statusCode: Int) -> Stub { request.response.statusCode = statusCode return self } public func withBody(body: HttpBodyProtocol) -> Stub { request.response.body = body.data return self } public func andFailWithError(error: NSError) -> Stub { request.response.error = error request.response.fail = true return self } }
mit
01459c903173941e746a35409937846c
21.906977
64
0.626396
4.020408
false
false
false
false
xwu/swift
test/SILGen/boxed_existentials.swift
13
12023
// RUN: %target-swift-emit-silgen -module-name boxed_existentials -Xllvm -sil-full-demangle %s | %FileCheck %s // RUN: %target-swift-emit-silgen -module-name boxed_existentials -Xllvm -sil-full-demangle %s | %FileCheck %s --check-prefix=GUARANTEED func test_type_lowering(_ x: Error) { } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@guaranteed Error) -> () { // CHECK-NOT: destroy_value %0 : $Error class Document {} enum ClericalError: Error { case MisplacedDocument(Document) var _domain: String { return "" } var _code: Int { return 0 } } func test_concrete_erasure(_ x: ClericalError) -> Error { return x } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials21test_concrete_erasureys5Error_pAA08ClericalF0OF // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClericalError): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[EXISTENTIAL:%.*]] = alloc_existential_box $Error, $ClericalError // CHECK: [[ADDR:%.*]] = project_existential_box $ClericalError in [[EXISTENTIAL]] : $Error // CHECK: store [[EXISTENTIAL]] to [init] [[EXISTENTIAL_BUF:%.*]] : // CHECK: store [[ARG_COPY]] to [init] [[ADDR]] : $*ClericalError // CHECK-NOT: destroy_value [[ARG]] // CHECK: [[EXISTENTIAL2:%.*]] = load [take] [[EXISTENTIAL_BUF]] // CHECK: return [[EXISTENTIAL2]] : $Error protocol HairType {} func test_composition_erasure(_ x: HairType & Error) -> Error { return x } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials24test_composition_erasureys5Error_psAC_AA8HairTypepF // CHECK: [[VALUE_ADDR:%.*]] = open_existential_addr immutable_access [[OLD_EXISTENTIAL:%.*]] : $*Error & HairType to $*[[VALUE_TYPE:@opened\(.*\) Error & HairType]] // CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error // CHECK: store [[NEW_EXISTENTIAL]] to [init] [[NEW_EXISTENTIALBUF:%.*]] : // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[ADDR]] // CHECK-NOT: destroy_addr [[OLD_EXISTENTIAL]] // CHECK: [[NEW_EXISTENTIAL2:%.*]] = load [take] [[NEW_EXISTENTIALBUF]] // CHECK: return [[NEW_EXISTENTIAL2]] protocol HairClass: class {} func test_class_composition_erasure(_ x: HairClass & Error) -> Error { return x } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials30test_class_composition_erasureys5Error_psAC_AA9HairClasspF // CHECK: [[VALUE:%.*]] = open_existential_ref [[OLD_EXISTENTIAL:%.*]] : $Error & HairClass to $[[VALUE_TYPE:@opened\(.*\) Error & HairClass]] // CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error // CHECK: store [[NEW_EXISTENTIAL]] to [init] [[NEW_EXISTENTIALBUF:%.*]] : // CHECK: [[COPIED_VALUE:%.*]] = copy_value [[VALUE]] // CHECK: store [[COPIED_VALUE]] to [init] [[ADDR]] // CHECK: [[NEW_EXISTENTIAL2:%.*]] = load [take] [[NEW_EXISTENTIALBUF]] // CHECK: return [[NEW_EXISTENTIAL2]] func test_property(_ x: Error) -> String { return x._domain } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials13test_propertyySSs5Error_pF // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: [[VALUE:%.*]] = open_existential_box [[ARG]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]] // FIXME: Extraneous copy here // CHECK-NEXT: [[COPY:%[0-9]+]] = alloc_stack $[[VALUE_TYPE]] // CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[COPY]] : $*[[VALUE_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter // -- self parameter of witness is @in_guaranteed; no need to copy since // value in box is immutable and box is guaranteed // CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]]) // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[RESULT]] func test_property_of_lvalue(_ x: Error) -> String { var x = x return x._domain } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials23test_property_of_lvalueySSs5Error_pF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: [[VAR:%.*]] = alloc_box ${ var Error } // CHECK: [[PVAR:%.*]] = project_box [[VAR]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Error // CHECK: store [[ARG_COPY]] to [init] [[PVAR]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PVAR]] : $*Error // CHECK: [[VALUE_BOX:%.*]] = load [copy] [[ACCESS]] // CHECK: [[BORROWED_VALUE_BOX:%.*]] = begin_borrow [[VALUE_BOX]] // CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_VALUE_BOX]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]] // CHECK: [[COPY:%.*]] = alloc_stack $[[VALUE_TYPE]] // CHECK: copy_addr [[VALUE]] to [initialization] [[COPY]] // CHECK: destroy_value [[VALUE_BOX]] // CHECK: [[BORROW:%.*]] = alloc_stack $[[VALUE_TYPE]] // CHECK: copy_addr [[COPY]] to [initialization] [[BORROW]] // CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter // CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[BORROW]]) // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: destroy_value [[VAR]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '$s18boxed_existentials23test_property_of_lvalueySSs5Error_pF' extension Error { func extensionMethod() { } } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials21test_extension_methodyys5Error_pF func test_extension_method(_ error: Error) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: [[VALUE:%.*]] = open_existential_box [[ARG]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_addr [[COPY]] // CHECK-NOT: destroy_addr [[VALUE]] // CHECK-NOT: destroy_addr [[VALUE]] // -- destroy_value the owned argument // CHECK-NOT: destroy_value %0 error.extensionMethod() } func plusOneError() -> Error { } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF // GUARANTEED-LABEL: sil hidden [ossa] @$s18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF // CHECK: bb0([[ARG0:%.*]]: @guaranteed $Error, // GUARANTEED: bb0([[ARG0:%.*]]: @guaranteed $Error, func test_open_existential_semantics(_ guaranteed: Error, _ immediate: Error) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // GUARANTEED: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // GUARANTEED: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK-NOT: copy_value [[ARG0]] // CHECK: [[VALUE:%.*]] = open_existential_box [[ARG0]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_value [[ARG0]] // GUARANTEED-NOT: copy_value [[ARG0]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[ARG0]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // GUARANTEED-NOT: destroy_value [[ARG0]] guaranteed.extensionMethod() // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // -- need a copy_value to guarantee // CHECK: [[IMMEDIATE_BORROW:%.*]] = begin_borrow [[IMMEDIATE]] // CHECK: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE_BORROW]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // -- end the guarantee // -- TODO: could in theory do this sooner, after the value's been copied // out. // CHECK: destroy_value [[IMMEDIATE]] // GUARANTEED: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error // GUARANTEED: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // -- need a copy_value to guarantee // GUARANTEED: [[BORROWED_IMMEDIATE:%.*]] = begin_borrow [[IMMEDIATE]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[BORROWED_IMMEDIATE]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // -- end the guarantee // GUARANTEED: destroy_value [[IMMEDIATE]] immediate.extensionMethod() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneError // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[PLUS_ONE_BORROW:%.*]] = begin_borrow [[PLUS_ONE]] // CHECK: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE_BORROW]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[PLUS_ONE]] // GUARANTEED: [[F:%.*]] = function_ref {{.*}}plusOneError // GUARANTEED: [[PLUS_ONE:%.*]] = apply [[F]]() // GUARANTEED: [[BORROWED_PLUS_ONE:%.*]] = begin_borrow [[PLUS_ONE]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[BORROWED_PLUS_ONE]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // GUARANTEED: destroy_value [[PLUS_ONE]] plusOneError().extensionMethod() } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials14erasure_to_anyyyps5Error_p_sAC_ptF // CHECK: bb0([[OUT:%.*]] : $*Any, [[GUAR:%.*]] : @guaranteed $Error, func erasure_to_any(_ guaranteed: Error, _ immediate: Error) -> Any { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] if true { // CHECK-NOT: copy_value [[GUAR]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[GUAR:%.*]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK-NOT: destroy_value [[GUAR]] return guaranteed } else if true { // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // CHECK: [[BORROWED_IMMEDIATE:%.*]] = begin_borrow [[IMMEDIATE]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[BORROWED_IMMEDIATE]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK: destroy_value [[IMMEDIATE]] return immediate } else if true { // CHECK: function_ref boxed_existentials.plusOneError // CHECK: [[PLUS_ONE:%.*]] = apply // CHECK: [[BORROWED_PLUS_ONE:%.*]] = begin_borrow [[PLUS_ONE]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[BORROWED_PLUS_ONE]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK: destroy_value [[PLUS_ONE]] return plusOneError() } } extension Error { var myError: Error { return self } } // Make sure we don't assert on this. // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials4testyyF // CHECK: [[ERROR_ADDR:%.*]] = alloc_stack $Error // CHECK: [[ARRAY_GET:%.*]] = function_ref @$sSayxSicig // CHECK: apply [[ARRAY_GET]]<Error>([[ERROR_ADDR]] // CHECK: [[ERROR:%.*]] = load [take] [[ERROR_ADDR]] : $*Error // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: open_existential_box [[BORROWED_ERROR]] func test() { var errors: [Error] = [] test_property(errors[0].myError) }
apache-2.0
00c2ba11094463447c8b95c21a0d31ac
47.092
173
0.595276
3.644438
false
true
false
false
skyylex/HaffmanSwift
Source/Haffman.swift
1
13314
// // HaffmanTree.swift // HaffmanCoding // // Created by Yury Lapitsky on 12/9/15. // Copyright © 2015 skyylex. All rights reserved. // import Foundation /// Phase 1. Get source string and save it /// Phase 2. Parse source string into characters /// Phase 3. Calculate quantity of the each symbols in the text /// Phase 4. Build HaffmanTree /// Phase 5. Create encoding map /// Phase 6. Encode text using created tree // Implementation to work with any binary open class UniversalHaffmanTreeBuilder { public typealias DistributionMap = [Int64 : [UInt8]] public typealias ReverseDistributionMap = [UInt8 : Int64] // No reason to load all data at once, keep work with file directly public let filePath: String // Configuration of the bytes amount to process per read from file public let chunkSize: Int public init(filePath: String, chunkSize: Int = 1024 * 1024) { self.filePath = filePath self.chunkSize = chunkSize } func generateDistribution() -> DistributionMap? { precondition(FileManager.default.fileExists(atPath: self.filePath)) guard let fileStream = InputStream.init(fileAtPath: filePath) else { return nil; } fileStream.open() var reverseMap = Array<Int64>(repeating: 0, count: 256) while fileStream.hasBytesAvailable { var buffer = Array<UInt8>(repeating: 0, count: self.chunkSize) let result = fileStream.read(&buffer, maxLength: buffer.count) switch result { case 0: print("No data to read during distribution calculation") break case (1...Int.max): for byte in buffer { let index = Int(byte) reverseMap[index] = reverseMap[index] + 1 } print("New data was read during distribution calculation") break case -1: print("An error during reading for distribution calculation") print("\(fileStream.streamError)") break default: preconditionFailure() } } fileStream.close() var resultMap = DistributionMap() for index in (0...reverseMap.count - 1) { let symbol = UInt8(index) let quantity = reverseMap[index] if let existingSymbols = resultMap[quantity] as Array<UInt8>? { resultMap[quantity] = existingSymbols + [symbol] } else { resultMap[quantity] = [symbol] } } return resultMap } fileprivate func digitize(_ node: UniversalNode?) { if let aliveNode = node { aliveNode.leftChild?.digit = BitsContainer(bits: [.zero]) aliveNode.rightChild?.digit = BitsContainer(bits: [.one]) digitize(aliveNode.leftChild) digitize(aliveNode.rightChild) } } } typealias SymbolRepresentationInBits = BitsContainer open class UniversalNode { /// Values for building tree open let quantity: Int64 /// Values for the decoding/encoding open let symbol: UInt8 open var digit: BitsContainer? open var leftChild: UniversalNode? open var rightChild: UniversalNode? open var isLeaf: Bool { return self.rightChild == nil && self.leftChild == nil } public init(value: UInt8, quantity: Int64) { self.quantity = quantity self.symbol = value } func join(_ anotherNode: UniversalNode) -> UniversalNode { let parentNodeValue = self.symbol + anotherNode.symbol let parentNodeQuantity = self.quantity + anotherNode.quantity let parentNode = UniversalNode(value: parentNodeValue, quantity: parentNodeQuantity) parentNode.leftChild = (self.quantity <= anotherNode.quantity) ? self : anotherNode parentNode.rightChild = (self.quantity > anotherNode.quantity) ? self : anotherNode return parentNode } } open class UniversalHaffmanTree { open let root: UniversalNode open func description() -> UInt8 { return root.symbol } // open func validate() -> Bool { // var validationResult = true // let decodingMap = generateDecodingMap() // for key1 in decodingMap.keys { // for key2 in decodingMap.keys { // if key1 == key2 { // continue // } else if key1.hasPrefix(key2) == true { // print(key1 + " contains " + key2) // validationResult = false // } // } // } // // return validationResult // } public init(root: UniversalNode) { self.root = root } open func join(_ node: UniversalNode) -> UniversalHaffmanTree { let rootNode = self.root.join(node) return UniversalHaffmanTree(root: rootNode) } func join(_ anotherTree: UniversalHaffmanTree) -> UniversalHaffmanTree { let rootNode = self.root.join(anotherTree.root) return UniversalHaffmanTree(root: rootNode) } public typealias OriginalSymbolBits = BitsContainer public typealias EncodingSymbolBits = BitsContainer open func generateEncodingMap() -> [OriginalSymbolBits : EncodingSymbolBits] { return generateEncodingMap(self.root, sequence: BitsContainer()) } fileprivate func generateEncodingMap(_ node: UniversalNode?, sequence: BitsContainer) -> [OriginalSymbolBits : EncodingSymbolBits] { // TODO: let encodingMap = [OriginalSymbolBits : EncodingSymbolBits]() guard let node = node else { return encodingMap } return encodingMap } } /// ====================================================== // Implementation will work only with String open class HaffmanTreeBuilder { public typealias DistributionMap = [Int : [Character]] public typealias ReverseDistributionMap = [Character : Int] open let text: String public init(text: String) { self.text = text } open func generateDistribution() -> DistributionMap { let distributionMap = self.text.characters.reduce(ReverseDistributionMap()) { current, next -> ReverseDistributionMap in var distributionTable = current if let existingQuantity = distributionTable[next] { distributionTable[next] = existingQuantity + 1 } else { distributionTable[next] = 1 } return distributionTable } let invertedDistributionMap = distributionMap.reduce(DistributionMap()) { currentMap, nextTuple -> DistributionMap in let symbol = nextTuple.0 let quantity = nextTuple.1 var updatedMap = currentMap if let existingSymbols = updatedMap[quantity] as Array<Character>? { updatedMap[quantity] = existingSymbols + [symbol] } else { updatedMap[quantity] = [symbol] } return updatedMap } return invertedDistributionMap } open func buildTree() -> HaffmanTree? { let sortedDistribution = generateDistribution().sorted { $0.0 < $1.0 } let collectedTrees = sortedDistribution.reduce([HaffmanTree]()) { collectedTrees, nextTuple -> [HaffmanTree] in let quantity = nextTuple.0 let symbols = nextTuple.1 let trees = symbols.map { symbol -> HaffmanTree in let node = Node(value: String(symbol), quantity: quantity) return HaffmanTree(root: node) } return collectedTrees + trees } let sortedTrees = collectedTrees.sorted { first, second -> Bool in first.root.quantity < second.root.quantity } let finalTrees = simplify(sortedTrees) precondition(finalTrees.count == 1) let finalTree = finalTrees.first digitize(finalTree?.root) return finalTree } fileprivate func digitize(_ node: Node?) { if let aliveNode = node { aliveNode.leftChild?.digit = 0 aliveNode.rightChild?.digit = 1 digitize(aliveNode.leftChild) digitize(aliveNode.rightChild) } } fileprivate func simplify(_ trees: [HaffmanTree]) -> [HaffmanTree] { /// print(trees.map { $0.root.symbol } ) if trees.count == 1 { return trees } else { let first = trees[0], second = trees[1] let combinedTree = first.join(second) let partedTrees = (trees.count > 2) ? Array(trees[2...(trees.count - 1)]) : [HaffmanTree]() let beforeInsertingTreesAmount = partedTrees.count var insertPosition = 0 for nextTree in partedTrees { if (combinedTree.root.quantity < nextTree.root.quantity) { break } else { insertPosition += 1 } } var updatedTreeGroup = partedTrees updatedTreeGroup.insert(combinedTree, at: insertPosition) let afterInsertingTreesAmount = updatedTreeGroup.count /// If there are no changes combined tree should be placed as the last let finalTreeGroup = (afterInsertingTreesAmount == beforeInsertingTreesAmount) ? updatedTreeGroup + [combinedTree] : updatedTreeGroup return simplify(finalTreeGroup) } } } open class HaffmanTree { open let root: Node open func description() -> String { return root.symbol } open func validate() -> Bool { var validationResult = true let decodingMap = generateDecodingMap() for key1 in decodingMap.keys { for key2 in decodingMap.keys { if key1 == key2 { continue } else if key1.hasPrefix(key2) == true { print(key1 + " contains " + key2) validationResult = false } } } return validationResult } public init(root: Node) { self.root = root } open func join(_ node: Node) -> HaffmanTree { let rootNode = self.root.join(node) return HaffmanTree(root: rootNode) } func join(_ anotherTree: HaffmanTree) -> HaffmanTree { let rootNode = self.root.join(anotherTree.root) return HaffmanTree(root: rootNode) } open func generateDecodingMap() -> [String: Character] { return generateEncodingMap().reduce([String: Character]()) { current, next -> [String: Character] in let symbol = next.0 let string = next.1 return current.join([string : symbol]) } } open func generateEncodingMap() -> [Character: String] { return generateEncodingMap(self.root, digitString: "") } fileprivate func generateEncodingMap(_ node: Node?, digitString: String) -> [Character : String] { let encodingMap = [Character:String]() if let aliveNode = node { var updatedDigitString = digitString if let symbol = aliveNode.symbol.characters.first, let digit = aliveNode.digit { updatedDigitString += String(digit) if aliveNode.isLeaf { return [symbol : updatedDigitString] } } let leftPartResults = generateEncodingMap(aliveNode.leftChild, digitString:updatedDigitString) let rightPartResults = generateEncodingMap(aliveNode.rightChild, digitString:updatedDigitString) let result = encodingMap.join(leftPartResults).join(rightPartResults) return result } return encodingMap } } open class Node { /// Values for building tree open let quantity: Int /// Values for the decoding/encoding open let symbol: String open var digit: Int? open var leftChild: Node? open var rightChild: Node? open var isLeaf: Bool { return self.rightChild == nil && self.leftChild == nil } public init(value: String, quantity: Int) { self.quantity = quantity self.symbol = value } func join(_ anotherNode: Node) -> Node { let parentNodeValue = self.symbol + anotherNode.symbol let parentNodeQuantity = self.quantity + anotherNode.quantity let parentNode = Node(value: parentNodeValue, quantity: parentNodeQuantity) parentNode.leftChild = (self.quantity <= anotherNode.quantity) ? self : anotherNode parentNode.rightChild = (self.quantity > anotherNode.quantity) ? self : anotherNode return parentNode } }
mit
e323935692fd5513f6fe252097d16e0a
32.78934
145
0.58041
4.885505
false
false
false
false
siavashalipour/SAPinViewController
SAPinViewController/Classes/SACircleView.swift
1
5299
// // SACircleView.swift // PINManagement // // Created by Siavash on 21/08/2016. // Copyright © 2016 Siavash Abbasalipour. All rights reserved. // import Foundation import UIKit /// Thanks to https://github.com/MengTo/Spring /// vary simplified version of Spring class SACircleView: UIView { var autostart: Bool = false var autohide: Bool = false var animation: String = "" var force: CGFloat = 1 var delay: CGFloat = 0 var duration: CGFloat = 0.7 var damping: CGFloat = 0.7 var velocity: CGFloat = 0.7 var repeatCount: Float = 1 var x: CGFloat = 0 var y: CGFloat = 0 var scaleX: CGFloat = 1 var scaleY: CGFloat = 1 var rotate: CGFloat = 0 var curve: String = "" var opacity: CGFloat = 1 var animateFrom: Bool = false var circleBorderColor: UIColor! { didSet { layer.borderColor = circleBorderColor.withAlphaComponent(0.8).cgColor } } var isRoundedRect: Bool! { didSet { layer.cornerRadius = (isRoundedRect == true) ? frame.size.width/4.0 : frame.size.width/2.0 } } override init(frame: CGRect) { super.init(frame: frame) circleBorderColor = UIColor.white layer.borderColor = circleBorderColor.withAlphaComponent(0.8).cgColor layer.borderWidth = 1 backgroundColor = UIColor.clear layer.cornerRadius = SAPinConstant.CircleWidth/2.0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func animatePreset() { let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 30*force, -30*force, 30*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1) animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "shake") } func animateTapFull() { UIView.animate(withDuration: 0.17, delay: 0, options: .curveEaseIn, animations: { self.backgroundColor = self.circleBorderColor.withAlphaComponent(0.6) }) { (_) in} } func animateTapEmpty() { UIView.animate(withDuration: 0.17, delay: 0, options: .curveEaseIn, animations: { self.backgroundColor = UIColor.clear }) { (_) in} } func setView(_ completion: @escaping () -> ()) { if animateFrom { let translate = CGAffineTransform(translationX: x, y: y) let scale = CGAffineTransform(scaleX: 1, y: 1) let rotate = CGAffineTransform(rotationAngle: self.rotate) let translateAndScale = translate.concatenating(scale) transform = rotate.concatenating(translateAndScale) alpha = opacity } UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [getAnimationOptions(curve), UIViewAnimationOptions.allowUserInteraction], animations: { [weak self] in if let _self = self { if _self.animateFrom { _self.transform = CGAffineTransform.identity _self.alpha = 1 } else { let translate = CGAffineTransform(translationX: _self.x, y: _self.y) let scale = CGAffineTransform(scaleX: 1, y: 1) let rotate = CGAffineTransform(rotationAngle: _self.rotate) let translateAndScale = translate.concatenating(scale) _self.transform = rotate.concatenating(translateAndScale) _self.alpha = _self.opacity } } }, completion: { [weak self] finished in completion() self?.resetAllForBallView() }) } func getAnimationOptions(_ curve: String) -> UIViewAnimationOptions { return UIViewAnimationOptions.curveLinear } func resetAllForBallView() { x = 0 y = 0 animation = "" opacity = 1 rotate = 0 damping = 0.7 velocity = 0.7 repeatCount = 1 delay = 0 duration = 0.7 } }
mit
185c8068635f6c49b171e6a27cdc79f3
37.671533
119
0.50906
5.395112
false
false
false
false
bestwpw/RxSwift
RxSwift/Disposables/SerialDisposable.swift
2
2228
// // SerialDisposable.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ public class SerialDisposable : DisposeBase, Cancelable { var lock = SpinLock() // state var _current = nil as Disposable? var _disposed = false /** - returns: Was resource disposed. */ public var disposed: Bool { get { return _disposed } } /** Initializes a new instance of the `SerialDisposable`. */ override public init() { super.init() } /** Gets or sets the underlying disposable. Assigning this property disposes the previous disposable object. If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. */ public var disposable: Disposable { get { return self.lock.calculateLocked { return self.disposable } } set (newDisposable) { let disposable: Disposable? = self.lock.calculateLocked { if _disposed { return newDisposable } else { let toDispose = _current _current = newDisposable return toDispose } } if let disposable = disposable { disposable.dispose() } } } /** Disposes the underlying disposable as well as all future replacements. */ public func dispose() { let disposable: Disposable? = self.lock.calculateLocked { if _disposed { return nil } else { _disposed = true return _current } } if let disposable = disposable { disposable.dispose() } } }
mit
27054e307b315bdb55198d8ee89763ae
24.918605
192
0.545332
5.612091
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Renderers/CombinedChartRenderer.swift
2
7211
// // CombinedChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class CombinedChartRenderer: DataRenderer { @objc open weak var chart: CombinedChartView? /// if set to true, all values are drawn above their bars, instead of below their top @objc open var drawValueAboveBarEnabled = true /// if set to true, a grey area is drawn behind each bar that indicates the maximum value @objc open var drawBarShadowEnabled = false internal var _renderers = [DataRenderer]() internal var _drawOrder: [CombinedChartView.DrawOrder] = [.bar, .bubble, .line, .candle, .scatter] @objc public init(chart: CombinedChartView, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart createRenderers() } /// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration. internal func createRenderers() { _renderers = [DataRenderer]() guard let chart = chart else { return } for order in drawOrder { switch (order) { case .bar: if chart.barData !== nil { _renderers.append(BarChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .line: if chart.lineData !== nil { _renderers.append(LineChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .candle: if chart.candleData !== nil { _renderers.append(CandleStickChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .scatter: if chart.scatterData !== nil { _renderers.append(ScatterChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .bubble: if chart.bubbleData !== nil { _renderers.append(BubbleChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break } } } open override func initBuffers() { for renderer in _renderers { renderer.initBuffers() } } open override func drawData(context: CGContext) { // If we redraw the data, remove and repopulate accessible elements to update label values and frames accessibleChartElements.removeAll() if let combinedChart = chart, let data = combinedChart.data { // Make the chart header the first element in the accessible elements array let element = createAccessibleHeader(usingChart: combinedChart, andData: data, withDefaultDescription: "Combined Chart") accessibleChartElements.append(element) } // TODO: Due to the potential complexity of data presented in Combined charts, a more usable way // for VO accessibility would be to use axis based traversal rather than by dataset. // Hence, accessibleChartElements is not populated below. (Individual renderers guard against dataSource being their respective views) for renderer in _renderers { renderer.drawData(context: context) } } open override func drawValues(context: CGContext) { for renderer in _renderers { renderer.drawValues(context: context) } } open override func drawExtras(context: CGContext) { for renderer in _renderers { renderer.drawExtras(context: context) } } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { for renderer in _renderers { var data: ChartData? if renderer is BarChartRenderer { data = (renderer as! BarChartRenderer).dataProvider?.barData } else if renderer is LineChartRenderer { data = (renderer as! LineChartRenderer).dataProvider?.lineData } else if renderer is CandleStickChartRenderer { data = (renderer as! CandleStickChartRenderer).dataProvider?.candleData } else if renderer is ScatterChartRenderer { data = (renderer as! ScatterChartRenderer).dataProvider?.scatterData } else if renderer is BubbleChartRenderer { data = (renderer as! BubbleChartRenderer).dataProvider?.bubbleData } let dataIndex = data == nil ? nil : (chart?.data as? CombinedChartData)?.allData.index(of: data!) let dataIndices = indices.filter{ $0.dataIndex == dataIndex || $0.dataIndex == -1 } renderer.drawHighlighted(context: context, indices: dataIndices) } } /// - returns: The sub-renderer object at the specified index. @objc open func getSubRenderer(index: Int) -> DataRenderer? { if index >= _renderers.count || index < 0 { return nil } else { return _renderers[index] } } /// - returns: All sub-renderers. @objc open var subRenderers: [DataRenderer] { get { return _renderers } set { _renderers = newValue } } // MARK: Accessors /// - returns: `true` if drawing values above bars is enabled, `false` ifnot @objc open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled } /// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot @objc open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. open var drawOrder: [CombinedChartView.DrawOrder] { get { return _drawOrder } set { if newValue.count > 0 { _drawOrder = newValue } } } }
apache-2.0
a1e84c8c54513a6e44300cf572aa2df7
32.384259
142
0.569824
5.581269
false
false
false
false
marcoconti83/targone
Sources/ParsingResult.swift
1
4583
//Copyright (c) Marco Conti 2015 // // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import Foundation // MARK: - Parsing public struct ParsingResult { /// Map from labels to values private let labelsToValues: [String : Any] /// Creates a parsing result from a mapping of argument labels to values. /// Argument labels will be stripped of the flag prefix ("--" or "-") init(labelsToValues: [String : Any]) { var noflagLabelsToValues = [String:Any]() labelsToValues.forEach{ (key, value) in noflagLabelsToValues[key.removeFlagPrefix()] = value } self.labelsToValues = noflagLabelsToValues } /// - returns: the value matching the argument label, only if the value /// is of the type expected from the argument /// - warning: it will abort execution and print an error if value is not of the required type private func value(for argument: CommandLineArgument) -> Any? { guard let value = labelsToValues[argument.label.removeFlagPrefix()] else { return nil } return (type(of: value) == argument.expectedType) ? value : nil } /// - returns: the value parsed for the given flag /// - warning: it will abort execution and print an error if value is not of the required type public func value(_ argument: FlagArgument) -> Bool? { return self.value(for: argument) as? Bool } /// - returns: the value parsed for the given optional argument /// - warning: it will abort execution and print an error if value is not of the required type public func value<Type>(_ argument: OptionalArgument<Type>) -> Type? { return self.value(for: argument) as? Type } /// - returns: the value parsed for the given positional argument /// - warning: it will abort execution and print an error if value is not of the required type public func value<Type>(_ argument: PositionalArgument<Type>) -> Type? { return self.value(for: argument) as? Type } /// - returns: the Bool value for the given label. /// - warning: it will abort execution and print an error if the value is not a Bool public func boolValue(_ label: String) -> Bool? { return (value(label, type: Bool.self) as! Bool?) } /// - returns: the String value for the given label. /// - warning: it will abort execution and print an error if the value is not a String public func stringValue(_ label: String) -> String? { return (value(label, type: String.self) as! String?) } /// - returns: the Int value for the given label. /// - warning: it will abort execution and print an error if the value is not an Int public func intValue(_ label: String) -> Int? { return (value(label, type: Int.self) as! Int?) } /// - returns: a value that is guaranteed to be of the required type if present. /// - warning: it will abort execution and print an error if value is not of the required type public func value(_ label: String, type: Any.Type) -> Any? { if let value = self.value(label) { if Swift.type(of: value) != type { ErrorReporting.die("value for label '\(label)' has actual type '\(Swift.type(of: label))' and not requested type '\(type.self)'") } return value } return nil } /// - returns: the value for the given label if present, or nil public func value(_ label: String) -> Any? { return self.labelsToValues[label] } }
mit
1e3566a0febca2086e80810b2e5ed8a5
43.067308
145
0.669649
4.398273
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/maximum-depth-of-binary-tree.swift
2
1690
/** * https://leetcode.com/problems/maximum-depth-of-binary-tree/ * * */ // Date: Tue May 5 14:15:14 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func maxDepth(_ root: TreeNode?) -> Int { guard let root = root else { return 0 } return 1 + max(maxDepth(root.left), maxDepth(root.right)) } } /** * https://leetcode.com/problems/maximum-depth-of-binary-tree/ * * */ // Date: Tue May 5 14:23:54 PDT 2020 class Solution { /// Non-recursive method by using queue level traverse a tree. /// - Complexity: /// - Time: O(n), n is the number of nodes in the tree /// - Space: O(n/2), n/2 is the number of leaf nodes for a full binary tree. /// func maxDepth(_ root: TreeNode?) -> Int { guard let root = root else { return 0 } var queue = [root] var depth = 0 while !queue.isEmpty { depth += 1 var n = queue.count while n > 0 { n -= 1 let node = queue.removeFirst() if let left = node.left { queue.append(left) } if let right = node.right { queue.append(right) } } } return depth } }
mit
5ddf6a15c381a8946370a0c8937ee010
29.178571
85
0.53432
3.557895
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-fileprivate.swift
1
12138
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z_0-9]+]]LLCySiGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: )*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type* // CHECK-SAME: )*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]] // CHECK-SAME:}> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCySiGMM // CHECK-unknown-SAME: [[INT]] 0, // : %swift.type* bitcast ( // : [[INT]]* getelementptr inbounds ( // : <{ // : void ( // : %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* // : )*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : %swift.method_descriptor // : }>*, // : i8*, // : [[INT]], // : %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* ( // : [[INT]], // : %swift.type* // : )* // : }>, // : <{ // : void ( // : %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* // : )*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : %swift.method_descriptor // : }>*, // : i8*, // : [[INT]], // : %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* ( // : [[INT]], // : %swift.type* // : )* // CHECK-SAME: $s4main9Ancestor1[[UNIQUE_ID_1]]LLCMf // : i32 0, // : i32 2 // : ) to %swift.type* // : ), // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // : i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_1]]5Value to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(32|16)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(136|80)}}, // CHECK-unknown-SAME: i32 112, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : %swift.method_override_descriptor // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn // CHECK-SAME: ), // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfE // CHECK-SAME: [[INT]] {{16|8}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGSi_tcfC // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: [[INT]] {{24|12}} // CHECK-SAME:}>, // CHECK-SAME:align [[ALIGNMENT]] fileprivate class Ancestor1 { let first_Ancestor1: Int init(first: Int) { self.first_Ancestor1 = first } } fileprivate class Value<First> : Ancestor1 { let first_Value: First init(first: First) { self.first_Value = first super.init(first: 32) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } func doit() { consume( Value(first: 13) ) } doit() // CHECK-LABEL: define hidden swiftcc void @"$s4main4doityyF"() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb" // CHECK: } // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCMa" // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} { // CHECK-NEXT: entry: // CHECK: [[SUPERCLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCMa"([[INT]] 0) // CHECK-unknown: ret // CHECK-apple: [[THIS_CLASS_METADATA:%[0-9]+]] = call %objc_class* @objc_opt_self( // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main5Value[[UNIQUE_ID_1]]LLC* // : )*, // : i8**, // : i64, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : i64, // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : void ( // : %T4main5Value[[UNIQUE_ID_1]]LLC* // : )*, // : i64, // : %T4main5Value[[UNIQUE_ID_1]]LLC* ( // : i64, // : %swift.type* // : )*, // : %swift.type*, // : i64, // : %T4main5Value[[UNIQUE_ID_1]]LLC* ( // : %swift.opaque*, // : %swift.type* // : )* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCySiGMf // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[THIS_TYPE_METADATA:%[0-9]+]] = bitcast %objc_class* [[THIS_CLASS_METADATA]] to %swift.type* // CHECK-apple: [[RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[THIS_TYPE_METADATA]], 0 // CHECK-apple: [[COMPLETE_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[COMPLETE_RESPONSE]] // CHECK: }
apache-2.0
f4e1a4bf94fa94d9909af9a705635ac3
38.796721
214
0.334981
3.594314
false
false
false
false
kyouko-taiga/LogicKit
Sources/LogicKit/Realizer.swift
1
7717
/// Base class for realizers. class RealizerBase: IteratorProtocol { public typealias Element = [String: Term] fileprivate init() {} public func next() -> [String: Term]? { fatalError("not implemented") } } /// Realizer that alternatively pulls results from multiple sub-realizers. final class RealizerAlternator: RealizerBase { init<S>(realizers: S) where S: Sequence, S.Element == Realizer { self.realizers = Array(realizers) } private var index = 0 private var realizers: [Realizer] public override func next() -> [String: Term]? { while !realizers.isEmpty { guard let result = realizers[index].next() else { realizers.remove(at: index) if !realizers.isEmpty { index = index % realizers.count } continue } index = (index + 1) % realizers.count return result } return nil } } /// Standard goal realizer. final class Realizer: RealizerBase { init( goals: [Term], knowledge: KnowledgeBase, parentBindings: BindingMap = [:], logger: Logger? = nil) { self.goals = goals self.knowledge = knowledge self.parentBindings = parentBindings self.logger = logger // Identify which part of the knowledge base the realizer should explore. assert(goals.count > 0) switch goals.first! { case ._term(let name, _): clauseIterator = knowledge.predicates[name].map { AnyIterator($0.makeIterator()) } case ._rule(let name, _, _): clauseIterator = knowledge.predicates[name].map { AnyIterator($0.makeIterator()) } default: clauseIterator = AnyIterator(knowledge.literals.makeIterator()) } } /// The goals to realize. private let goals: [Term] /// The knowledge base. private let knowledge: KnowledgeBase /// The bindings already determined by the parent realizer. private let parentBindings: BindingMap /// The optional logger, for debug purpose. private var logger: Logger? /// An iterator on the knowledge clauses to check. private var clauseIterator: AnyIterator<Term>? /// The subrealizer, if any. private var subRealizer: RealizerBase? = nil public override func next() -> [String: Term]? { // If we have a subrealizer running, pull its results first. if let sub = subRealizer { if let result = sub.next() { return result .merged(with: parentBindings) } else { logger?.didBacktrack() subRealizer = nil } } let goal = goals.first! logger?.willRealize(goal: goal) // Check for the built-in `~=~/2` predicate. if case ._term("lk.~=~", let args) = goal { assert(args.count == 2) if let nodeResult = unify(goal: args[0], fact: args[1]) { if goals.count > 1 { let subGoals = goals.dropFirst().map(nodeResult.deepWalk) subRealizer = Realizer( goals: subGoals, knowledge: knowledge, parentBindings: nodeResult, logger: logger) if let branchResult = subRealizer!.next() { return branchResult .merged(with: parentBindings) } } else { return nodeResult .merged(with: parentBindings) } } } // Check for the built-in `native/1` predicate. if case .native(let predicate) = goal { return predicate(parentBindings.reified) ? parentBindings : nil } // Look for the next root clause. while let clause = clauseIterator?.next() { logger?.willAttempt(clause: clause) switch (goal, clause) { case (.val(let lvalue), .val(let rvalue)) where lvalue == rvalue: if goals.count > 1 { let subGoals = Array(goals.dropFirst()) subRealizer = Realizer(goals: subGoals, knowledge: knowledge, logger: logger) if let branchResult = subRealizer!.next() { return branchResult .merged(with: parentBindings) } } case (._term, ._term): if let nodeResult = unify(goal: goal, fact: clause) { if goals.count > 1 { let subGoals = goals.dropFirst().map(nodeResult.deepWalk) subRealizer = Realizer( goals: subGoals, knowledge: knowledge, parentBindings: nodeResult, logger: logger) if let branchResult = subRealizer!.next() { return branchResult .merged(with: parentBindings) } } else { return nodeResult .merged(with: parentBindings) } } case let (._term(goalName, _), ._rule(ruleName, ruleArgs, ruleBody)): assert(goalName == ruleName) // First we try to unify the rule head with the goal. let head: Term = ._term(name: goalName, arguments: ruleArgs) if let nodeResult = unify(goal: goal, fact: head) { let subGoals = goals.dropFirst() .map(nodeResult.deepWalk) let ruleGoals = ruleBody.goals .map({ $0.map(nodeResult.deepWalk) + subGoals }) assert(!ruleGoals.isEmpty) // We have to make sure bound knowledge variables are renamed in the sub-realizer's // knowledge, otherwise they may collide with the ones we already bound. For instance, // consider a recursive rule `p(q($x), $y) ⊢ p($x, q($y))` and a goal `p($z, 0)`. `$z` // would get bound to `q($x)` and `$y` to `0` before we try satisfy `p($x, q(0))`. But // if `$x` wasn't renamed, we'd be trying to unify `$x` with `q($x)` while recursing. let subKnowledge = knowledge.renaming(Set(clause.variables)) let subRealizers = ruleGoals.map { Realizer( goals: $0, knowledge: subKnowledge, parentBindings: nodeResult, logger: logger) } subRealizer = subRealizers.count > 1 ? RealizerAlternator(realizers: subRealizers) : subRealizers[0] if let branchResult = subRealizer!.next() { // Note the `branchResult` already contains the bindings of `nodeResult`, as the these // will have been merged by sub-realizer. return branchResult .merged(with: parentBindings) } } default: break } } return nil } func unify(goal: Term, fact: Term, knowing bindings: BindingMap = [:]) -> BindingMap? { // Shallow-walk the terms to unify. let lhs = bindings.shallowWalk(goal) let rhs = bindings.shallowWalk(fact) // Equal terms always unify. if lhs == rhs { return bindings } switch (lhs, rhs) { case let (.var(name), _): switch bindings[name] { case .none: return bindings.binding(name, to: rhs) case rhs? : return bindings default : return nil } case let (_, .var(name)): switch bindings[name] { case .none: return bindings.binding(name, to: lhs) case lhs? : return bindings default : return nil } case let (.val(lvalue), .val(rvalue)): return lvalue == rvalue ? bindings : nil case let (._term(lname, largs), ._term(rname, rargs)) where lname == rname: // Make sure both terms are of same arity. guard largs.count == rargs.count else { return nil } // Try unify subterms (i.e. arguments). var intermediateResult = bindings for (larg, rarg) in zip(largs, rargs) { if let b = unify(goal: larg, fact: rarg, knowing: intermediateResult) { intermediateResult = b } else { return nil } } // Unification succeeded. return intermediateResult default: return nil } } }
mit
b4c77a40ac1d27fa583cdd8352627820
30.234818
98
0.598704
4.112473
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/tvOS/Presentation Controllers/OptionsPresentationController.swift
1
4585
import Foundation class OptionsPresentationController: UIPresentationController { var containerContentSize = CGSize.zero lazy var dimmingView: UIView = { let view = UIView() view.backgroundColor = .black return view }() func dimmingViewTapped(_ gesture: UIGestureRecognizer) { if gesture.state == .recognized { presentingViewController.dismiss(animated: true) } } override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) { super.preferredContentSizeDidChange(forChildContentContainer: container) containerContentSize = container.preferredContentSize containerViewDidLayoutSubviews() } override func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() dimmingView.frame = containerView!.bounds dimmingView.alpha = 0 containerView?.insertSubview(dimmingView, at: 0) presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] context in self?.dimmingView.alpha = 0.6 }) } override func dismissalTransitionWillBegin() { super.dismissalTransitionWillBegin() presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] context in self?.dimmingView.alpha = 0 }) } override var frameOfPresentedViewInContainerView: CGRect { let screenSize = UIScreen.main.bounds.size if containerContentSize.height < screenSize.height { return CGRect(x: 0, y: 0, width: containerView?.bounds.width ?? containerContentSize.width, height: containerContentSize.height) } return CGRect(origin: CGPoint.zero, size: screenSize) } override func containerViewDidLayoutSubviews() { super.containerViewDidLayoutSubviews() if let bounds = containerView?.bounds { dimmingView.frame = bounds } if presentedView?.frame != frameOfPresentedViewInContainerView { UIView.animate(withDuration: .default) { [unowned self] in self.presentedView?.frame = self.frameOfPresentedViewInContainerView } } } } class OptionsAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning { let isPresenting: Bool init(isPresenting: Bool) { self.isPresenting = isPresenting super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.6 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresenting { animatePresentationWithTransitionContext(transitionContext) } else { animateDismissalWithTransitionContext(transitionContext) } } func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) { guard let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } transitionContext.containerView.addSubview(presentedControllerView) presentedControllerView.frame.origin.y = -presentedControllerView.frame.height UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: { presentedControllerView.frame.origin.y = 0 }, completion: { completed in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) { guard let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { return } UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: { presentedControllerView.frame.origin.y = -presentedControllerView.frame.height }, completion: { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }
gpl-3.0
406ca55ca6fb43da0ec6f1c6f2dc6962
37.855932
197
0.683533
6.503546
false
false
false
false
ethanneff/organize
Organize/Modal+DatePicker.swift
1
3388
// // Modal+DatePicker.swift // Organize // // Created by Ethan Neff on 6/7/16. // Copyright © 2016 Ethan Neff. All rights reserved. // import UIKit class ModalDatePicker: Modal { // MARK: - properties private var header: UILabel! private var topSeparator: UIView! private var midSeparator: UIView! private var yes: UIButton! private var no: UIButton! private var picker: UIDatePicker! private let modalWidth: CGFloat = 290 private let modalHeight: CGFloat = 290 private let modalTitleText: String = "Pick a date" private let pickerMinuteInterval: Int = 5 enum OutputKeys: String { case Date } // MARK: - init override init() { super.init() createViews() createConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init coder not implemented") } // MARK: - deinit deinit { } // MARK: - create private func createViews() { header = createTitle(title: modalTitleText) topSeparator = createSeparator() midSeparator = createSeparator() yes = createButton(title: nil, confirm: true) no = createButton(title: nil, confirm: false) picker = createDatePicker(minuteInterval: pickerMinuteInterval) modal.addSubview(header) modal.addSubview(topSeparator) modal.addSubview(midSeparator) modal.addSubview(yes) modal.addSubview(no) modal.addSubview(picker) yes.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside) no.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside) } private func createConstraints() { constraintHeader(header: header) constraintButtonDoubleBottom(topSeparator: topSeparator, midSeparator: midSeparator, left: no, right: yes) NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: modal, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: modalWidth), NSLayoutConstraint(item: modal, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: modalHeight), NSLayoutConstraint(item: modal, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0), NSLayoutConstraint(item: modal, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0), ]) NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: picker, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: picker, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: picker, attribute: .Top, relatedBy: .Equal, toItem: modal, attribute: .Top, multiplier: 1, constant: Constant.Button.height), NSLayoutConstraint(item: picker, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparator, attribute: .Top, multiplier: 1, constant: 0), ]) } // MARK: - buttons func buttonPressed(button: UIButton) { Util.animateButtonPress(button: button) hide() { if let completion = self.completion where button.tag == 1 { completion(output: [OutputKeys.Date.rawValue: self.picker.date]) } } } }
mit
37a8c26b0fb1b3d770cbf48477548fe4
35.042553
156
0.702687
4.375969
false
false
false
false
garynewby/GLNPianoView
Source/NoteNameLayer.swift
1
1320
// // NoteNameLayer.swift // Example // // Created by Gary Newby on 6/11/19. // import UIKit import QuartzCore public final class NoteNameLayer: CATextLayer { public init(layerHeight: CGFloat, keyRect: CGRect, noteNumber: Int, label: String) { super.init() let width = keyRect.size.width / 2.0 let height = width var yOffset: CGFloat = 20 contentsScale = UIScreen.main.scale string = label foregroundColor = UIColor.white.cgColor if noteNumber.isWhiteKey() { backgroundColor = UIColor.noteColourFor(midiNumber: noteNumber, alpha: 0.75).cgColor cornerRadius = (height * 0.5) yOffset = 10 } font = UIFont.boldSystemFont(ofSize: 0.0) fontSize = (keyRect.size.width / 4.0) alignmentMode = .center frame = CGRect(x: (keyRect.size.width * 0.25), y: (layerHeight - height - yOffset), width: width, height: height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func draw(in ctx: CGContext) { ctx.saveGState() ctx.translateBy(x: 0.0, y: (bounds.size.height - fontSize) / 2.0 - fontSize / 10.0) super.draw(in: ctx) ctx.restoreGState() } }
mit
e5c537ba84a4b848ab5b22d8a09dd50d
28.333333
121
0.611364
3.928571
false
false
false
false
queueit/QueueIT.iOS.Sdk
QueueItSDK/StatusDTO.swift
1
527
import Foundation class StatusDTO { var eventDetails: EventDTO? var redirectDto: RedirectDTO? var widgets: [WidgetDTO]? var nextCallMSec: Int var rejectDto: RejectDTO? init(_ eventDetails: EventDTO?, _ redirectDto: RedirectDTO?, _ widgets: [WidgetDTO]?, _ nextCallMSec: Int, _ rejectDto: RejectDTO?) { self.eventDetails = eventDetails self.redirectDto = redirectDto self.widgets = widgets self.nextCallMSec = nextCallMSec self.rejectDto = rejectDto } }
lgpl-3.0
6385ddd13083ea6a4bcb5cfb63da2f6a
30
137
0.669829
3.711268
false
false
false
false
xuzhuoxi/SearchKit
Source/code/math/MathUtils.swift
1
3128
// // MathUtils.swift // SearchKit // // Created by 许灼溪 on 15/12/17. // // /** * 一些常用的数学方法 * * @author xuzhuoxi * */ public struct MathUtils { fileprivate init(){} /** * 计算从个数为m的有序数组中取得n个元素所构成的组合的个数<br> * 组合行为基于数组顺序 * * @param m * 数据数量 * @param n * 选择个数 * @return 组合个数 */ public static func getCombinationCount(_ m:Int, _ n:Int) ->Int{ var getLen: Int = 0 var fenzi: Int = m var fenmu: Int = 1 for i in 1..<n { let temp = m fenzi = fenzi * (temp - i) let demp = 1 fenmu = fenmu * (demp + i) } getLen = fenzi / fenmu return getLen } /** * 十进制转换不确定进制 * * @param value * 十进制数值 * @param system * 不确定进制数组 * @return 由十进制数据组成的数组 */ public static func tenToCustomSystem(_ value:Int, _ system:[Int]) ->[Int] { var rs = Array<Int>(repeating: 0, count: system.count) var temp = value for i in 0..<system.count { rs[i] = temp%system[i] temp = temp/system[i] } return rs } /** * 从sourceLen个源数据中最多选择dimension个元素进行组合,组合过程基于源数据的顺序<br> * * @param sourceLen * 源数据个数 * @param dimension * 最多可选择个数 * @return 全部组合的索引情况 */ public static func getDimensionCombinationIndex(_ sourceLen:Int, dimension:Int) ->[[[Int]]]? { let newDimension = sourceLen<dimension ? sourceLen : dimension if newDimension<1 { return nil } if 1==newDimension { var result = [[[Int]]](repeating: [[Int]](), count: 1) for i in 0..<sourceLen { result[0].append([i]) } return result } var rs = [[[Int]]](repeating: [[Int]](), count: newDimension) for i in 0..<sourceLen { for j in (0...(newDimension-2)).reversed() { if rs[j].count > 0 { for indexs in rs[j] { var add = indexs add.append(i) rs[j+1].append(add) } } if 0 == j { rs[0].append([i]) } } } for i in 0..<rs.count { rs[i].sort(by: intArrayComparable) } return rs; } fileprivate static func intArrayComparable(_ o1:[Int], o2:[Int]) ->Bool { if o1.count != o2.count { return o1.count < o2.count }else{ for i in 0..<o1.count { if o1[i] != o2[i] { return o1[i] < o2[i] } } return false } } }
mit
95ae86b5ff65d5e41d315d1d48341d0c
23.912281
98
0.434859
3.655084
false
false
false
false
apple/swift-log
Tests/LoggingTests/LoggingTest.swift
1
37335
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Logging API open source project // // Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Swift Logging API project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// @testable import Logging import XCTest #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #elseif os(Windows) import WinSDK #else import Glibc #endif class LoggingTest: XCTestCase { func testAutoclosure() throws { // bootstrap with our test logging impl let logging = TestLogging() LoggingSystem.bootstrapInternal(logging.make) var logger = Logger(label: "test") logger.logLevel = .info logger.log(level: .debug, { XCTFail("debug should not be called") return "debug" }()) logger.trace({ XCTFail("trace should not be called") return "trace" }()) logger.debug({ XCTFail("debug should not be called") return "debug" }()) logger.info({ "info" }()) logger.warning({ "warning" }()) logger.error({ "error" }()) XCTAssertEqual(3, logging.history.entries.count, "expected number of entries to match") logging.history.assertNotExist(level: .debug, message: "trace") logging.history.assertNotExist(level: .debug, message: "debug") logging.history.assertExist(level: .info, message: "info") logging.history.assertExist(level: .warning, message: "warning") logging.history.assertExist(level: .error, message: "error") } func testMultiplex() throws { // bootstrap with our test logging impl let logging1 = TestLogging() let logging2 = TestLogging() LoggingSystem.bootstrapInternal { MultiplexLogHandler([logging1.make(label: $0), logging2.make(label: $0)]) } var logger = Logger(label: "test") logger.logLevel = .warning logger.info("hello world?") logger[metadataKey: "foo"] = "bar" logger.warning("hello world!") logging1.history.assertNotExist(level: .info, message: "hello world?") logging2.history.assertNotExist(level: .info, message: "hello world?") logging1.history.assertExist(level: .warning, message: "hello world!", metadata: ["foo": "bar"]) logging2.history.assertExist(level: .warning, message: "hello world!", metadata: ["foo": "bar"]) } func testMultiplexLogHandlerWithVariousLogLevels() throws { let logging1 = TestLogging() let logging2 = TestLogging() var logger1 = logging1.make(label: "1") logger1.logLevel = .info var logger2 = logging2.make(label: "2") logger2.logLevel = .debug LoggingSystem.bootstrapInternal { _ in MultiplexLogHandler([logger1, logger2]) } let multiplexLogger = Logger(label: "test") multiplexLogger.trace("trace") multiplexLogger.debug("debug") multiplexLogger.info("info") multiplexLogger.warning("warning") logging1.history.assertNotExist(level: .trace, message: "trace") logging1.history.assertNotExist(level: .debug, message: "debug") logging1.history.assertExist(level: .info, message: "info") logging1.history.assertExist(level: .warning, message: "warning") logging2.history.assertNotExist(level: .trace, message: "trace") logging2.history.assertExist(level: .debug, message: "debug") logging2.history.assertExist(level: .info, message: "info") logging2.history.assertExist(level: .warning, message: "warning") } func testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes() throws { let logging1 = TestLogging() let logging2 = TestLogging() var logger1 = logging1.make(label: "1") logger1.logLevel = .info var logger2 = logging2.make(label: "2") logger2.logLevel = .info LoggingSystem.bootstrapInternal { _ in MultiplexLogHandler([logger1, logger2]) } var messageMaterializations: Int = 0 var metadataMaterializations: Int = 0 let multiplexLogger = Logger(label: "test") multiplexLogger.info( { () -> Logger.Message in messageMaterializations += 1 return "info" }(), metadata: { () -> Logger.Metadata in metadataMaterializations += 1 return [:] }() ) logging1.history.assertExist(level: .info, message: "info") logging2.history.assertExist(level: .info, message: "info") XCTAssertEqual(messageMaterializations, 1) XCTAssertEqual(metadataMaterializations, 1) } func testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers() { let logging1 = TestLogging() let logging2 = TestLogging() var logger1 = logging1.make(label: "1") logger1.metadata["one"] = "111" logger1.metadata["in"] = "in-1" var logger2 = logging2.make(label: "2") logger2.metadata["two"] = "222" logger2.metadata["in"] = "in-2" LoggingSystem.bootstrapInternal { _ in MultiplexLogHandler([logger1, logger2]) } var multiplexLogger = Logger(label: "test") // each logs its own metadata multiplexLogger.info("info") logging1.history.assertExist(level: .info, message: "info", metadata: [ "one": "111", "in": "in-1", ]) logging2.history.assertExist(level: .info, message: "info", metadata: [ "two": "222", "in": "in-2", ]) // if modified, change applies to both underlying handlers multiplexLogger[metadataKey: "new"] = "new" multiplexLogger.info("info") logging1.history.assertExist(level: .info, message: "info", metadata: [ "one": "111", "in": "in-1", "new": "new", ]) logging2.history.assertExist(level: .info, message: "info", metadata: [ "two": "222", "in": "in-2", "new": "new", ]) // overriding an existing value works the same way as adding a new one multiplexLogger[metadataKey: "in"] = "multi" multiplexLogger.info("info") logging1.history.assertExist(level: .info, message: "info", metadata: [ "one": "111", "in": "multi", "new": "new", ]) logging2.history.assertExist(level: .info, message: "info", metadata: [ "two": "222", "in": "multi", "new": "new", ]) } func testMultiplexLogHandlerMetadata_readingHandlerMetadata() { let logging1 = TestLogging() let logging2 = TestLogging() var logger1 = logging1.make(label: "1") logger1.metadata["one"] = "111" logger1.metadata["in"] = "in-1" var logger2 = logging2.make(label: "2") logger2.metadata["two"] = "222" logger2.metadata["in"] = "in-2" LoggingSystem.bootstrapInternal { _ in MultiplexLogHandler([logger1, logger2]) } let multiplexLogger = Logger(label: "test") XCTAssertEqual(multiplexLogger.handler.metadata, [ "one": "111", "two": "222", "in": "in-1", ]) } enum TestError: Error { case boom } func testDictionaryMetadata() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger[metadataKey: "foo"] = ["bar": "buz"] logger[metadataKey: "empty-dict"] = [:] logger[metadataKey: "nested-dict"] = ["l1key": ["l2key": ["l3key": "l3value"]]] logger.info("hello world!") testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["foo": ["bar": "buz"], "empty-dict": [:], "nested-dict": ["l1key": ["l2key": ["l3key": "l3value"]]]]) } func testListMetadata() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger[metadataKey: "foo"] = ["bar", "buz"] logger[metadataKey: "empty-list"] = [] logger[metadataKey: "nested-list"] = ["l1str", ["l2str1", "l2str2"]] logger.info("hello world!") testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["foo": ["bar", "buz"], "empty-list": [], "nested-list": ["l1str", ["l2str1", "l2str2"]]]) } // Example of custom "box" which may be used to implement "render at most once" semantics // Not thread-safe, thus should not be shared across threads. internal final class LazyMetadataBox: CustomStringConvertible { private var makeValue: (() -> String)? private var _value: String? public init(_ makeValue: @escaping () -> String) { self.makeValue = makeValue } /// This allows caching a value in case it is accessed via an by name subscript, // rather than as part of rendering all metadata that a LoggingContext was carrying public var value: String { if let f = self.makeValue { self._value = f() self.makeValue = nil } assert(self._value != nil, "_value MUST NOT be nil once `lazyValue` has run.") return self._value! } public var description: String { return "\(self.value)" } } func testStringConvertibleMetadata() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger[metadataKey: "foo"] = .stringConvertible("raw-string") let lazyBox = LazyMetadataBox { "rendered-at-first-use" } logger[metadataKey: "lazy"] = .stringConvertible(lazyBox) logger.info("hello world!") testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["foo": .stringConvertible("raw-string"), "lazy": .stringConvertible(LazyMetadataBox { "rendered-at-first-use" })]) } private func dontEvaluateThisString(file: StaticString = #file, line: UInt = #line) -> Logger.Message { XCTFail("should not have been evaluated", file: file, line: line) return "should not have been evaluated" } func testAutoClosuresAreNotForcedUnlessNeeded() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .error logger.debug(self.dontEvaluateThisString(), metadata: ["foo": "\(self.dontEvaluateThisString())"]) logger.debug(self.dontEvaluateThisString()) logger.info(self.dontEvaluateThisString()) logger.warning(self.dontEvaluateThisString()) logger.log(level: .warning, self.dontEvaluateThisString()) } func testLocalMetadata() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.info("hello world!", metadata: ["foo": "bar"]) logger[metadataKey: "bar"] = "baz" logger[metadataKey: "baz"] = "qux" logger.warning("hello world!") logger.error("hello world!", metadata: ["baz": "quc"]) testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["foo": "bar"]) testLogging.history.assertExist(level: .warning, message: "hello world!", metadata: ["bar": "baz", "baz": "qux"]) testLogging.history.assertExist(level: .error, message: "hello world!", metadata: ["bar": "baz", "baz": "quc"]) } func testCustomFactory() { struct CustomHandler: LogHandler { func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt) {} subscript(metadataKey _: String) -> Logger.Metadata.Value? { get { return nil } set {} } var metadata: Logger.Metadata { get { return Logger.Metadata() } set {} } var logLevel: Logger.Level { get { return .info } set {} } } let logger1 = Logger(label: "foo") XCTAssertFalse(logger1.handler is CustomHandler, "expected non-custom log handler") let logger2 = Logger(label: "foo", factory: { _ in CustomHandler() }) XCTAssertTrue(logger2.handler is CustomHandler, "expected custom log handler") } func testAllLogLevelsExceptCriticalCanBeBlocked() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .critical logger.trace("no") logger.debug("no") logger.info("no") logger.notice("no") logger.warning("no") logger.error("no") logger.critical("yes: critical") testLogging.history.assertNotExist(level: .trace, message: "no") testLogging.history.assertNotExist(level: .debug, message: "no") testLogging.history.assertNotExist(level: .info, message: "no") testLogging.history.assertNotExist(level: .notice, message: "no") testLogging.history.assertNotExist(level: .warning, message: "no") testLogging.history.assertNotExist(level: .error, message: "no") testLogging.history.assertExist(level: .critical, message: "yes: critical") } func testAllLogLevelsWork() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .trace logger.trace("yes: trace") logger.debug("yes: debug") logger.info("yes: info") logger.notice("yes: notice") logger.warning("yes: warning") logger.error("yes: error") logger.critical("yes: critical") testLogging.history.assertExist(level: .trace, message: "yes: trace") testLogging.history.assertExist(level: .debug, message: "yes: debug") testLogging.history.assertExist(level: .info, message: "yes: info") testLogging.history.assertExist(level: .notice, message: "yes: notice") testLogging.history.assertExist(level: .warning, message: "yes: warning") testLogging.history.assertExist(level: .error, message: "yes: error") testLogging.history.assertExist(level: .critical, message: "yes: critical") } func testAllLogLevelByFunctionRefWithSource() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .trace let trace = logger.trace(_:metadata:source:file:function:line:) let debug = logger.debug(_:metadata:source:file:function:line:) let info = logger.info(_:metadata:source:file:function:line:) let notice = logger.notice(_:metadata:source:file:function:line:) let warning = logger.warning(_:metadata:source:file:function:line:) let error = logger.error(_:metadata:source:file:function:line:) let critical = logger.critical(_:metadata:source:file:function:line:) trace("yes: trace", [:], "foo", #file, #function, #line) debug("yes: debug", [:], "foo", #file, #function, #line) info("yes: info", [:], "foo", #file, #function, #line) notice("yes: notice", [:], "foo", #file, #function, #line) warning("yes: warning", [:], "foo", #file, #function, #line) error("yes: error", [:], "foo", #file, #function, #line) critical("yes: critical", [:], "foo", #file, #function, #line) testLogging.history.assertExist(level: .trace, message: "yes: trace", source: "foo") testLogging.history.assertExist(level: .debug, message: "yes: debug", source: "foo") testLogging.history.assertExist(level: .info, message: "yes: info", source: "foo") testLogging.history.assertExist(level: .notice, message: "yes: notice", source: "foo") testLogging.history.assertExist(level: .warning, message: "yes: warning", source: "foo") testLogging.history.assertExist(level: .error, message: "yes: error", source: "foo") testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "foo") } func testAllLogLevelByFunctionRefWithoutSource() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .trace let trace = logger.trace(_:metadata:file:function:line:) let debug = logger.debug(_:metadata:file:function:line:) let info = logger.info(_:metadata:file:function:line:) let notice = logger.notice(_:metadata:file:function:line:) let warning = logger.warning(_:metadata:file:function:line:) let error = logger.error(_:metadata:file:function:line:) let critical = logger.critical(_:metadata:file:function:line:) #if compiler(>=5.3) trace("yes: trace", [:], #fileID, #function, #line) debug("yes: debug", [:], #fileID, #function, #line) info("yes: info", [:], #fileID, #function, #line) notice("yes: notice", [:], #fileID, #function, #line) warning("yes: warning", [:], #fileID, #function, #line) error("yes: error", [:], #fileID, #function, #line) critical("yes: critical", [:], #fileID, #function, #line) #else trace("yes: trace", [:], #file, #function, #line) debug("yes: debug", [:], #file, #function, #line) info("yes: info", [:], #file, #function, #line) notice("yes: notice", [:], #file, #function, #line) warning("yes: warning", [:], #file, #function, #line) error("yes: error", [:], #file, #function, #line) critical("yes: critical", [:], #file, #function, #line) #endif testLogging.history.assertExist(level: .trace, message: "yes: trace") testLogging.history.assertExist(level: .debug, message: "yes: debug") testLogging.history.assertExist(level: .info, message: "yes: info") testLogging.history.assertExist(level: .notice, message: "yes: notice") testLogging.history.assertExist(level: .warning, message: "yes: warning") testLogging.history.assertExist(level: .error, message: "yes: error") testLogging.history.assertExist(level: .critical, message: "yes: critical") } func testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .trace emitLogMessage("hello", to: logger) #if compiler(>=5.3) let moduleName = "LoggingTests" // the actual name #else let moduleName = "SubDirectoryOfLoggingTests" // the last path component of `#file` showing the failure mode #endif testLogging.history.assertExist(level: .trace, message: "hello", source: moduleName) testLogging.history.assertExist(level: .debug, message: "hello", source: moduleName) testLogging.history.assertExist(level: .info, message: "hello", source: moduleName) testLogging.history.assertExist(level: .notice, message: "hello", source: moduleName) testLogging.history.assertExist(level: .warning, message: "hello", source: moduleName) testLogging.history.assertExist(level: .error, message: "hello", source: moduleName) testLogging.history.assertExist(level: .critical, message: "hello", source: moduleName) } func testLogMessageWithStringInterpolation() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .debug let someInt = Int.random(in: 23 ..< 42) logger.debug("My favourite number is \(someInt) and not \(someInt - 1)") testLogging.history.assertExist(level: .debug, message: "My favourite number is \(someInt) and not \(someInt - 1)" as String) } func testLoggingAString() { let testLogging = TestLogging() LoggingSystem.bootstrapInternal(testLogging.make) var logger = Logger(label: "\(#function)") logger.logLevel = .debug let anActualString: String = "hello world!" // We can't stick an actual String in here because we expect a Logger.Message. If we want to log an existing // `String`, we can use string interpolation. The error you'll get trying to use the String directly is: // // error: Cannot convert value of type 'String' to expected argument type 'Logger.Message' logger.debug("\(anActualString)") testLogging.history.assertExist(level: .debug, message: "hello world!") } func testMultiplexerIsValue() { let multi = MultiplexLogHandler([StreamLogHandler.standardOutput(label: "x"), StreamLogHandler.standardOutput(label: "y")]) LoggingSystem.bootstrapInternal { _ in print("new multi") return multi } let logger1: Logger = { var logger = Logger(label: "foo") logger.logLevel = .debug logger[metadataKey: "only-on"] = "first" return logger }() XCTAssertEqual(.debug, logger1.logLevel) var logger2 = logger1 logger2.logLevel = .error logger2[metadataKey: "only-on"] = "second" XCTAssertEqual(.error, logger2.logLevel) XCTAssertEqual(.debug, logger1.logLevel) XCTAssertEqual("first", logger1[metadataKey: "only-on"]) XCTAssertEqual("second", logger2[metadataKey: "only-on"]) logger1.error("hey") } func testLoggerWithGlobalOverride() { struct LogHandlerWithGlobalLogLevelOverride: LogHandler { // the static properties hold the globally overridden log level (if overridden) private static let overrideLock = Lock() private static var overrideLogLevel: Logger.Level? private let recorder: Recorder // this holds the log level if not overridden private var _logLevel: Logger.Level = .info // metadata storage var metadata: Logger.Metadata = [:] init(recorder: Recorder) { self.recorder = recorder } var logLevel: Logger.Level { // when we get asked for the log level, we check if it was globally overridden or not get { return LogHandlerWithGlobalLogLevelOverride.overrideLock.withLock { LogHandlerWithGlobalLogLevelOverride.overrideLogLevel } ?? self._logLevel } // we set the log level whenever we're asked (note: this might not have an effect if globally // overridden) set { self._logLevel = newValue } } func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt) { self.recorder.record(level: level, metadata: metadata, message: message, source: source) } subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { return self.metadata[metadataKey] } set(newValue) { self.metadata[metadataKey] = newValue } } // this is the function to globally override the log level, it is not part of the `LogHandler` protocol static func overrideGlobalLogLevel(_ logLevel: Logger.Level) { LogHandlerWithGlobalLogLevelOverride.overrideLock.withLock { LogHandlerWithGlobalLogLevelOverride.overrideLogLevel = logLevel } } } let logRecorder = Recorder() LoggingSystem.bootstrapInternal { _ in LogHandlerWithGlobalLogLevelOverride(recorder: logRecorder) } var logger1 = Logger(label: "logger-\(#file):\(#line)") var logger2 = logger1 logger1.logLevel = .warning logger1[metadataKey: "only-on"] = "first" logger2.logLevel = .error logger2[metadataKey: "only-on"] = "second" XCTAssertEqual(.error, logger2.logLevel) XCTAssertEqual(.warning, logger1.logLevel) XCTAssertEqual("first", logger1[metadataKey: "only-on"]) XCTAssertEqual("second", logger2[metadataKey: "only-on"]) logger1.notice("logger1, before") logger2.notice("logger2, before") LogHandlerWithGlobalLogLevelOverride.overrideGlobalLogLevel(.debug) logger1.notice("logger1, after") logger2.notice("logger2, after") logRecorder.assertNotExist(level: .notice, message: "logger1, before") logRecorder.assertNotExist(level: .notice, message: "logger2, before") logRecorder.assertExist(level: .notice, message: "logger1, after") logRecorder.assertExist(level: .notice, message: "logger2, after") } func testLogLevelCases() { let levels = Logger.Level.allCases XCTAssertEqual(7, levels.count) } func testLogLevelOrdering() { XCTAssertLessThan(Logger.Level.trace, Logger.Level.debug) XCTAssertLessThan(Logger.Level.trace, Logger.Level.info) XCTAssertLessThan(Logger.Level.trace, Logger.Level.notice) XCTAssertLessThan(Logger.Level.trace, Logger.Level.warning) XCTAssertLessThan(Logger.Level.trace, Logger.Level.error) XCTAssertLessThan(Logger.Level.trace, Logger.Level.critical) XCTAssertLessThan(Logger.Level.debug, Logger.Level.info) XCTAssertLessThan(Logger.Level.debug, Logger.Level.notice) XCTAssertLessThan(Logger.Level.debug, Logger.Level.warning) XCTAssertLessThan(Logger.Level.debug, Logger.Level.error) XCTAssertLessThan(Logger.Level.debug, Logger.Level.critical) XCTAssertLessThan(Logger.Level.info, Logger.Level.notice) XCTAssertLessThan(Logger.Level.info, Logger.Level.warning) XCTAssertLessThan(Logger.Level.info, Logger.Level.error) XCTAssertLessThan(Logger.Level.info, Logger.Level.critical) XCTAssertLessThan(Logger.Level.notice, Logger.Level.warning) XCTAssertLessThan(Logger.Level.notice, Logger.Level.error) XCTAssertLessThan(Logger.Level.notice, Logger.Level.critical) XCTAssertLessThan(Logger.Level.warning, Logger.Level.error) XCTAssertLessThan(Logger.Level.warning, Logger.Level.critical) XCTAssertLessThan(Logger.Level.error, Logger.Level.critical) } final class InterceptStream: TextOutputStream { var interceptedText: String? var strings = [String]() func write(_ string: String) { // This is a test implementation, a real implementation would include locking self.strings.append(string) self.interceptedText = (self.interceptedText ?? "") + string } } func testStreamLogHandlerWritesToAStream() { let interceptStream = InterceptStream() LoggingSystem.bootstrapInternal { _ in StreamLogHandler(label: "test", stream: interceptStream) } let log = Logger(label: "test") let testString = "my message is better than yours" log.critical("\(testString)") let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(testString) XCTAssertTrue(messageSucceeded ?? false) XCTAssertEqual(interceptStream.strings.count, 1) } func testStreamLogHandlerOutputFormat() { let interceptStream = InterceptStream() let label = "testLabel" LoggingSystem.bootstrapInternal { _ in StreamLogHandler(label: label, stream: interceptStream) } let source = "testSource" let log = Logger(label: label) let testString = "my message is better than yours" log.critical("\(testString)", source: source) let pattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label)\\s:\\s\\[\(source)\\]\\s\(testString)$" let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(of: pattern, options: .regularExpression) != nil XCTAssertTrue(messageSucceeded) XCTAssertEqual(interceptStream.strings.count, 1) } func testStreamLogHandlerOutputFormatWithMetaData() { let interceptStream = InterceptStream() let label = "testLabel" LoggingSystem.bootstrapInternal { _ in StreamLogHandler(label: label, stream: interceptStream) } let source = "testSource" let log = Logger(label: label) let testString = "my message is better than yours" log.critical("\(testString)", metadata: ["test": "test"], source: source) let pattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label)\\s:\\stest=test\\s\\[\(source)\\]\\s\(testString)$" let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(of: pattern, options: .regularExpression) != nil XCTAssertTrue(messageSucceeded) XCTAssertEqual(interceptStream.strings.count, 1) } func testStreamLogHandlerOutputFormatWithOrderedMetadata() { let interceptStream = InterceptStream() let label = "testLabel" LoggingSystem.bootstrapInternal { _ in StreamLogHandler(label: label, stream: interceptStream) } let log = Logger(label: label) let testString = "my message is better than yours" log.critical("\(testString)", metadata: ["a": "a0", "b": "b0"]) log.critical("\(testString)", metadata: ["b": "b1", "a": "a1"]) XCTAssertEqual(interceptStream.strings.count, 2) guard interceptStream.strings.count == 2 else { XCTFail("Intercepted \(interceptStream.strings.count) logs, expected 2") return } XCTAssert(interceptStream.strings[0].contains("a=a0 b=b0")) XCTAssert(interceptStream.strings[1].contains("a=a1 b=b1")) } func testStdioOutputStreamWrite() { self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in let logStream = StdioOutputStream(file: writeFD, flushMode: .always) LoggingSystem.bootstrapInternal { StreamLogHandler(label: $0, stream: logStream) } let log = Logger(label: "test") let testString = "hello\u{0} world" log.critical("\(testString)") let size = read(readFD, readBuffer, 256) let output = String(decoding: UnsafeRawBufferPointer(start: UnsafeRawPointer(readBuffer), count: numericCast(size)), as: UTF8.self) let messageSucceeded = output.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(testString) XCTAssertTrue(messageSucceeded) } } func testStdioOutputStreamFlush() { // flush on every statement self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in let logStream = StdioOutputStream(file: writeFD, flushMode: .always) LoggingSystem.bootstrapInternal { StreamLogHandler(label: $0, stream: logStream) } Logger(label: "test").critical("test") let size = read(readFD, readBuffer, 256) XCTAssertGreaterThan(size, -1, "expected flush") logStream.flush() let size2 = read(readFD, readBuffer, 256) XCTAssertEqual(size2, -1, "expected no flush") } // default flushing self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in let logStream = StdioOutputStream(file: writeFD, flushMode: .undefined) LoggingSystem.bootstrapInternal { StreamLogHandler(label: $0, stream: logStream) } Logger(label: "test").critical("test") let size = read(readFD, readBuffer, 256) XCTAssertEqual(size, -1, "expected no flush") logStream.flush() let size2 = read(readFD, readBuffer, 256) XCTAssertGreaterThan(size2, -1, "expected flush") } } func withWriteReadFDsAndReadBuffer(_ body: (CFilePointer, CInt, UnsafeMutablePointer<Int8>) -> Void) { var fds: [Int32] = [-1, -1] #if os(Windows) fds.withUnsafeMutableBufferPointer { let err = _pipe($0.baseAddress, 256, _O_BINARY) XCTAssertEqual(err, 0, "_pipe failed \(err)") } #else fds.withUnsafeMutableBufferPointer { ptr in let err = pipe(ptr.baseAddress!) XCTAssertEqual(err, 0, "pipe failed \(err)") } #endif let writeFD = fdopen(fds[1], "w") let writeBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: 256) defer { writeBuffer.deinitialize(count: 256) writeBuffer.deallocate() } var err = setvbuf(writeFD, writeBuffer, _IOFBF, 256) XCTAssertEqual(err, 0, "setvbuf failed \(err)") let readFD = fds[0] #if os(Windows) let hPipe: HANDLE = HANDLE(bitPattern: _get_osfhandle(readFD))! XCTAssertFalse(hPipe == INVALID_HANDLE_VALUE) var dwMode: DWORD = DWORD(PIPE_NOWAIT) let bSucceeded = SetNamedPipeHandleState(hPipe, &dwMode, nil, nil) XCTAssertTrue(bSucceeded) #else err = fcntl(readFD, F_SETFL, fcntl(readFD, F_GETFL) | O_NONBLOCK) XCTAssertEqual(err, 0, "fcntl failed \(err)") #endif let readBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: 256) defer { readBuffer.deinitialize(count: 256) readBuffer.deallocate() } // the actual test body(writeFD!, readFD, readBuffer) fds.forEach { close($0) } } func testOverloadingError() { struct Dummy: Error, LocalizedError { var errorDescription: String? { return "errorDescription" } } // bootstrap with our test logging impl let logging = TestLogging() LoggingSystem.bootstrapInternal(logging.make) var logger = Logger(label: "test") logger.logLevel = .error logger.error(error: Dummy()) logging.history.assertExist(level: .error, message: "errorDescription") } } extension Logger { #if compiler(>=5.3) public func error(error: Error, metadata: @autoclosure () -> Logger.Metadata? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { self.error("\(error.localizedDescription)", metadata: metadata(), file: file, function: function, line: line) } #else public func error(error: Error, metadata: @autoclosure () -> Logger.Metadata? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.error("\(error.localizedDescription)", metadata: metadata(), file: file, function: function, line: line) } #endif } // Sendable #if compiler(>=5.6) // used to test logging metadata which requires Sendable conformance // @unchecked Sendable since manages it own state extension LoggingTest.LazyMetadataBox: @unchecked Sendable {} // used to test logging stream which requires Sendable conformance // @unchecked Sendable since manages it own state extension LoggingTest.InterceptStream: @unchecked Sendable {} #endif
apache-2.0
fdb1bec88c60cad57ef2b604379f9961
40.345515
168
0.608866
4.362585
false
true
false
false
ifLab/WeCenterMobile-iOS
WeCenterMobile/View/Home/AnswerAgreementActionCell.swift
3
2713
// // AnswerAgreementActionCell.swift // WeCenterMobile // // Created by Darren Liu on 14/12/29. // Copyright (c) 2014年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class AnswerAgreementActionCell: UITableViewCell { @IBOutlet weak var userAvatarView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var questionTitleLabel: UILabel! @IBOutlet weak var agreementCountLabel: UILabel! @IBOutlet weak var answerBodyLabel: UILabel! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var questionButton: UIButton! @IBOutlet weak var answerButton: UIButton! @IBOutlet weak var containerView: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var questionContainerView: UIView! @IBOutlet weak var answerContainerView: UIView! @IBOutlet weak var separatorA: UIView! @IBOutlet weak var separatorB: UIView! override func awakeFromNib() { super.awakeFromNib() msr_scrollView?.delaysContentTouches = false let theme = SettingsManager.defaultManager.currentTheme for v in [containerView, agreementCountLabel] { v.msr_borderColor = theme.borderColorA } for v in [userButton, questionButton, answerButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } for v in [userContainerView, questionContainerView] { v.backgroundColor = theme.backgroundColorB } for v in [agreementCountLabel, answerContainerView] { v.backgroundColor = theme.backgroundColorA } for v in [separatorA, separatorB] { v.backgroundColor = theme.borderColorA } for v in [userNameLabel, questionTitleLabel] { v.textColor = theme.titleTextColor } for v in [agreementCountLabel, typeLabel, answerBodyLabel] { v.textColor = theme.subtitleTextColor } } func update(action action: Action) { let action = action as! AnswerAgreementAction userAvatarView.wc_updateWithUser(action.user) userNameLabel.text = action.user?.name ?? "匿名用户" questionTitleLabel.text = action.answer!.question!.title! agreementCountLabel.text = "\(action.answer!.agreementCount!)" answerBodyLabel.text = action.answer!.body!.wc_plainString userButton.msr_userInfo = action.user questionButton.msr_userInfo = action.answer!.question answerButton.msr_userInfo = action.answer setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
24e94faaa72bf6fd42246dc75e81e3ed
38.173913
99
0.685165
5.04291
false
false
false
false
fastred/HamburgerButton
HamburgerButton/HamburgerButton.swift
2
6875
// // HamburgerButton.swift // HamburgerButton // // Created by Arkadiusz on 14-07-14. // Copyright (c) 2014 Arkadiusz Holko. All rights reserved. // import CoreGraphics import QuartzCore import UIKit public class HamburgerButton: UIButton { public var color: UIColor = UIColor.whiteColor() { didSet { for shapeLayer in shapeLayers { shapeLayer.strokeColor = color.CGColor } } } private let top: CAShapeLayer = CAShapeLayer() private let middle: CAShapeLayer = CAShapeLayer() private let bottom: CAShapeLayer = CAShapeLayer() private let width: CGFloat = 18 private let height: CGFloat = 16 private let topYPosition: CGFloat = 2 private let middleYPosition: CGFloat = 7 private let bottomYPosition: CGFloat = 12 override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: 0)) path.addLineToPoint(CGPoint(x: width, y: 0)) for shapeLayer in shapeLayers { shapeLayer.path = path.CGPath shapeLayer.lineWidth = 2 shapeLayer.strokeColor = color.CGColor // Disables implicit animations. shapeLayer.actions = [ "transform": NSNull(), "position": NSNull() ] let strokingPath = CGPathCreateCopyByStrokingPath(shapeLayer.path, nil, shapeLayer.lineWidth, CGLineCap.Butt, CGLineJoin.Miter, shapeLayer.miterLimit) // Otherwise bounds will be equal to CGRectZero. shapeLayer.bounds = CGPathGetPathBoundingBox(strokingPath) layer.addSublayer(shapeLayer) } let widthMiddle = width / 2 top.position = CGPoint(x: widthMiddle, y: topYPosition) middle.position = CGPoint(x: widthMiddle, y: middleYPosition) bottom.position = CGPoint(x: widthMiddle, y: bottomYPosition) } override public func intrinsicContentSize() -> CGSize { return CGSize(width: width, height: height) } public var showsMenu: Bool = true { didSet { // There's many animations so it's easier to set up duration and timing function at once. CATransaction.begin() CATransaction.setAnimationDuration(0.4) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.2, 1.0)) let strokeStartNewValue: CGFloat = showsMenu ? 0.0 : 0.3 let positionPathControlPointY = bottomYPosition / 2 let verticalOffsetInRotatedState: CGFloat = 0.75 let topRotation = CAKeyframeAnimation(keyPath: "transform") topRotation.values = rotationValuesFromTransform(top.transform, endValue: showsMenu ? CGFloat(-M_PI - M_PI_4) : CGFloat(M_PI + M_PI_4)) // Kind of a workaround. Used because it was hard to animate positions of segments' such that their ends form the arrow's tip and don't cross each other. topRotation.calculationMode = kCAAnimationCubic topRotation.keyTimes = [0.0, 0.33, 0.73, 1.0] top.ahk_applyKeyframeValuesAnimation(topRotation) let topPosition = CAKeyframeAnimation(keyPath: "position") let topPositionEndPoint = CGPoint(x: width / 2, y: showsMenu ? topYPosition : bottomYPosition + verticalOffsetInRotatedState) topPosition.path = quadBezierCurveFromPoint(top.position, toPoint: topPositionEndPoint, controlPoint: CGPoint(x: width, y: positionPathControlPointY)).CGPath top.ahk_applyKeyframePathAnimation(topPosition, endValue: NSValue(CGPoint: topPositionEndPoint)) top.strokeStart = strokeStartNewValue let middleRotation = CAKeyframeAnimation(keyPath: "transform") middleRotation.values = rotationValuesFromTransform(middle.transform, endValue: showsMenu ? CGFloat(-M_PI) : CGFloat(M_PI)) middle.ahk_applyKeyframeValuesAnimation(middleRotation) middle.strokeEnd = showsMenu ? 1.0 : 0.85 let bottomRotation = CAKeyframeAnimation(keyPath: "transform") bottomRotation.values = rotationValuesFromTransform(bottom.transform, endValue: showsMenu ? CGFloat(-M_PI_2 - M_PI_4) : CGFloat(M_PI_2 + M_PI_4)) bottomRotation.calculationMode = kCAAnimationCubic bottomRotation.keyTimes = [0.0, 0.33, 0.63, 1.0] bottom.ahk_applyKeyframeValuesAnimation(bottomRotation) let bottomPosition = CAKeyframeAnimation(keyPath: "position") let bottomPositionEndPoint = CGPoint(x: width / 2, y: showsMenu ? bottomYPosition : topYPosition - verticalOffsetInRotatedState) bottomPosition.path = quadBezierCurveFromPoint(bottom.position, toPoint: bottomPositionEndPoint, controlPoint: CGPoint(x: 0, y: positionPathControlPointY)).CGPath bottom.ahk_applyKeyframePathAnimation(bottomPosition, endValue: NSValue(CGPoint: bottomPositionEndPoint)) bottom.strokeStart = strokeStartNewValue CATransaction.commit() } } private var shapeLayers: [CAShapeLayer] { return [top, middle, bottom] } } extension CALayer { func ahk_applyKeyframeValuesAnimation(animation: CAKeyframeAnimation) { guard let copy = animation.copy() as? CAKeyframeAnimation, let values = copy.values where !values.isEmpty, let keyPath = copy.keyPath else { return } self.addAnimation(copy, forKey: keyPath) self.setValue(values[values.count - 1], forKeyPath:keyPath) } // Mark: TODO: endValue could be removed from the definition, because it's possible to get it from the path (see: CGPathApply). func ahk_applyKeyframePathAnimation(animation: CAKeyframeAnimation, endValue: NSValue) { let copy = animation.copy() as! CAKeyframeAnimation self.addAnimation(copy, forKey: copy.keyPath) self.setValue(endValue, forKeyPath:copy.keyPath!) } } func rotationValuesFromTransform(transform: CATransform3D, endValue: CGFloat) -> [NSValue] { let frames = 4 // values at 0, 1/3, 2/3 and 1 return (0..<frames).map { num in NSValue(CATransform3D: CATransform3DRotate(transform, endValue / CGFloat(frames - 1) * CGFloat(num), 0, 0, 1)) } } func quadBezierCurveFromPoint(startPoint: CGPoint, toPoint: CGPoint, controlPoint: CGPoint) -> UIBezierPath { let quadPath = UIBezierPath() quadPath.moveToPoint(startPoint) quadPath.addQuadCurveToPoint(toPoint, controlPoint: controlPoint) return quadPath }
mit
e6793571e7bb1a4b1197c1ec9dcf2925
38.976744
165
0.666036
4.814426
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Extension/DateExtension.swift
1
3592
// // DateExtension.swift // DereGuide // // Created by zzk on 2017/1/15. // Copyright © 2017年 zzk. All rights reserved. // import UIKit extension Date { func toString(format: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = .tokyo) -> String { let dateFormatter = DateFormatter() dateFormatter.timeZone = timeZone dateFormatter.dateFormat = format // If not set this, and in your phone settings select a region that defaults to a 24-hour time, for example "United Kingdom" or "France". Then, disable the "24 hour time" from the settings. Now if you create an NSDateFormatter without setting its locale, "HH" will not work. // Reference from https://stackoverflow.com/questions/29374181/nsdateformatter-hh-returning-am-pm-on-ios-8-device dateFormatter.locale = Locale(identifier: "en_US_POSIX") return dateFormatter.string(from: self) } func truncateHours(timeZone: TimeZone = .tokyo) -> Date { var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = timeZone let comps = gregorian.dateComponents([.day, .month, .year], from: self) return gregorian.date(from: comps)! } func getElapsedInterval() -> String { var calendar = Calendar.current calendar.locale = Locale(identifier: Bundle.main.preferredLocalizations[0]) //--> IF THE USER HAVE THE PHONE IN SPANISH BUT YOUR APP ONLY SUPPORTS I.E. ENGLISH AND GERMAN WE SHOULD CHANGE THE LOCALE OF THE FORMATTER TO THE PREFERRED ONE (IS THE LOCALE THAT THE USER IS SEEING THE APP), IF NOT, THIS ELAPSED TIME IS GOING TO APPEAR IN SPANISH let formatter = DateComponentsFormatter() formatter.unitsStyle = .full formatter.maximumUnitCount = 1 formatter.calendar = calendar var dateString: String? let interval = calendar.dateComponents([.year, .month, .weekOfYear, .day, .hour, .minute, .second], from: self, to: Date()) if let year = interval.year, year > 0 { formatter.allowedUnits = [.year] //2 years } else if let month = interval.month, month > 0 { formatter.allowedUnits = [.month] //1 month } else if let week = interval.weekOfYear, week > 0 { formatter.allowedUnits = [.weekOfMonth] //3 weeks } else if let day = interval.day, day > 0 { formatter.allowedUnits = [.day] // 6 days } else if let hour = interval.hour, hour > 0 { formatter.allowedUnits = [.hour] } else if let minute = interval.minute, minute > 0 { formatter.allowedUnits = [.minute] } else if let second = interval.second, second > 0 { formatter.allowedUnits = [.second] } else { // let dateFormatter = DateFormatter() // dateFormatter.locale = Locale(identifier: Bundle.main.preferredLocalizations[0]) //--> IF THE USER HAVE THE PHONE IN SPANISH BUT YOUR APP ONLY SUPPORTS I.E. ENGLISH AND GERMAN WE SHOULD CHANGE THE LOCALE OF THE FORMATTER TO THE PREFERRED ONE (IS THE LOCALE THAT THE USER IS SEEING THE APP), IF NOT, THIS ELAPSED TIME IS GOING TO APPEAR IN SPANISH // dateFormatter.dateStyle = .medium // dateFormatter.doesRelativeDateFormatting = true // // dateString = dateFormatter.string(from: self) // IS GOING TO SHOW 'TODAY' } if dateString == nil { dateString = formatter.string(from: self, to: Date()) } return dateString! } }
mit
29a0b78a29c8dbf41cc48188a24311fc
46.853333
360
0.638061
4.303357
false
true
false
false
nathawes/swift
test/decl/var/function_builders.swift
1
9558
// RUN: %target-typecheck-verify-swift @_functionBuilder // expected-error {{'@_functionBuilder' attribute cannot be applied to this declaration}} var globalBuilder: Int @_functionBuilder // expected-error {{'@_functionBuilder' attribute cannot be applied to this declaration}} func globalBuilderFunction() -> Int { return 0 } @_functionBuilder struct Maker {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder class Inventor {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @Maker // expected-error {{function builder attribute 'Maker' can only be applied to a parameter, function, or computed property}} typealias typename = Inventor @Maker // expected-error {{function builder attribute 'Maker' can only be applied to a variable if it defines a getter}} var global: Int // FIXME: should this be allowed? @Maker var globalWithEmptyImplicitGetter: Int {} // expected-error@-1 {{computed property must have accessors specified}} // expected-error@-3 {{function builder attribute 'Maker' can only be applied to a variable if it defines a getter}} @Maker var globalWithEmptyExplicitGetter: Int { get {} } // expected-error{{type 'Maker' has no member 'buildBlock'}} @Maker var globalWithSingleGetter: Int { 0 } // expected-error {{ype 'Maker' has no member 'buildBlock'}} @Maker var globalWithMultiGetter: Int { 0; 0 } // expected-error {{ype 'Maker' has no member 'buildBlock'}} @Maker func globalFunction() {} // expected-error {{ype 'Maker' has no member 'buildBlock'}} @Maker func globalFunctionWithFunctionParam(fn: () -> ()) {} // expected-error {{ype 'Maker' has no member 'buildBlock'}} func makerParam(@Maker fn: () -> ()) {} // FIXME: these diagnostics are reversed? func makerParamRedundant(@Maker // expected-error {{only one function builder attribute can be attached to a parameter}} @Maker // expected-note {{previous function builder specified here}} fn: () -> ()) {} func makerParamConflict(@Maker // expected-error {{only one function builder attribute can be attached to a parameter}} @Inventor // expected-note {{previous function builder specified here}} fn: () -> ()) {} func makerParamMissing1(@Missing // expected-error {{unknown attribute 'Missing'}} @Maker fn: () -> ()) {} func makerParamMissing2(@Maker @Missing // expected-error {{unknown attribute 'Missing'}} fn: () -> ()) {} func makerParamExtra(@Maker(5) // expected-error {{function builder attributes cannot have arguments}} fn: () -> ()) {} func makerParamAutoclosure(@Maker // expected-error {{function builder attribute 'Maker' cannot be applied to an autoclosure parameter}} fn: @autoclosure () -> ()) {} @_functionBuilder struct GenericMaker<T> {} // expected-note {{generic type 'GenericMaker' declared here}} expected-error {{function builder must provide at least one static 'buildBlock' method}} struct GenericContainer<T> { // expected-note {{generic type 'GenericContainer' declared here}} @_functionBuilder struct Maker {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} } func makeParamUnbound(@GenericMaker // expected-error {{reference to generic type 'GenericMaker' requires arguments}} fn: () -> ()) {} func makeParamBound(@GenericMaker<Int> fn: () -> ()) {} func makeParamNestedUnbound(@GenericContainer.Maker // expected-error {{reference to generic type 'GenericContainer' requires arguments}} fn: () -> ()) {} func makeParamNestedBound(@GenericContainer<Int>.Maker fn: () -> ()) {} protocol P { } @_functionBuilder struct ConstrainedGenericMaker<T: P> {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} struct WithinGeneric<U> { func makeParamBoundInContext(@GenericMaker<U> fn: () -> ()) {} // expected-error@+1{{type 'U' does not conform to protocol 'P'}} func makeParamBoundInContextBad(@ConstrainedGenericMaker<U> fn: () -> ()) {} } @_functionBuilder struct ValidBuilder1 { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } protocol BuilderFuncHelper {} extension BuilderFuncHelper { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder struct ValidBuilder2: BuilderFuncHelper {} class BuilderFuncBase { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder class ValidBuilder3: BuilderFuncBase {} @_functionBuilder struct ValidBuilder4 {} extension ValidBuilder4 { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder struct ValidBuilder5 { static func buildBlock() -> Int { 0 } } @_functionBuilder struct InvalidBuilder1 {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder struct InvalidBuilder2 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{did you mean to make instance method 'buildBlock' static?}} {{3-3=static }} } @_functionBuilder struct InvalidBuilder3 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder struct InvalidBuilder4 {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} extension InvalidBuilder4 { func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{did you mean to make instance method 'buildBlock' static?}} {{3-3=static }} } protocol InvalidBuilderHelper {} extension InvalidBuilderHelper { func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder struct InvalidBuilder5: InvalidBuilderHelper {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder struct InvalidBuilder6 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} static var buildBlock: Int = 0 // expected-note {{potential match 'buildBlock' is not a static method}} } struct Callable { func callAsFunction(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder struct InvalidBuilder7 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} static var buildBlock = Callable() // expected-note {{potential match 'buildBlock' is not a static method}} } class BuilderVarBase { static var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder class InvalidBuilder8: BuilderVarBase {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} protocol BuilderVarHelper {} extension BuilderVarHelper { static var buildBlock: (Any...) -> Int { { return $0.count } } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder struct InvalidBuilder9: BuilderVarHelper {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder struct InvalidBuilder10 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} static var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder enum InvalidBuilder11 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} case buildBlock(Any) // expected-note {{enum case 'buildBlock' cannot be used to satisfy the function builder requirement}} } struct S { @ValidBuilder1 var v1: Int { 1 } @ValidBuilder2 var v2: Int { 1 } @ValidBuilder3 var v3: Int { 1 } @ValidBuilder4 var v4: Int { 1 } @ValidBuilder5 func v5() -> Int {} @InvalidBuilder1 var i1: Int { 1 } // expected-error {{type 'InvalidBuilder1' has no member 'buildBlock'}} @InvalidBuilder2 var i2: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder2'; did you mean to use a value of this type instead?}} @InvalidBuilder3 var i3: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder3'; did you mean to use a value of this type instead?}} @InvalidBuilder4 var i4: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder4'; did you mean to use a value of this type instead?}} @InvalidBuilder5 var i5: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder5'; did you mean to use a value of this type instead?}} @InvalidBuilder6 var i6: Int { 1 } // expected-error {{cannot call value of non-function type 'Int'}} @InvalidBuilder7 var i7: Int { 1 } @InvalidBuilder8 var i8: Int { 1 } @InvalidBuilder9 var i9: Int { 1 } @InvalidBuilder10 var i10: Int { 1 } @InvalidBuilder11 var i11: InvalidBuilder11 { 1 } }
apache-2.0
ad5e1c3fe74cf24256e5e96218c668d2
42.643836
179
0.699623
4.221731
false
false
false
false
jordanhamill/Stated
Sources/Stated/DSL/TransitionFromStateWithMapDSL.swift
1
1507
public struct TransitionFromStateWithMap<InputArguments, ArgumentsForFromState, StateFrom: State, MappedState> { let transitionFromState: TransitionFromState<InputArguments, ArgumentsForFromState, StateFrom> let map: (StateFrom) -> MappedState public func to<StateTo>(_ to: StateSlot<InputArguments, StateTo>) -> StateTransitionTrigger<InputArguments, StateFrom, StateTo> where StateTo.Arguments == InputArguments, StateTo.MappedState == MappedState { let transition = transitionFromState.from._to(to, map: map) return StateTransitionTrigger(inputSlot: transitionFromState.input, transition: transition) } } /// /// Sugar for creating a mapped state transition e.g. /// An alias for `TransitionFromStateWithMap.to(_: toState)` to be used when mapping is required in order to construct the `toState`. /// ``` /// anInput.given(fromState).transition(with: { $0.prop }).to(toState) /// ``` /// Using operators you can get readable arrow structure /// ``` /// anInput | fromState => { $0.prop } => toState /// ``` /// public func => <ArgumentsForToState, ArgumentsForFromState, StateFrom, StateTo>( transitionFromStateMap: TransitionFromStateWithMap<ArgumentsForToState, ArgumentsForFromState, StateFrom, StateTo.MappedState>, toState: StateSlot<ArgumentsForToState, StateTo>) -> StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo> where StateTo.Arguments == ArgumentsForToState { return transitionFromStateMap.to(toState) }
mit
def20b2d50c7b008738970b97f805b0a
52.821429
133
0.745853
4.368116
false
false
false
false
FTChinese/iPhoneApp
Pods/FolioReaderKit/Source/FolioReaderKit.swift
2
26028
// // FolioReaderKit.swift // FolioReaderKit // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import Foundation import UIKit // MARK: - Internal constants for devices internal let isPad = UIDevice.current.userInterfaceIdiom == .pad internal let isPhone = UIDevice.current.userInterfaceIdiom == .phone // MARK: - Internal constants internal let kApplicationDocumentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] internal let kCurrentFontFamily = "com.folioreader.kCurrentFontFamily" internal let kCurrentFontSize = "com.folioreader.kCurrentFontSize" internal let kCurrentAudioRate = "com.folioreader.kCurrentAudioRate" internal let kCurrentHighlightStyle = "com.folioreader.kCurrentHighlightStyle" internal var kCurrentMediaOverlayStyle = "com.folioreader.kMediaOverlayStyle" internal var kCurrentScrollDirection = "com.folioreader.kCurrentScrollDirection" internal let kNightMode = "com.folioreader.kNightMode" internal let kCurrentTOCMenu = "com.folioreader.kCurrentTOCMenu" internal let kHighlightRange = 30 internal var kBookId: String! /** Defines the media overlay and TTS selection - Default: The background is colored - Underline: The underlined is colored - TextColor: The text is colored */ enum MediaOverlayStyle: Int { case `default` case underline case textColor init() { self = .default } func className() -> String { return "mediaOverlayStyle\(self.rawValue)" } } /// FolioReader actions delegate @objc public protocol FolioReaderDelegate: class { /** Did finished loading book. - parameter folioReader: The FolioReader instance - parameter book: The Book instance */ @objc optional func folioReader(_ folioReader: FolioReader, didFinishedLoading book: FRBook) /** Called when reader did closed. */ @objc optional func folioReaderDidClosed() } /** Main Library class with some useful constants and methods */ open class FolioReader: NSObject { open static let shared = FolioReader() open var unzipPath: String? static let defaults = UserDefaults.standard open weak var delegate: FolioReaderDelegate? open weak var readerCenter: FolioReaderCenter? open weak var readerContainer: FolioReaderContainer! open weak var readerAudioPlayer: FolioReaderAudioPlayer? fileprivate override init() {} /// Check if reader is open static var isReaderOpen = false /// Check if reader is open and ready static var isReaderReady = false /// Check if layout needs to change to fit Right To Left static var needsRTLChange: Bool { return book.spine.isRtl && readerConfig.scrollDirection == .horizontal } /// Check if current theme is Night mode open static var nightMode: Bool { get { return FolioReader.defaults.bool(forKey: kNightMode) } set (value) { FolioReader.defaults.set(value, forKey: kNightMode) FolioReader.defaults.synchronize() if let readerCenter = FolioReader.shared.readerCenter { UIView.animate(withDuration: 0.6, animations: { _ = readerCenter.currentPage?.webView.js("nightMode(\(nightMode))") readerCenter.pageIndicatorView?.reloadColors() readerCenter.configureNavBar() readerCenter.scrollScrubber?.reloadColors() readerCenter.collectionView.backgroundColor = (nightMode ? readerConfig.nightModeBackground : UIColor.white) }, completion: { (finished: Bool) in NotificationCenter.default.post(name: Notification.Name(rawValue: "needRefreshPageMode"), object: nil) }) } } } /// Check current font name open static var currentFont: FolioReaderFont { get { return FolioReaderFont(rawValue: FolioReader.defaults.value(forKey: kCurrentFontFamily) as! Int)! } set (font) { FolioReader.defaults.setValue(font.rawValue, forKey: kCurrentFontFamily) _ = FolioReader.shared.readerCenter?.currentPage?.webView.js("setFontName('\(font.cssIdentifier)')") } } /// Check current font size open static var currentFontSize: FolioReaderFontSize { get { return FolioReaderFontSize(rawValue: FolioReader.defaults.value(forKey: kCurrentFontSize) as! Int)! } set (value) { FolioReader.defaults.setValue(value.rawValue, forKey: kCurrentFontSize) if let _currentPage = FolioReader.shared.readerCenter?.currentPage { _currentPage.webView.js("setFontSize('\(currentFontSize.cssIdentifier)')") } } } /// Check current audio rate, the speed of speech voice static var currentAudioRate: Int { get { return FolioReader.defaults.value(forKey: kCurrentAudioRate) as! Int } set (value) { FolioReader.defaults.setValue(value, forKey: kCurrentAudioRate) } } /// Check the current highlight style static var currentHighlightStyle: Int { get { return FolioReader.defaults.value(forKey: kCurrentHighlightStyle) as! Int } set (value) { FolioReader.defaults.setValue(value, forKey: kCurrentHighlightStyle) } } /// Check the current Media Overlay or TTS style static var currentMediaOverlayStyle: MediaOverlayStyle { get { return MediaOverlayStyle(rawValue: FolioReader.defaults.value(forKey: kCurrentMediaOverlayStyle) as! Int)! } set (value) { FolioReader.defaults.setValue(value.rawValue, forKey: kCurrentMediaOverlayStyle) } } /// Check the current scroll direction open static var currentScrollDirection: Int { get { return FolioReader.defaults.value(forKey: kCurrentScrollDirection) as! Int } set (value) { FolioReader.defaults.setValue(value, forKey: kCurrentScrollDirection) if let _readerCenter = FolioReader.shared.readerCenter { let direction = FolioReaderScrollDirection(rawValue: currentScrollDirection) ?? .defaultVertical _readerCenter.setScrollDirection(direction) } } } // MARK: - Get Cover Image /** Read Cover Image and Return an `UIImage` */ open class func getCoverImage(_ epubPath: String) -> UIImage? { return FREpubParser().parseCoverImage(epubPath) } // MARK: - Get Title open class func getTitle(_ epubPath: String) -> String? { return FREpubParser().parseTitle(epubPath) } open class func getAuthorName(_ epubPath: String) -> String? { return FREpubParser().parseAuthorName(epubPath) } // MARK: - Present Folio Reader /** Present a Folio Reader for a Parent View Controller. */ open class func presentReader(parentViewController: UIViewController, withEpubPath epubPath: String, andConfig config: FolioReaderConfig, shouldRemoveEpub: Bool = true, animated: Bool = true) { let reader = FolioReaderContainer(withConfig: config, epubPath: epubPath, removeEpub: shouldRemoveEpub) FolioReader.shared.readerContainer = reader parentViewController.present(reader, animated: animated, completion: nil) } // MARK: - Application State /** Called when the application will resign active */ open class func applicationWillResignActive() { saveReaderState() } /** Called when the application will terminate */ open class func applicationWillTerminate() { saveReaderState() } /** Save Reader state, book, page and scroll are saved */ open class func saveReaderState() { guard FolioReader.isReaderOpen else { return } if let currentPage = FolioReader.shared.readerCenter?.currentPage { let position = [ "pageNumber": currentPageNumber, "pageOffsetX": currentPage.webView.scrollView.contentOffset.x, "pageOffsetY": currentPage.webView.scrollView.contentOffset.y ] as [String : Any] FolioReader.defaults.set(position, forKey: kBookId) } } /** Closes and save the reader current instance */ open class func close() { FolioReader.saveReaderState() FolioReader.isReaderOpen = false FolioReader.isReaderReady = false FolioReader.shared.readerAudioPlayer?.stop(immediate: true) FolioReader.defaults.set(0, forKey: kCurrentTOCMenu) FolioReader.shared.delegate?.folioReaderDidClosed?() } } // MARK: - Global Functions func isNight<T> (_ f: T, _ l: T) -> T { return FolioReader.nightMode ? f : l } // MARK: - Scroll Direction Functions /** Simplify attibution of values based on direction, basically is to avoid too much usage of `switch`, `if` and `else` statements to check. So basically this is like a shorthand version of the `switch` verification. For example: ``` let pageOffsetPoint = isDirection(CGPoint(x: 0, y: pageOffset), CGPoint(x: pageOffset, y: 0), CGPoint(x: 0, y: pageOffset)) ``` As usually the `vertical` direction and `horizontalContentVertical` has similar statements you can basically hide the last value and it will assume the value from `vertical` as fallback. ``` let pageOffsetPoint = isDirection(CGPoint(x: 0, y: pageOffset), CGPoint(x: pageOffset, y: 0)) ``` - parameter vertical: Value for `vertical` direction - parameter horizontal: Value for `horizontal` direction - parameter horizontalContentVertical: Value for `horizontalWithVerticalContent` direction, if nil will fallback to `vertical` value - returns: The right value based on direction. */ func isDirection<T> (_ vertical: T, _ horizontal: T, _ horizontalContentVertical: T? = nil) -> T { switch readerConfig.scrollDirection { case .vertical, .defaultVertical: return vertical case .horizontal: return horizontal case .horizontalWithVerticalContent: return horizontalContentVertical ?? vertical } } extension UICollectionViewScrollDirection { static func direction() -> UICollectionViewScrollDirection { return isDirection(.vertical, .horizontal, .horizontal) } } extension UICollectionViewScrollPosition { static func direction() -> UICollectionViewScrollPosition { return isDirection(.top, .left, .left) } } extension CGPoint { func forDirection() -> CGFloat { return isDirection(y, x, y) } } extension CGSize { func forDirection() -> CGFloat { return isDirection(height, width, height) } func forReverseDirection() -> CGFloat { return isDirection(width, height, width) } } extension CGRect { func forDirection() -> CGFloat { return isDirection(height, width, height) } } extension ScrollDirection { static func negative() -> ScrollDirection { return isDirection(.down, .right, .right) } static func positive() -> ScrollDirection { return isDirection(.up, .left, .left) } } // MARK: Helpers /** Delay function From: http://stackoverflow.com/a/24318861/517707 - parameter delay: Delay in seconds - parameter closure: Closure */ func delay(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } // MARK: - Extensions internal extension Bundle { class func frameworkBundle() -> Bundle { return Bundle(for: FolioReader.self) } } internal extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) let hex = rgba.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 break case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 break case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 break case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 break default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") break } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix", terminator: "") } self.init(red:red, green:green, blue:blue, alpha:alpha) } /** Hex string of a UIColor instance. - parameter rgba: Whether the alpha should be included. */ // from: https://github.com/yeahdongcn/UIColor-Hex-Swift 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)) } } // MARK: - color shades // https://gist.github.com/mbigatti/c6be210a6bbc0ff25972 func highlightColor() -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: 0.30, brightness: 1, alpha: alpha) } else { return self; } } /** Returns a lighter color by the provided percentage :param: lighting percent percentage :returns: lighter UIColor */ func lighterColor(_ percent : Double) -> UIColor { return colorWithBrightnessFactor(CGFloat(1 + percent)); } /** Returns a darker color by the provided percentage :param: darking percent percentage :returns: darker UIColor */ func darkerColor(_ percent : Double) -> UIColor { return colorWithBrightnessFactor(CGFloat(1 - percent)); } /** Return a modified color using the brightness factor provided :param: factor brightness factor :returns: modified color */ func colorWithBrightnessFactor(_ factor: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return self; } } } internal extension String { /// Truncates the string to length number of characters and /// appends optional trailing string if longer func truncate(_ length: Int, trailing: String? = nil) -> String { if self.characters.count > length { return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) + (trailing ?? "") } else { return self } } func stripHtml() -> String { return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression) } func stripLineBreaks() -> String { return self.replacingOccurrences(of: "\n", with: "", options: .regularExpression) } /** Converts a clock time such as `0:05:01.2` to seconds (`Double`) Looks for media overlay clock formats as specified [here][1] - Note: this may not be the most efficient way of doing this. It can be improved later on. - Returns: seconds as `Double` [1]: http://www.idpf.org/epub/301/spec/epub-mediaoverlays.html#app-clock-examples */ func clockTimeToSeconds() -> Double { let val = self.trimmingCharacters(in: CharacterSet.whitespaces) if( val.isEmpty ){ return 0 } let formats = [ "HH:mm:ss.SSS" : "^\\d{1,2}:\\d{2}:\\d{2}\\.\\d{1,3}$", "HH:mm:ss" : "^\\d{1,2}:\\d{2}:\\d{2}$", "mm:ss.SSS" : "^\\d{1,2}:\\d{2}\\.\\d{1,3}$", "mm:ss" : "^\\d{1,2}:\\d{2}$", "ss.SSS" : "^\\d{1,2}\\.\\d{1,3}$", ] // search for normal duration formats such as `00:05:01.2` for (format, pattern) in formats { if val.range(of: pattern, options: .regularExpression) != nil { let formatter = DateFormatter() formatter.dateFormat = format let time = formatter.date(from: val) if( time == nil ){ return 0 } formatter.dateFormat = "ss.SSS" let seconds = (formatter.string(from: time!) as NSString).doubleValue formatter.dateFormat = "mm" let minutes = (formatter.string(from: time!) as NSString).doubleValue formatter.dateFormat = "HH" let hours = (formatter.string(from: time!) as NSString).doubleValue return seconds + (minutes*60) + (hours*60*60) } } // if none of the more common formats match, check for other possible formats // 2345ms if val.range(of: "^\\d+ms$", options: .regularExpression) != nil{ return (val as NSString).doubleValue / 1000.0 } // 7.25h if val.range(of: "^\\d+(\\.\\d+)?h$", options: .regularExpression) != nil { return (val as NSString).doubleValue * 60 * 60 } // 13min if val.range(of: "^\\d+(\\.\\d+)?min$", options: .regularExpression) != nil { return (val as NSString).doubleValue * 60 } return 0 } func clockTimeToMinutesString() -> String { let val = clockTimeToSeconds() let min = floor(val / 60) let sec = floor(val.truncatingRemainder(dividingBy: 60)) return String(format: "%02.f:%02.f", min, sec) } } internal extension UIImage { convenience init?(readerImageNamed: String) { self.init(named: readerImageNamed, in: Bundle.frameworkBundle(), compatibleWith: nil) } /** Forces the image to be colored with Reader Config tintColor - returns: Returns a colored image */ func ignoreSystemTint() -> UIImage { return self.imageTintColor(readerConfig.tintColor).withRenderingMode(.alwaysOriginal) } /** Colorize the image with a color - parameter tintColor: The input color - returns: Returns a colored image */ func imageTintColor(_ tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! as CGContext context.translateBy(x: 0, y: self.size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(CGBlendMode.normal) let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect context.clip(to: rect, mask: self.cgImage!) tintColor.setFill() context.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() return newImage } /** Generate a image with a color - parameter color: The input color - returns: Returns a colored image */ class func imageWithColor(_ color: UIColor?) -> UIImage { let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) let context = UIGraphicsGetCurrentContext() if let color = color { color.setFill() } else { UIColor.white.setFill() } context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } /** Generates a image with a `CALayer` - parameter layer: The input `CALayer` - returns: Return a rendered image */ class func imageWithLayer(_ layer: CALayer) -> UIImage { UIGraphicsBeginImageContextWithOptions(layer.bounds.size, layer.isOpaque, 0.0) layer.render(in: UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } /** Generates a image from a `UIView` - parameter view: The input `UIView` - returns: Return a rendered image */ class func imageWithView(_ view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } } internal extension UIViewController { func setCloseButton() { let closeImage = UIImage(readerImageNamed: "icon-navbar-close")?.ignoreSystemTint() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: closeImage, style: .plain, target: self, action: #selector(dismiss as (Void) -> Void)) } func dismiss() { dismiss(nil) } func dismiss(_ completion: (() -> Void)?) { DispatchQueue.main.async { self.dismiss(animated: true, completion: { completion?() }) } } // MARK: - NavigationBar func setTransparentNavigation() { let navBar = self.navigationController?.navigationBar navBar?.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navBar?.hideBottomHairline() navBar?.isTranslucent = true } func setTranslucentNavigation(_ translucent: Bool = true, color: UIColor, tintColor: UIColor = UIColor.white, titleColor: UIColor = UIColor.black, andFont font: UIFont = UIFont.systemFont(ofSize: 17)) { let navBar = self.navigationController?.navigationBar navBar?.setBackgroundImage(UIImage.imageWithColor(color), for: UIBarMetrics.default) navBar?.showBottomHairline() navBar?.isTranslucent = translucent navBar?.tintColor = tintColor navBar?.titleTextAttributes = [NSForegroundColorAttributeName: titleColor, NSFontAttributeName: font] } } internal extension UINavigationBar { func hideBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.isHidden = true } func showBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.isHidden = false } fileprivate func hairlineImageViewInNavigationBar(_ view: UIView) -> UIImageView? { if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews ) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) { return imageView } } return nil } } extension UINavigationController { open override var preferredStatusBarStyle : UIStatusBarStyle { guard let viewController = visibleViewController else { return .default } return viewController.preferredStatusBarStyle } open override var supportedInterfaceOrientations : UIInterfaceOrientationMask { guard let viewController = visibleViewController else { return .portrait } return viewController.supportedInterfaceOrientations } open override var shouldAutorotate : Bool { guard let viewController = visibleViewController else { return false } return viewController.shouldAutorotate } } /** This fixes iOS 9 crash http://stackoverflow.com/a/32010520/517707 */ extension UIAlertController { open override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .portrait } open override var shouldAutorotate : Bool { return false } } extension Array { /** Return index if is safe, if not return nil http://stackoverflow.com/a/30593673/517707 */ subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
mit
efc41d5ff110f61d06609b65db16c615
32.455013
206
0.629322
4.662845
false
false
false
false
Authman2/Pix
Pods/Hero/Sources/UIKit+Hero.swift
1
13430
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit fileprivate let parameterRegex = "(?:\\-?\\d+(\\.?\\d+)?)|\\w+" fileprivate let modifiersRegex = "(\\w+)(?:\\(([^\\)]*)\\))?" public extension UIView { private struct AssociatedKeys { static var heroID = "heroID" static var heroModifiers = "heroModifers" static var heroStoredAlpha = "heroStoredAlpha" } /** **heroID** is the identifier for the view. When doing a transition between two view controllers, Hero will search through all the subviews for both view controllers and matches views with the same **heroID**. Whenever a pair is discovered, Hero will automatically transit the views from source state to the destination state. */ @IBInspectable public var heroID: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.heroID) as? String } set { objc_setAssociatedObject(self, &AssociatedKeys.heroID, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** Use **heroModifiers** to specify animations alongside the main transition. Checkout `HeroModifier.swift` for available modifiers. */ public var heroModifiers: [HeroModifier]? { get { return objc_getAssociatedObject(self, &AssociatedKeys.heroModifiers) as? [HeroModifier] } set { objc_setAssociatedObject(self, &AssociatedKeys.heroModifiers, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** **heroModifierString** provides another way to set **heroModifiers**. It can be assigned through storyboard. */ @IBInspectable public var heroModifierString: String? { get { fatalError("Reverse lookup is not supported") } set { guard let newValue = newValue else { heroModifiers = nil return } let modifierString = newValue as NSString func matches(for regex: String, text: NSString) -> [NSTextCheckingResult] { do { let regex = try NSRegularExpression(pattern: regex) return regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)) } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } var modifiers = [HeroModifier]() for r in matches(for: modifiersRegex, text:modifierString) { var parameters = [String]() if r.numberOfRanges > 2, r.rangeAt(2).location < modifierString.length { let parameterString = modifierString.substring(with: r.rangeAt(2)) as NSString for r in matches(for: parameterRegex, text: parameterString) { parameters.append(parameterString.substring(with: r.range)) } } let name = modifierString.substring(with: r.rangeAt(1)) if let modifier = HeroModifier.from(name: name, parameters: parameters) { modifiers.append(modifier) } } heroModifiers = modifiers } } internal func slowSnapshotView() -> UIView { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0) layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(image: image) imageView.frame = bounds let snapshotView = UIView(frame:bounds) snapshotView.addSubview(imageView) return snapshotView } internal var flattenedViewHierarchy: [UIView] { return [self] + subviews.flatMap { $0.flattenedViewHierarchy } } /// Used for .overFullScreen presentation internal var heroStoredAlpha: CGFloat? { get { if let doubleValue = (objc_getAssociatedObject(self, &AssociatedKeys.heroStoredAlpha) as? NSNumber)?.doubleValue { return CGFloat(doubleValue) } return nil } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.heroStoredAlpha, NSNumber(value:newValue.native), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &AssociatedKeys.heroStoredAlpha, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } } internal extension NSObject { func copyWithArchiver() -> Any? { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! } } public extension UIViewController { private struct AssociatedKeys { static var previousNavigationDelegate = "previousNavigationDelegate" static var previousTabBarDelegate = "previousTabBarDelegate" static var heroStoredSnapshots = "heroStoredSnapshots" } var previousNavigationDelegate: UINavigationControllerDelegate? { get { return objc_getAssociatedObject(self, &AssociatedKeys.previousNavigationDelegate) as? UINavigationControllerDelegate } set { objc_setAssociatedObject(self, &AssociatedKeys.previousNavigationDelegate, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var previousTabBarDelegate: UITabBarControllerDelegate? { get { return objc_getAssociatedObject(self, &AssociatedKeys.previousTabBarDelegate) as? UITabBarControllerDelegate } set { objc_setAssociatedObject(self, &AssociatedKeys.previousTabBarDelegate, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @IBInspectable public var isHeroEnabled: Bool { get { return transitioningDelegate is Hero } set { guard newValue != isHeroEnabled else { return } if newValue { transitioningDelegate = Hero.shared if let navi = self as? UINavigationController { previousNavigationDelegate = navi.delegate navi.delegate = Hero.shared } if let tab = self as? UITabBarController { previousTabBarDelegate = tab.delegate tab.delegate = Hero.shared } } else { transitioningDelegate = nil if let navi = self as? UINavigationController, navi.delegate is Hero { navi.delegate = previousNavigationDelegate } if let tab = self as? UITabBarController, tab.delegate is Hero { tab.delegate = previousTabBarDelegate } } } } /// used for .overFullScreen presentation internal var heroStoredSnapshots: [UIView]? { get { return objc_getAssociatedObject(self, &AssociatedKeys.heroStoredSnapshots) as? [UIView] } set { objc_setAssociatedObject(self, &AssociatedKeys.heroStoredSnapshots, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @available(*, deprecated: 0.1.4, message: "use hero_dismissViewController instead") @IBAction public func ht_dismiss(_ sender: UIView) { hero_dismissViewController() } @available(*, deprecated: 0.1.4, message: "use hero_replaceViewController(with:) instead") public func heroReplaceViewController(with next: UIViewController) { hero_replaceViewController(with: next) } /** Dismiss the current view controller with animation. Will perform a navigationController.popViewController if the current view controller is contained inside a navigationController */ @IBAction public func hero_dismissViewController() { if let navigationController = navigationController, navigationController.viewControllers.first != self { navigationController.popViewController(animated: true) } else { dismiss(animated: true, completion: nil) } } /** Unwind to the root view controller using Hero */ @IBAction public func hero_unwindToRootViewController() { hero_unwindToViewController { $0.presentingViewController == nil } } /** Unwind to a specific view controller using Hero */ public func hero_unwindToViewController(_ toViewController: UIViewController) { hero_unwindToViewController { $0 == toViewController } } /** Unwind to a view controller that responds to the given selector using Hero */ public func hero_unwindToViewController(withSelector: Selector) { hero_unwindToViewController { $0.responds(to: withSelector) } } /** Unwind to a view controller with given class using Hero */ public func hero_unwindToViewController(withClass: AnyClass) { hero_unwindToViewController { $0.isKind(of: withClass) } } /** Unwind to a view controller that the matchBlock returns true on. */ public func hero_unwindToViewController(withMatchBlock: (UIViewController) -> Bool) { var target: UIViewController? = nil var current: UIViewController? = self while target == nil && current != nil { if let childViewControllers = (current as? UINavigationController)?.childViewControllers ?? current!.navigationController?.childViewControllers { for vc in childViewControllers.reversed() { if vc != self, withMatchBlock(vc) { target = vc break } } } if target == nil { current = current!.presentingViewController if let vc = current, withMatchBlock(vc) == true { target = vc } } } if let target = target { if target.presentedViewController != nil { let _ = target.navigationController?.popToViewController(target, animated: false) let fromVC = self.navigationController ?? self let toVC = target.navigationController ?? target if target.presentedViewController != fromVC { // UIKit's UIViewController.dismiss will jump to target.presentedViewController then perform the dismiss. // We overcome this behavior by inserting a snapshot into target.presentedViewController // And also force Hero to use the current VC as the fromViewController Hero.shared.fromViewController = fromVC let snapshotView = fromVC.view.snapshotView(afterScreenUpdates: true)! toVC.presentedViewController!.view.addSubview(snapshotView) } toVC.dismiss(animated: true, completion: nil) } else { let _ = target.navigationController?.popToViewController(target, animated: true) } } else { // unwind target not found } } /** Replace the current view controller with another VC on the navigation/modal stack. */ public func hero_replaceViewController(with next: UIViewController) { if let navigationController = navigationController { var vcs = navigationController.childViewControllers if !vcs.isEmpty { vcs.removeLast() vcs.append(next) } if navigationController.isHeroEnabled { Hero.shared.forceNotInteractive = true } navigationController.setViewControllers(vcs, animated: true) } else if let container = view.superview { let parentVC = presentingViewController Hero.shared.transition(from: self, to: next, in: container) { finished in if finished { UIApplication.shared.keyWindow?.addSubview(next.view) if let parentVC = parentVC { self.dismiss(animated: false) { parentVC.present(next, animated: false, completion:nil) } } else { UIApplication.shared.keyWindow?.rootViewController = next } } } } } public func hero_presentOnTop(viewController: UIViewController, frame: CGRect) { var oldViews = view.flattenedViewHierarchy oldViews.removeFirst() let hero = HeroIndependentController() addChildViewController(viewController) viewController.view.frame = frame view.addSubview(viewController.view) viewController.didMove(toParentViewController: self) viewController.view.heroModifiers = [.scale(0.5), .fade] hero.transition(rootView: view, fromViews: oldViews, toViews: viewController.view.flattenedViewHierarchy) } } internal extension UIImage { class func imageWithView(view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } } internal extension UIColor { var components:(r:CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } var alphaComponent: CGFloat { return components.a } }
gpl-3.0
df849ad2ff21f21e925b3d2aa5968acc
36.619048
151
0.697915
4.952065
false
false
false
false
coach-plus/ios
Pods/YPImagePicker/Source/Pages/Gallery/LibraryMediaManager.swift
1
8238
// // LibraryMediaManager.swift // YPImagePicker // // Created by Sacha DSO on 26/01/2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Photos class LibraryMediaManager { weak var v: YPLibraryView? var collection: PHAssetCollection? internal var fetchResult: PHFetchResult<PHAsset>! internal var previousPreheatRect: CGRect = .zero internal var imageManager: PHCachingImageManager? internal var exportTimer: Timer? internal var currentExportSessions: [AVAssetExportSession] = [] func initialize() { imageManager = PHCachingImageManager() resetCachedAssets() } func resetCachedAssets() { imageManager?.stopCachingImagesForAllAssets() previousPreheatRect = .zero } func updateCachedAssets(in collectionView: UICollectionView) { let size = UIScreen.main.bounds.width/4 * UIScreen.main.scale let cellSize = CGSize(width: size, height: size) var preheatRect = collectionView.bounds preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height) let delta = abs(preheatRect.midY - previousPreheatRect.midY) if delta > collectionView.bounds.height / 3.0 { var addedIndexPaths: [IndexPath] = [] var removedIndexPaths: [IndexPath] = [] previousPreheatRect.differenceWith(rect: preheatRect, removedHandler: { removedRect in let indexPaths = collectionView.aapl_indexPathsForElementsInRect(removedRect) removedIndexPaths += indexPaths }, addedHandler: { addedRect in let indexPaths = collectionView.aapl_indexPathsForElementsInRect(addedRect) addedIndexPaths += indexPaths }) let assetsToStartCaching = fetchResult.assetsAtIndexPaths(addedIndexPaths) let assetsToStopCaching = fetchResult.assetsAtIndexPaths(removedIndexPaths) imageManager?.startCachingImages(for: assetsToStartCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) imageManager?.stopCachingImages(for: assetsToStopCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) previousPreheatRect = preheatRect } } func fetchVideoUrlAndCrop(for videoAsset: PHAsset, cropRect: CGRect, callback: @escaping (URL) -> Void) { let videosOptions = PHVideoRequestOptions() videosOptions.isNetworkAccessAllowed = true videosOptions.deliveryMode = .highQualityFormat imageManager?.requestAVAsset(forVideo: videoAsset, options: videosOptions) { asset, _, _ in do { guard let asset = asset else { print("⚠️ PHCachingImageManager >>> Don't have the asset"); return } let assetComposition = AVMutableComposition() let trackTimeRange = CMTimeRangeMake(start: CMTime.zero, duration: asset.duration) // 1. Inserting audio and video tracks in composition guard let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first, let videoCompositionTrack = assetComposition .addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) else { print("⚠️ PHCachingImageManager >>> Problems with video track") return } if let audioTrack = asset.tracks(withMediaType: AVMediaType.audio).first, let audioCompositionTrack = assetComposition .addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid) { try audioCompositionTrack.insertTimeRange(trackTimeRange, of: audioTrack, at: CMTime.zero) } try videoCompositionTrack.insertTimeRange(trackTimeRange, of: videoTrack, at: CMTime.zero) // Layer Instructions let layerInstructions = AVMutableVideoCompositionLayerInstruction(assetTrack: videoCompositionTrack) var transform = videoTrack.preferredTransform transform.tx -= cropRect.minX transform.ty -= cropRect.minY layerInstructions.setTransform(transform, at: CMTime.zero) // CompositionInstruction let mainInstructions = AVMutableVideoCompositionInstruction() mainInstructions.timeRange = trackTimeRange mainInstructions.layerInstructions = [layerInstructions] // Video Composition let videoComposition = AVMutableVideoComposition(propertiesOf: asset) videoComposition.instructions = [mainInstructions] videoComposition.renderSize = cropRect.size // needed? // 5. Configuring export session let exportSession = AVAssetExportSession(asset: assetComposition, presetName: YPConfig.video.compression) exportSession?.outputFileType = YPConfig.video.fileType exportSession?.shouldOptimizeForNetworkUse = true exportSession?.videoComposition = videoComposition exportSession?.outputURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension) // 6. Exporting DispatchQueue.main.async { self.exportTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.onTickExportTimer), userInfo: exportSession, repeats: true) } self.currentExportSessions.append(exportSession!) exportSession?.exportAsynchronously(completionHandler: { DispatchQueue.main.async { if let url = exportSession?.outputURL, exportSession?.status == .completed { callback(url) if let index = self.currentExportSessions.firstIndex(of:exportSession!) { self.currentExportSessions.remove(at: index) } } else { let error = exportSession?.error print("error exporting video \(String(describing: error))") } } }) } catch let error { print("⚠️ PHCachingImageManager >>> \(error)") } } } @objc func onTickExportTimer(sender: Timer) { if let exportSession = sender.userInfo as? AVAssetExportSession { if let v = v { if exportSession.progress > 0 { v.updateProgress(exportSession.progress) } } if exportSession.progress > 0.99 { sender.invalidate() v?.updateProgress(0) self.exportTimer = nil } } } func forseCancelExporting() { for s in self.currentExportSessions { s.cancelExport() } } }
mit
fd269f643be1cc19884acb65586b562e
46
116
0.543343
6.676136
false
false
false
false
AliSoftware/Dip
Sources/AutoInjection.swift
1
14900
// // Dip // // Copyright (c) 2015 Olivier Halligon <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension DependencyContainer { /** Resolves properties of passed object wrapped with `Injected<T>` or `InjectedWeak<T>` */ func autoInjectProperties(in instance: Any) throws { let mirror = Mirror(reflecting: instance) //mirror only contains class own properties //so we need to walk through super class mirrors //to resolve super class auto-injected properties var superClassMirror = mirror.superclassMirror while superClassMirror != nil { try superClassMirror?.children.forEach(resolveChild) superClassMirror = superClassMirror?.superclassMirror } try mirror.children.forEach(resolveChild) } private func resolveChild(child: Mirror.Child) throws { //HOTFIX for https://bugs.swift.org/browse/SR-2282 guard !String(describing: type(of: child.value)).has(prefix: "ImplicitlyUnwrappedOptional") else { return } guard let injectedPropertyBox = child.value as? AutoInjectedPropertyBox else { return } let wrappedType = type(of: injectedPropertyBox).wrappedType let contextKey = DefinitionKey(type: wrappedType, typeOfArguments: Void.self, tag: context.tag) try inContext(key:contextKey, injectedInType: context?.resolvingType, injectedInProperty: child.label, logErrors: false) { try injectedPropertyBox.resolve(self) } } } /** Implement this protocol if you want to use your own type to wrap auto-injected properties instead of using `Injected<T>` or `InjectedWeak<T>` types. **Example**: ```swift class MyCustomBox<T> { private(set) var value: T? init() {} } extension MyCustomBox: AutoInjectedPropertyBox { static var wrappedType: Any.Type { return T.self } func resolve(container: DependencyContainer) throws { value = try container.resolve() as T } } ``` */ public protocol AutoInjectedPropertyBox { ///The type of wrapped property. static var wrappedType: Any.Type { get } /** This method will be called by `DependencyContainer` during processing resolved instance properties. In this method you should resolve an instance for wrapped property and store a reference to it. - parameter container: A container to be used to resolve an instance - note: This method is not intended to be called manually, `DependencyContainer` will call it by itself. */ func resolve(_ container: DependencyContainer) throws } #if swift(>=5.1) /** Use this wrapper to identify _strong_ properties of the instance that should be auto-injected by `DependencyContainer`. Type T can be any type. **Example**: ```swift class ClientImp: Client { @Injected var service: Service? } ``` - seealso: `InjectedWeak` */ @propertyWrapper public struct Injected<T>: _InjectedPropertyBox, AutoInjectedPropertyBox { let valueBox: NullableBox<T> = NullableBox(nil) ///Wrapped value. public var wrappedValue: T? { get { return valueBox.unboxed } set { guard (required && newValue != nil) || !required else { fatalError("Can not set required property to nil.") } valueBox.unboxed = newValue } } let required: Bool let didInject: (T) -> () let tag: DependencyContainer.Tag? let overrideTag: Bool public init(wrappedValue initialValue: T?) { self.init() } } #else /** Use this wrapper to identify _strong_ properties of the instance that should be auto-injected by `DependencyContainer`. Type T can be any type. - warning: Do not define this property as optional or container will not be able to inject it. Instead define it with initial value of `Injected<T>()`. **Example**: ```swift class ClientImp: Client { var service = Injected<Service>() } ``` - seealso: `InjectedWeak` */ public struct Injected<T>: _InjectedPropertyBox, AutoInjectedPropertyBox { let valueBox: NullableBox<T> = NullableBox(nil) ///Wrapped value. public var value: T? { return valueBox.unboxed } let required: Bool let didInject: (T) -> () let tag: DependencyContainer.Tag? let overrideTag: Bool /// Returns a new wrapper with provided value. func setValue(_ value: T?) -> Injected { guard (required && value != nil) || !required else { fatalError("Can not set required property to nil.") } return Injected(value: value, required: required, tag: tag, overrideTag: overrideTag, didInject: didInject) } } #endif public extension Injected { ///The type of wrapped property. static var wrappedType: Any.Type { return T.self } init(value: T?, required: Bool = true, tag: DependencyTagConvertible?, overrideTag: Bool, didInject: @escaping (T) -> ()) { self.init(required: required, tag: tag, overrideTag: overrideTag, didInject: didInject) self.valueBox.unboxed = value } init(required: Bool = true, tag: DependencyTagConvertible?, overrideTag: Bool, didInject: @escaping (T) -> () = { _ in }) { self.required = required self.tag = tag?.dependencyTag self.overrideTag = overrideTag self.didInject = didInject } /** Creates a new wrapper for auto-injected property. - parameters: - required: Defines if the property is required or not. If container fails to inject required property it will als fail to resolve the instance that defines that property. Default is `true`. - tag: An optional tag to use to lookup definitions when injecting this property. Default is `nil`. - didInject: Block that will be called when concrete instance is injected in this property. Similar to `didSet` property observer. Default value does nothing. */ init(required: Bool = true, didInject: @escaping (T) -> () = { _ in }) { self.init(value: nil, required: required, tag: nil, overrideTag: false, didInject: didInject) } init(required: Bool = true, tag: DependencyTagConvertible?, didInject: @escaping (T) -> () = { _ in }) { self.init(value: nil, required: required, tag: tag, overrideTag: true, didInject: didInject) } func resolve(_ container: DependencyContainer) throws { let resolved: T? = try self.resolve(with: container, tag: tag, overrideTag: overrideTag, required: required) valueBox.unboxed = resolved if let resolved = resolved { didInject(resolved) } } } #if swift(>=5.1) /** Use this wrapper to identify _weak_ properties of the instance that should be auto-injected by `DependencyContainer`. Type T should be a **class** type. Otherwise it will cause runtime exception when container will try to resolve the property. Use this wrapper to define one of two circular dependencies to avoid retain cycle. - note: The only difference between `InjectedWeak` and `Injected` is that `InjectedWeak` uses _weak_ reference to store underlying value, when `Injected` uses _strong_ reference. For that reason if you resolve instance that has a _weak_ auto-injected property this property will be released when `resolve` will complete. Use `InjectedWeak<T>` to define one of two circular dependencies if another dependency is defined as `Injected<U>`. This will prevent a retain cycle between resolved instances. - warning: Do not define this property as optional or container will not be able to inject it. Instead define it with initial value of `InjectedWeak<T>()`. **Example**: ```swift class ServiceImp: Service { @InjectedWeak var client: Client? } ``` - seealso: `Injected` */ @propertyWrapper public struct InjectedWeak<T>: _InjectedPropertyBox, AutoInjectedPropertyBox { //Only classes (means AnyObject) can be used as `weak` properties //but we can not make <T: AnyObject> because that will prevent using protocol as generic type //so we just rely on user reading documentation and passing AnyObject in runtime //also we will throw fatal error if type can not be casted to AnyObject during resolution. let valueBox: WeakBox<T> = WeakBox(nil) ///Wrapped value. public var wrappedValue: T? { get { return valueBox.value } set { guard (required && newValue != nil) || !required else { fatalError("Can not set required property to nil.") } valueBox.unboxed = newValue as AnyObject } } let required: Bool let didInject: (T) -> () let tag: DependencyContainer.Tag? let overrideTag: Bool public init(wrappedValue initialValue: T?) { self.init() } } #else /** Use this wrapper to identify _weak_ properties of the instance that should be auto-injected by `DependencyContainer`. Type T should be a **class** type. Otherwise it will cause runtime exception when container will try to resolve the property. Use this wrapper to define one of two circular dependencies to avoid retain cycle. - note: The only difference between `InjectedWeak` and `Injected` is that `InjectedWeak` uses _weak_ reference to store underlying value, when `Injected` uses _strong_ reference. For that reason if you resolve instance that has a _weak_ auto-injected property this property will be released when `resolve` will complete. Use `InjectedWeak<T>` to define one of two circular dependencies if another dependency is defined as `Injected<U>`. This will prevent a retain cycle between resolved instances. - warning: Do not define this property as optional or container will not be able to inject it. Instead define it with initial value of `InjectedWeak<T>()`. **Example**: ```swift class ServiceImp: Service { var client = InjectedWeak<Client>() } ``` - seealso: `Injected` */ public struct InjectedWeak<T>: _InjectedPropertyBox, AutoInjectedPropertyBox { //Only classes (means AnyObject) can be used as `weak` properties //but we can not make <T: AnyObject> because that will prevent using protocol as generic type //so we just rely on user reading documentation and passing AnyObject in runtime //also we will throw fatal error if type can not be casted to AnyObject during resolution. let valueBox: WeakBox<T> = WeakBox(nil) ///Wrapped value. public var value: T? { return valueBox.value } let required: Bool let didInject: (T) -> () let tag: DependencyContainer.Tag? let overrideTag: Bool /// Returns a new wrapper with provided value. func setValue(_ value: T?) -> InjectedWeak { guard (required && value != nil) || !required else { fatalError("Can not set required property to nil.") } return InjectedWeak(value: value, required: required, tag: tag, overrideTag: overrideTag, didInject: didInject) } } #endif public extension InjectedWeak { ///The type of wrapped property. static var wrappedType: Any.Type { return T.self } init(value: T?, required: Bool = true, tag: DependencyTagConvertible?, overrideTag: Bool, didInject: @escaping (T) -> ()) { self.init(required: required, tag: tag, overrideTag: overrideTag, didInject: didInject) self.valueBox.unboxed = value as AnyObject } init(required: Bool = true, tag: DependencyTagConvertible?, overrideTag: Bool, didInject: @escaping (T) -> () = { _ in }) { self.required = required self.tag = tag?.dependencyTag self.overrideTag = overrideTag self.didInject = didInject } /** Creates a new wrapper for weak auto-injected property. - parameters: - required: Defines if the property is required or not. If container fails to inject required property it will als fail to resolve the instance that defines that property. Default is `true`. - tag: An optional tag to use to lookup definitions when injecting this property. Default is `nil`. - didInject: Block that will be called when concrete instance is injected in this property. Similar to `didSet` property observer. Default value does nothing. */ init(required: Bool = true, didInject: @escaping (T) -> () = { _ in }) { self.init(value: nil, required: required, tag: nil, overrideTag: false, didInject: didInject) } init(required: Bool = true, tag: DependencyTagConvertible?, didInject: @escaping (T) -> () = { _ in }) { self.init(value: nil, required: required, tag: tag, overrideTag: true, didInject: didInject) } func resolve(_ container: DependencyContainer) throws { let resolved: T? = try self.resolve(with: container, tag: tag, overrideTag: overrideTag, required: required) valueBox.unboxed = resolved as AnyObject if let resolved = resolved { didInject(resolved) } } } protocol _InjectedPropertyBox {} extension _InjectedPropertyBox { func resolve<T>(with container: DependencyContainer, tag: DependencyContainer.Tag?, overrideTag: Bool, required: Bool) throws -> T? { let tag = overrideTag ? tag : container.context.tag do { container.context.key = container.context.key.tagged(with: tag) let key = DefinitionKey(type: T.self, typeOfArguments: Void.self, tag: tag?.dependencyTag) return try resolve(with: container, key: key, builder: { (factory: (Any) throws -> Any) in try factory(()) }) as? T } catch { let error = DipError.autoInjectionFailed(label: container.context.injectedInProperty, type: container.context.resolvingType, underlyingError: error) if required { throw error } else { log(level: .Errors, error) return nil } } } func resolve<U>(with container: DependencyContainer, key: DefinitionKey, builder: ((U) throws -> Any) throws -> Any) throws -> Any { return try container._resolve(key: key, builder: { definition throws -> Any in try builder(definition.weakFactory) }) } }
mit
d62c79a4e5cb0dabbdee7618c0352205
34.141509
156
0.699195
4.321346
false
false
false
false
blackbear/OpenHumansUpload
OpenHumansUpload/OpenHumansUpload/DataView.swift
1
15883
// // DataView.swift // OpenHumansUpload // // Created by James Turner on 6/18/16. // Copyright © 2016 Open Humans. All rights reserved. // import UIKit class DataViewCell :UITableViewCell { @IBOutlet weak var dataName: UILabel! @IBOutlet weak var dataSwitch: UISwitch! } class DataView: UIViewController,UITableViewDelegate, UITableViewDataSource { 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 func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 10 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Body Measurements" case 1: return "Fitness" case 2: return "Vitals" case 3: return "Results" case 4: return "Nutrition" case 5: return "Misc" default: return "Foo" } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("dataViewCell", forIndexPath: indexPath) /** /*--------------------------------*/ /* HKQuantityType Identifiers */ /*--------------------------------*/ // Body Measurements HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyMassIndex NS_AVAILABLE_IOS(8_0); // Scalar(Count), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyFatPercentage NS_AVAILABLE_IOS(8_0); // Scalar(Percent, 0.0 - 1.0), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierHeight NS_AVAILABLE_IOS(8_0); // Length, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyMass NS_AVAILABLE_IOS(8_0); // Mass, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierLeanBodyMass NS_AVAILABLE_IOS(8_0); // Mass, Discrete // Fitness HK_EXTERN NSString * const HKQuantityTypeIdentifierStepCount NS_AVAILABLE_IOS(8_0); // Scalar(Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDistanceWalkingRunning NS_AVAILABLE_IOS(8_0); // Length, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDistanceCycling NS_AVAILABLE_IOS(8_0); // Length, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierBasalEnergyBurned NS_AVAILABLE_IOS(8_0); // Energy, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierActiveEnergyBurned NS_AVAILABLE_IOS(8_0); // Energy, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierFlightsClimbed NS_AVAILABLE_IOS(8_0); // Scalar(Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierNikeFuel NS_AVAILABLE_IOS(8_0); // Scalar(Count), Cumulative // Vitals HK_EXTERN NSString * const HKQuantityTypeIdentifierHeartRate NS_AVAILABLE_IOS(8_0); // Scalar(Count)/Time, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyTemperature NS_AVAILABLE_IOS(8_0); // Temperature, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBasalBodyTemperature NS_AVAILABLE_IOS(9_0); // Basal Body Temperature, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodPressureSystolic NS_AVAILABLE_IOS(8_0); // Pressure, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodPressureDiastolic NS_AVAILABLE_IOS(8_0); // Pressure, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierRespiratoryRate NS_AVAILABLE_IOS(8_0); // Scalar(Count)/Time, Discrete // Results HK_EXTERN NSString * const HKQuantityTypeIdentifierOxygenSaturation NS_AVAILABLE_IOS(8_0); // Scalar (Percent, 0.0 - 1.0, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierPeripheralPerfusionIndex NS_AVAILABLE_IOS(8_0); // Scalar(Percent, 0.0 - 1.0), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodGlucose NS_AVAILABLE_IOS(8_0); // Mass/Volume, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierNumberOfTimesFallen NS_AVAILABLE_IOS(8_0); // Scalar(Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierElectrodermalActivity NS_AVAILABLE_IOS(8_0); // Conductance, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierInhalerUsage NS_AVAILABLE_IOS(8_0); // Scalar(Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodAlcoholContent NS_AVAILABLE_IOS(8_0); // Scalar(Percent, 0.0 - 1.0), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierForcedVitalCapacity NS_AVAILABLE_IOS(8_0); // Volume, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierForcedExpiratoryVolume1 NS_AVAILABLE_IOS(8_0); // Volume, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierPeakExpiratoryFlowRate NS_AVAILABLE_IOS(8_0); // Volume/Time, Discrete // Nutrition HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatTotal NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatPolyunsaturated NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatMonounsaturated NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatSaturated NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCholesterol NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietarySodium NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCarbohydrates NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFiber NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietarySugar NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryEnergyConsumed NS_AVAILABLE_IOS(8_0); // Energy, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryProtein NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminA NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminB6 NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminB12 NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminC NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminD NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminE NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminK NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCalcium NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryIron NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryThiamin NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryRiboflavin NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryNiacin NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFolate NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryBiotin NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryPantothenicAcid NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryPhosphorus NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryIodine NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryMagnesium NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryZinc NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietarySelenium NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCopper NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryManganese NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryChromium NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryMolybdenum NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryChloride NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryPotassium NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCaffeine NS_AVAILABLE_IOS(8_0); // Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryWater NS_AVAILABLE_IOS(9_0); // Volume, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierUVExposure NS_AVAILABLE_IOS(9_0); // Scalar (Count), Discrete /*--------------------------------*/ /* HKCategoryType Identifiers */ /*--------------------------------*/ HK_EXTERN NSString * const HKCategoryTypeIdentifierSleepAnalysis NS_AVAILABLE_IOS(8_0); // HKCategoryValueSleepAnalysis HK_EXTERN NSString * const HKCategoryTypeIdentifierSedentaryState NS_AVAILABLE_IOS(9_0); // HKCategoryValueSedentaryState HK_EXTERN NSString * const HKCategoryTypeIdentifierCervicalMucusQuality NS_AVAILABLE_IOS(9_0); // HKCategoryValueCervicalMucusQuality HK_EXTERN NSString * const HKCategoryTypeIdentifierOvulationTestResult NS_AVAILABLE_IOS(9_0); // HKCategoryValueOvulationTestResult HK_EXTERN NSString * const HKCategoryTypeIdentifierMenstrualFlow NS_AVAILABLE_IOS(9_0); // HKCategoryValueMenstrualFlow HK_EXTERN NSString * const HKCategoryTypeIdentifierVaginalSpotting NS_AVAILABLE_IOS(9_0); // HKCategoryValue HK_EXTERN NSString * const HKCategoryTypeIdentifierSexualActivity NS_AVAILABLE_IOS(9_0); // HKCategoryValue /*--------------------------------------*/ /* HKCharacteristicType Identifiers */ /*--------------------------------------*/ HK_EXTERN NSString * const HKCharacteristicTypeIdentifierBiologicalSex NS_AVAILABLE_IOS(8_0); // NSNumber (HKCharacteristicBiologicalSex) HK_EXTERN NSString * const HKCharacteristicTypeIdentifierBloodType NS_AVAILABLE_IOS(8_0); // NSNumber (HKCharacteristicBloodType) HK_EXTERN NSString * const HKCharacteristicTypeIdentifierDateOfBirth NS_AVAILABLE_IOS(8_0); // NSDate HK_EXTERN NSString * const HKCharacteristicTypeIdentifierFitzpatrickSkinType NS_AVAILABLE_IOS(9_0); // HKFitzpatrickSkinType /*-----------------------------------*/ /* HKCorrelationType Identifiers */ /*-----------------------------------*/ HK_EXTERN NSString * const HKCorrelationTypeIdentifierBloodPressure NS_AVAILABLE_IOS(8_0); HK_EXTERN NSString * const HKCorrelationTypeIdentifierFood NS_AVAILABLE_IOS(8_0); /*------------------------------*/ /* HKWorkoutType Identifier */ /*------------------------------*/ HK_EXTERN NSString * const HKWorkoutTypeIdentifier NS_AVAILABLE_IOS(8_0); // 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. } */ }
mit
533ca28ac3605decc3097696d1ec9150
66.29661
157
0.6525
5.032319
false
false
false
false
bananafish911/SmartReceiptsiOS
SmartReceipts/Modules/Generate Report/GenerateReportFormView.swift
1
2566
// // GenerateReportFormView.swift // SmartReceipts // // Created by Bogdan Evsenev on 07/06/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import UIKit import Eureka import RxSwift class GenerateReportFormView: FormViewController { private weak var fullPdfReport: BehaviorSubject<Bool>! private weak var pdfReportWithoutTable: BehaviorSubject<Bool>! private weak var csvFile: BehaviorSubject<Bool>! private weak var zipStampedJPGs: BehaviorSubject<Bool>! weak var settingsTapObservable: PublishSubject<Any?>? init(fullPdf: BehaviorSubject<Bool>, pdfNoTable: BehaviorSubject<Bool>, csvFile: BehaviorSubject<Bool>, zipStamped: BehaviorSubject<Bool>) { super.init(nibName: nil, bundle: nil) self.fullPdfReport = fullPdf self.pdfReportWithoutTable = pdfNoTable self.csvFile = csvFile self.zipStampedJPGs = zipStamped } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.bounces = false form +++ Section() <<< ButtonRow() { row in row.title = LocalizedString("generate.report.button.configure.layout") }.cellSetup({ cell, _ in cell.tintColor = AppTheme.themeColor }).onCellSelection({ [weak self] _,_ in self?.settingsTapObservable?.onNext(nil) }) +++ Section() <<< checkRow(title: LocalizedString("generate.report.option.full.pdf")) .onChange({ [weak self] row in self?.fullPdfReport.onNext(row.value ?? false) }) <<< checkRow(title: LocalizedString("generate.report.option.pdf.no.table")) .onChange({ [weak self] row in self?.pdfReportWithoutTable?.onNext(row.value ?? false) }) <<< checkRow(title: LocalizedString("generate.report.option.csv")) .onChange({ [weak self] row in self?.csvFile.onNext(row.value ?? false) }) <<< checkRow(title: LocalizedString("generate.report.option.zip.stamped")) .onChange({ [weak self] row in self?.zipStampedJPGs?.onNext(row.value ?? false) }) } private func checkRow(title: String) -> CheckRow { return CheckRow() { row in row.title = LocalizedString(title) }.cellSetup({ cell, _ in cell.tintColor = AppTheme.themeColor }) } }
agpl-3.0
0c8cc440e517918591d63d6006d2c048
31.884615
83
0.617544
4.468641
false
false
false
false
prosperence/prosperence-ios
Prosperance/Prosperance/LogginInViewController.swift
1
4466
import UIKit class LogginInViewController: UIViewController { @IBOutlet weak var urlTextField: UITextField! @IBOutlet weak var passwordTextFeild: UITextField! @IBOutlet weak var errorTextFeild: UITextView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var busyDiv: UIActivityIndicatorView! var profile: Profile? var errorMessage: String = "" var sessionId: String = "" override func viewDidLoad() { super.viewDidLoad() updateScreen(false) } override func viewWillDisappear(animated: Bool) { ///////////////////////////////////////////////////////////////////////////////// // If remember password set to false, clear password when leaving Login screen // ///////////////////////////////////////////////////////////////////////////////// if(profile?.rememberPassword === false) { profile?.password = "" } } func updateScreen(isBlocked: Bool) { if(isBlocked) { busyDiv.startAnimating() passwordTextFeild.userInteractionEnabled = false loginButton.enabled = false } else { busyDiv.stopAnimating() // Get host from environment variables let dict = NSProcessInfo.processInfo().environment let host = dict["HOST"] as? String urlTextField.text = host passwordTextFeild.text = profile?.password passwordTextFeild.userInteractionEnabled = true errorTextFeild.text = errorMessage ////////////////////////////////////////////////////////// // Set button text depending on whether error displayed // ////////////////////////////////////////////////////////// if(errorMessage.isEmpty) { loginButton.setTitle("Login", forState: UIControlState.Normal) } else { loginButton.setTitle("Try Again", forState: UIControlState.Normal) } loginButton.enabled = true } } @IBAction func handleUIUpdate(sender: AnyObject) { profile?.password = passwordTextFeild.text } @IBAction func handleLoginButton(sender: AnyObject) { updateScreen(true) let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(backgroundQueue, { var wasSuccessful = self.authWithServer() if(wasSuccessful) { ///////////////////////////////////////////////////////////////////////////////////// // we were successful - keep the screen locked - and transition to the next screen // ///////////////////////////////////////////////////////////////////////////////////// dispatch_async(dispatch_get_main_queue()) { self.showUiWebView() } } else { /////////////////////////////////////////////////////////////////////////////////////////// // there were issues - update the screen with them - unlock it - allow user to try again // /////////////////////////////////////////////////////////////////////////////////////////// dispatch_async(dispatch_get_main_queue()) { self.updateScreen(false) } } }) } func showUiWebView() -> Void { var wvc = self.storyboard?.instantiateViewControllerWithIdentifier("webViewController") as! WebViewController wvc.profile = self.profile wvc.sessionId = self.sessionId self.presentViewController(wvc, animated: false, completion: nil) } func authWithServer() -> Bool { var sessionId = getSessionId(self.profile!) if(!sessionId.error.isEmpty) { errorMessage = "Invalid username or password. Please check and try again." self.sessionId = "" return(false) } else { self.sessionId = sessionId.success return(true) } } }
mit
c7f7584e1bafa086be9e7270e5108060
29.182432
117
0.454769
6.453757
false
false
false
false
gtranchedone/AlgorithmsSwift
Algorithms.playground/Pages/Problem - Remove and Replace.xcplaygroundpage/Contents.swift
1
1089
/*: [Previous](@previous) # Replace and remove ### Write a program which takes as input a string s, and removes each “b” and replaces each “a” with “dd”. Assume s is stored in an array that has enough spaces for the final result. */ // O(n) time and space. If space is already allocaded correcly, instead of iterating forward // we can iterate backwards and take O(n) time but O(1) space in other languages, but not in Swift as Arrays are values func replaceAndRemove(s: String) -> String { let oldChars = s.characters var newChars = String.CharacterView() var index = oldChars.startIndex while index < oldChars.endIndex { let currentChar = oldChars[index] if currentChar == "a" { newChars.append("d") newChars.append("d") } else if currentChar != "b" { newChars.append(currentChar) } index = index.successor() } return String(newChars) } replaceAndRemove("abcd") replaceAndRemove("bbbbbbbb") replaceAndRemove("aaa") replaceAndRemove("abcabcabc") //: [Next](@next)
mit
4036d22addcc79d8efab2c00cac15f08
32.65625
182
0.663881
4.003717
false
false
false
false
snailjj/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/Skills/ViewControllers/SystemServicesViewController.swift
2
5549
// // SystemServicesViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2016/12/6. // Copyright © 2016年 Snail. All rights reserved. // /* 调用系统内置的应用来发送短信、邮件相当简单,但是这么操作也存在着一些弊端:当你点击了发送短信(或邮件)操作之后直接启动了系统的短信(或邮件)应用程序, 我们的应用其实此时已经处于一种挂起状态,发送完(短信或邮件)之后无法自动回到应用界面。 如果想要在应用程序内部完成这些操作则可以利用iOS中的MessageUI.framework,它提供了关于短信和邮件的UI接口供开发者在应用程序内部调用。 从框架名称不难看出这是一套UI接口,提供有现成的短信和邮件的编辑界面,开发人员只需要通过编程的方式给短信和邮件控制器设置对应的参数即可。 在MessageUI.framework中主要有两个控制器类分别用于发送短信(MFMessageComposeViewController)和邮件(MFMailComposeViewController),它们均继承于UINavigationController。 发送短信和发送邮件的方式是一模一样的,会了发送短信,邮件也就会了。 */ import UIKit import MessageUI class SystemServicesViewController: CustomViewController,MFMessageComposeViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* MARK: - 发送信息 1.创建MFMessageComposeViewController对象。 2.设置收件人recipients、信息正文body,如果运行商支持主题和附件的话可以设置主题subject、附件attachments(可以通 过canSendSubject、canSendAttachments方法判断是否支持) 3.设置代理messageComposeDelegate(注意这里不是delegate属性,因为delegate属性已经留给UINavigationController, MFMessageComposeViewController没有覆盖此属性而是重新定义了一个代理),实现代理方法获得发送状态。 4.可以通过几种方式来指定发送的附件,在这个过程中请务必指定文件的后缀,否则在发送后无法正确识别文件类别(例如如果发送的是一张jpg图片, 在发送后无法正确查看图片)。 */ @IBAction func sendMessage(_ sender: UIButton) { let phoneNumber = "15265348716" let content = "Snail" let subject = "Hello" if MFMessageComposeViewController.canSendText() { let messageController = MFMessageComposeViewController() messageController.recipients = [phoneNumber] messageController.body = content messageController.messageComposeDelegate = self if MFMessageComposeViewController.canSendSubject() { messageController.subject = subject } //TODO:判断是否能添加附件 if MFMessageComposeViewController.canSendAttachments() { /* TODO:添加附件 第一种方法:messageController.attachments = ... */ /*第二种方法*/ let attachmesths = ["/user/dsa.png","sda.ipa"] if attachmesths.count > 0{ try? attachmesths.forEach({ (s) in let path = Bundle.main.path(forResource: s, ofType: nil) let url = URL.init(fileURLWithPath: path!) messageController.addAttachmentURL(url as URL, withAlternateFilename: s) }) } /* 第三种方法 */ let path = Bundle.main.path(forResource: "/Snail/sad.ipa", ofType: nil) let url = URL.init(fileURLWithPath: path!) let data = NSData.init(contentsOfFile: "") /* 第一个参数:文件数据 第二个参数:统一类型标识,标识文件类型,Declared Uniform Type Identifiers 第三个参数:展现给用户看的文件名称 */ messageController.addAttachmentData(data as! Data, typeIdentifier: "", filename: "photo.jpg") } self.present(messageController, animated: true, completion: { print("。。。。") }) } } //MFMessageComposeViewControllerDelegate methods func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { switch result { case .cancelled: print("取消发送") case .sent: print("发送完成") default: print("出错了") } self.dismiss(animated: true, completion: { }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
84399a9bd42470ea891c9ff36c3515cc
34.354839
133
0.614279
4.464358
false
false
false
false
hooman/swift
test/decl/class/effectful_properties.swift
4
2531
// RUN: %target-typecheck-verify-swift -disable-availability-checking enum E : Error { case NotAvailable } class GolfCourse { var yards : Int { get throws { throw E.NotAvailable } } var holes : Int { get { 18 } } var par : Int { get async throws { 71 } } subscript(_ i : Int) -> Int { get throws { throw E.NotAvailable } } } class Presidio : GolfCourse { private var yardsFromBackTees = 6481 override var yards : Int { // removes effect & makes it mutable get { do { return try super.yards } catch { return yardsFromBackTees } } set { yardsFromBackTees = newValue } } override var holes : Int { // expected-error {{cannot override non-async property with async property}} get async { 18 } } override var par : Int { get async { 72 } // removes the 'throws' effect } override subscript(_ i : Int) -> Int { // removes effects get { (try? super[i]) ?? 3 } } } class PresidioBackNine : Presidio { override var par : Int { // expected-error{{cannot override non-throwing property with throwing property}} get throws { 36 } // attempts to put the 'throws' effect back } override subscript(_ i : Int) -> Int { // expected-error{{cannot override non-async subscript with async subscript}} get async throws { 0 } } } func timeToPlay(gc : Presidio) async { _ = gc.yards _ = (gc as GolfCourse).yards // expected-error{{property access can throw, but it is not marked with 'try' and the error is not handled}} _ = try? (gc as GolfCourse).yards // expected-error@+3 {{property access can throw, but it is not marked with 'try' and the error is not handled}} // expected-error@+2 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@+1:7{{property access is 'async'}} _ = (gc as GolfCourse).par _ = try? await (gc as GolfCourse).par _ = await gc.par _ = gc[2] _ = (gc as GolfCourse)[2] // expected-error{{subscript access can throw, but it is not marked with 'try' and the error is not handled}} _ = try? (gc as GolfCourse)[2] } class AcceptableDynamic { dynamic var par : Int { get async throws { 60 } } dynamic subscript(_ i : Int) -> Int { get throws { throw E.NotAvailable } } } // mainly just some sanity checks class Misc { // expected-error@+2 {{'lazy' cannot be used on a computed property}} // expected-error@+1 {{lazy properties must have an initializer}} lazy var someProp : Int { get throws { 0 } } }
apache-2.0
af9902c3445f2834a9c71dae71fe0e4e
25.642105
139
0.638088
3.620887
false
false
false
false
AliSoftware/SwiftGen
Sources/SwiftGen/Commander/ParserCLICommands.swift
1
3160
// // SwiftGen // Copyright © 2020 SwiftGen // MIT Licence // import Commander import PathKit import StencilSwiftKit import SwiftGenCLI import SwiftGenKit extension ParserCLI { private enum CLIOption { // deprecated option static let deprecatedTemplateName = Option<String>( "template", default: "", flag: "t", description: """ DEPRECATED, use `--templateName` instead """ ) static func filter(for parser: ParserCLI) -> Option<String> { Option<String>( "filter", default: parser.parserType.defaultFilter, flag: "f", description: "The regular expression to filter input paths." ) } static func options(for parser: ParserCLI) -> VariadicOption<String> { VariadicOption<String>( "option", default: [], description: "List of parser options. \(parser.parserType.allOptions)" ) } static let params = VariadicOption<String>( "param", default: [], description: "List of template parameters" ) static let templateName = Option<String>( "templateName", default: "", flag: "n", description: """ The name of the template to use for code generation. \ See `swiftgen template list` for a list of available names """ ) static let templatePath = Option<String>( "templatePath", default: "", flag: "p", description: "The path of the template to use for code generation." ) } } extension ParserCLI { func command() -> CommandType { Commander.command( CLIOption.deprecatedTemplateName, CLIOption.templateName, CLIOption.templatePath, CLIOption.options(for: self), CLIOption.params, CLIOption.filter(for: self), OutputDestination.cliOption, Argument<[Path]>("PATH", description: self.pathDescription, validator: pathsExist) ) { oldTemplateName, templateName, templatePath, parserOptions, parameters, filter, output, paths in try ErrorPrettifier.execute { let options = try Parameters.parse(items: parserOptions) let parser = try self.parserType.init(options: options) { msg, _, _ in logMessage(.warning, msg) } let filter = try Filter(pattern: filter, options: parserType.filterOptions) try parser.searchAndParse(paths: paths, filter: filter) let resolvedTemplateName = templateName.isEmpty ? oldTemplateName : templateName let templateRef = try TemplateRef( templateShortName: resolvedTemplateName, templateFullPath: templatePath ) let templateRealPath = try templateRef.resolvePath(forParser: self) let template = try StencilSwiftTemplate( templateString: templateRealPath.read(), environment: stencilSwiftEnvironment() ) let context = parser.stencilContext() let enriched = try StencilContext.enrich(context: context, parameters: parameters) let rendered = try template.render(enriched) try output.write(content: rendered, onlyIfChanged: true) } } } }
mit
fcd97bd8175b52f388a5a73ee0a059c4
28.523364
104
0.644824
4.645588
false
false
false
false
hooman/swift
stdlib/public/Concurrency/AsyncSequence.swift
4
19729
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift /// A type that provides asynchronous, sequential, iterated access to its /// elements. /// /// An `AsyncSequence` resembles the `Sequence` type --- offering a list of /// values you can step through one at a time --- and adds asynchronicity. An /// `AsyncSequence` may have all, some, or none of its values available when /// you first use it. Instead, you use `await` to receive values as they become /// available. /// /// As with `Sequence`, you typically iterate through an `AsyncSequence` with a /// `for await`-`in` loop. However, because the caller must potentially wait for values, /// you use the `await` keyword. The following example shows how to iterate /// over `Counter`, a custom `AsyncSequence` that produces `Int` values from /// `1` up to a `howHigh` value: /// /// for await i in Counter(howHigh: 10) { /// print(i, terminator: " ") /// } /// // Prints: 1 2 3 4 5 6 7 8 9 10 /// /// An `AsyncSequence` doesn't generate or contain the values; it just defines /// how you access them. Along with defining the type of values as an associated /// type called `Element`, the `AsyncSequence` defines a `makeAsyncIterator()` /// method. This returns an instance of type `AsyncIterator`. Like the standard /// `IteratorProtocol`, the `AsyncIteratorProtocol` defines a single `next()` /// method to produce elements. The difference is that the `AsyncIterator` /// defines its `next()` method as `async`, which requires a caller to wait for /// the next value with the `await` keyword. /// /// `AsyncSequence` also defines methods for processing the elements you /// receive, modeled on the operations provided by the basic `Sequence` in the /// standard library. There are two categories of methods: those that return a /// single value, and those that return another `AsyncSequence`. /// /// Single-value methods eliminate the need for a `for await`-`in` loop, and instead /// let you make a single `await` call. For example, the `contains(_:)` method /// returns a Boolean value that indicates if a given value exists in the /// `AsyncSequence`. Given the `Counter` sequence from the previous example, /// you can test for the existence of a sequence member with a one-line call: /// /// let found = await Counter(howHigh: 10).contains(5) // true /// /// Methods that return another `AsyncSequence` return a type specific to the /// method's semantics. For example, the `.map(_:)` method returns a /// `AsyncMapSequence` (or a `AsyncThrowingMapSequence`, if the closure you /// provide to the `map(_:)` method can throw an error). These returned /// sequences don't eagerly await the next member of the sequence, which allows /// the caller to decide when to start work. Typically, you'll iterate over /// these sequences with `for await`-`in`, like the base `AsyncSequence` you started /// with. In the following example, the `map(_:)` method transforms each `Int` /// received from a `Counter` sequence into a `String`: /// /// let stream = Counter(howHigh: 10) /// .map { $0 % 2 == 0 ? "Even" : "Odd" } /// for await s in stream { /// print(s, terminator: " ") /// } /// // Prints: Odd Even Odd Even Odd Even Odd Even Odd Even /// @available(SwiftStdlib 5.5, *) @rethrows public protocol AsyncSequence { /// The type of asynchronous iterator that produces elements of this /// asynchronous sequence. associatedtype AsyncIterator: AsyncIteratorProtocol where AsyncIterator.Element == Element /// The type of element produced by this asynchronous sequence. associatedtype Element /// Creates the asynchronous iterator that produces elements of this /// asynchronous sequence. /// /// - Returns: An instance of the `AsyncIterator` type used to produce /// elements of the asynchronous sequence. __consuming func makeAsyncIterator() -> AsyncIterator } @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns the result of combining the elements of the asynchronous sequence /// using the given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements of /// an entire sequence. For example, you can use this method on an sequence of /// numbers to find their sum or product. /// /// The `nextPartialResult` closure executes sequentially with an accumulating /// value initialized to `initialResult` and each element of the sequence. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `4`. The `reduce(_:_:)` method sums the values /// received from the asynchronous sequence. /// /// let sum = await Counter(howHigh: 4) /// .reduce(0) { /// $0 + $1 /// } /// print(sum) /// // Prints: 10 /// /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// The `nextPartialResult` closure receives `initialResult` the first /// time the closure runs. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the asynchronous sequence into a new accumulating value, /// for use in the next call of the `nextPartialResult` closure or /// returned to the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) async throws -> Result ) async rethrows -> Result { var accumulator = initialResult var iterator = makeAsyncIterator() while let element = try await iterator.next() { accumulator = try await nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the asynchronous sequence /// using the given closure, given a mutable initial value. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on a /// sequence of numbers to find their sum or product. /// /// The `nextPartialResult` closure executes sequentially with an accumulating /// value initialized to `initialResult` and each element of the sequence. /// /// Prefer this method over `reduce(_:_:)` for efficiency when the result is /// a copy-on-write type, for example an `Array` or `Dictionary`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// The `nextPartialResult` closure receives `initialResult` the first /// time the closure executes. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the asynchronous sequence into a new accumulating value, /// for use in the next call of the `nextPartialResult` closure or /// returned to the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. @inlinable public func reduce<Result>( into initialResult: __owned Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) async throws -> Void ) async rethrows -> Result { var accumulator = initialResult var iterator = makeAsyncIterator() while let element = try await iterator.next() { try await updateAccumulatingResult(&accumulator, element) } return accumulator } } @available(SwiftStdlib 5.5, *) @inlinable @inline(__always) func _contains<Source: AsyncSequence>( _ self: Source, where predicate: (Source.Element) async throws -> Bool ) async rethrows -> Bool { for try await element in self { if try await predicate(element) { return true } } return false } @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns a Boolean value that indicates whether the asynchronous sequence /// contains an element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that doesn’t /// conform to the `Equatable` protocol, or to find an element that satisfies /// a general condition. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `contains(where:)` method checks to see /// whether the sequence produces a value divisible by `3`: /// /// let containsDivisibleByThree = await Counter(howHigh: 10) /// .contains { $0 % 3 == 0 } /// print(containsDivisibleByThree) /// // Prints: true /// /// The predicate executes each time the asynchronous sequence produces an /// element, until either the predicate finds a match or the sequence ends. /// /// - Parameter predicate: A closure that takes an element of the asynchronous /// sequence as its argument and returns a Boolean value that indicates /// whether the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// predicate; otherwise, `false`. @inlinable public func contains( where predicate: (Element) async throws -> Bool ) async rethrows -> Bool { return try await _contains(self, where: predicate) } /// Returns a Boolean value that indicates whether all elements produced by the /// asynchronous sequence satisfies the given predicate. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `allSatisfy(_:)` method checks to see whether /// all elements produced by the sequence are less than `10`. /// /// let allLessThanTen = await Counter(howHigh: 10) /// .allSatisfy { $0 < 10 } /// print(allLessThanTen) /// // Prints: false /// /// The predicate executes each time the asynchronous sequence produces an /// element, until either the predicate returns `false` or the sequence ends. /// /// - Parameter predicate: A closure that takes an element of the asynchronous /// sequence as its argument and returns a Boolean value that indicates /// whether the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. @inlinable public func allSatisfy( _ predicate: (Element) async throws -> Bool ) async rethrows -> Bool { return try await !contains { try await !predicate($0) } } } @available(SwiftStdlib 5.5, *) extension AsyncSequence where Element: Equatable { /// Returns a Boolean value that indicates whether the asynchronous sequence /// contains the given element. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `contains(_:)` method checks to see whether /// the sequence produces the value `5`: /// /// let containsFive = await Counter(howHigh: 10) /// .contains(5) /// print(containsFive) /// // Prints: true /// /// - Parameter search: The element to find in the asynchronous sequence. /// - Returns: `true` if the method found the element in the asynchronous /// sequence; otherwise, `false`. @inlinable public func contains(_ search: Element) async rethrows -> Bool { for try await element in self { if element == search { return true } } return false } } @available(SwiftStdlib 5.5, *) @inlinable @inline(__always) func _first<Source: AsyncSequence>( _ self: Source, where predicate: (Source.Element) async throws -> Bool ) async rethrows -> Source.Element? { for try await element in self { if try await predicate(element) { return element } } return nil } @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `first(where:)` method returns the first /// member of the sequence that's evenly divisible by both `2` and `3`. /// /// let divisibleBy2And3 = await Counter(howHigh: 10) /// .first { $0 % 2 == 0 && $0 % 3 == 0 } /// print(divisibleBy2And3 ?? "none") /// // Prints: 6 /// /// The predicate executes each time the asynchronous sequence produces an /// element, until either the predicate finds a match or the sequence ends. /// /// - Parameter predicate: A closure that takes an element of the asynchronous /// sequence as its argument and returns a Boolean value that indicates /// whether the element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. @inlinable public func first( where predicate: (Element) async throws -> Bool ) async rethrows -> Element? { return try await _first(self, where: predicate) } } @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns the minimum element in the asynchronous sequence, using the given /// predicate as the comparison between elements. /// /// Use this method when the asynchronous sequence's values don't conform /// to `Comparable`, or when you want to apply a custom ordering to the /// sequence. /// /// The predicate must be a *strict weak ordering* over the elements. That is, /// for any elements `a`, `b`, and `c`, the following conditions must hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The following example uses an enumeration of playing cards ranks, `Rank`, /// which ranges from `ace` (low) to `king` (high). An asynchronous sequence /// called `RankCounter` produces all elements of the array. The predicate /// provided to the `min(by:)` method sorts ranks based on their `rawValue`: /// /// enum Rank: Int { /// case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king /// } /// /// let min = await RankCounter() /// .min { $0.rawValue < $1.rawValue } /// print(min ?? "none") /// // Prints: ace /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: The sequence’s minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns `nil`. @inlinable @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) async throws -> Bool ) async rethrows -> Element? { var it = makeAsyncIterator() guard var result = try await it.next() else { return nil } while let e = try await it.next() { if try await areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the asynchronous sequence, using the given /// predicate as the comparison between elements. /// /// Use this method when the asynchronous sequence's values don't conform /// to `Comparable`, or when you want to apply a custom ordering to the /// sequence. /// /// The predicate must be a *strict weak ordering* over the elements. That is, /// for any elements `a`, `b`, and `c`, the following conditions must hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The following example uses an enumeration of playing cards ranks, `Rank`, /// which ranges from `ace` (low) to `king` (high). An asynchronous sequence /// called `RankCounter` produces all elements of the array. The predicate /// provided to the `max(by:)` method sorts ranks based on their `rawValue`: /// /// enum Rank: Int { /// case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king /// } /// /// let max = await RankCounter() /// .max { $0.rawValue < $1.rawValue } /// print(max ?? "none") /// // Prints: king /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: The sequence’s minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns `nil`. @inlinable @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) async throws -> Bool ) async rethrows -> Element? { var it = makeAsyncIterator() guard var result = try await it.next() else { return nil } while let e = try await it.next() { if try await areInIncreasingOrder(result, e) { result = e } } return result } } @available(SwiftStdlib 5.5, *) extension AsyncSequence where Element: Comparable { /// Returns the minimum element in an asynchronous sequence of comparable /// elements. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `min()` method returns the minimum value /// of the sequence. /// /// let min = await Counter(howHigh: 10) /// .min() /// print(min ?? "none") /// // Prints: 1 /// /// - Returns: The sequence’s minimum element. If the sequence has no /// elements, returns `nil`. @inlinable @warn_unqualified_access public func min() async rethrows -> Element? { return try await self.min(by: <) } /// Returns the maximum element in an asynchronous sequence of comparable /// elements. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `max()` method returns the max value /// of the sequence. /// /// let max = await Counter(howHigh: 10) /// .max() /// print(max ?? "none") /// // Prints: 10 /// /// - Returns: The sequence’s maximum element. If the sequence has no /// elements, returns `nil`. @inlinable @warn_unqualified_access public func max() async rethrows -> Element? { return try await self.max(by: <) } }
apache-2.0
00b7bd0b80770724b1862dd631900f04
40.167015
99
0.662762
4.376165
false
false
false
false
nathanlea/CS4153MobileAppDev
Daily Stuff/DrawTest/DrawTest/MyView.swift
1
3391
// // MyView.swift // DrawTest // // Created by Blayne Mayfield on 9/1/15. // Copyright © 2015 Oklahoma State University. All rights reserved. // import UIKit class MyView: UIView { override func drawRect(rect: CGRect) { // Load the contents of the image file. if let myImage = UIImage(named: "LilPete.png") { // Draw at center of display. let p = CGPoint(x: (self.bounds.size.width - myImage.size.width) / 2, y:(self.bounds.size.height - myImage.size.height) / 2) myImage.drawAtPoint(p) //// Draw in upper-left corner, 1/2 width let rect = CGRect(x: 0, y: 0, width: myImage.size.width / 2, height: myImage.size.height) myImage.drawInRect(rect) } else { NSLog("No image file found") } //============================= let colorOrange = UIColor(red: 1.0, green: 0.65, blue: 0.0, alpha: 1.0) /*if*/ let context = UIGraphicsGetCurrentContext() //{ // Save the current context. CGContextSaveGState(context) CGContextSetFillColorWithColor(context, colorOrange.CGColor) CGContextSetStrokeColorWithColor(context, colorOrange.CGColor) // Create an array of points defining a triangle. let pointsTriangle = [ CGPoint(x:self.bounds.size.width / 2 - 50, y:200), CGPoint(x:self.bounds.size.width / 2 + 50, y:200), CGPoint(x:self.bounds.size.width / 2, y:50) ] // Create an empty path. let path = CGPathCreateMutable() // Move to the first point in the path. CGPathMoveToPoint(path, nil, pointsTriangle[0].x, pointsTriangle[0].y) // Add the other points to the path. CGPathAddLineToPoint(path, nil, pointsTriangle[1].x, pointsTriangle[1].y) CGPathAddLineToPoint(path, nil, pointsTriangle[2].x, pointsTriangle[2].y) // Close the path. CGPathCloseSubpath(path) // Add the path to the context. CGContextAddPath(context, path) // Stroke and fill the path. CGContextFillPath(context) // Restore the saved context. CGContextRestoreGState(context) //} //============================= // The string to be drawn let text: NSString = "Pistol Pete" // The font to use. let font = UIFont(name: "Helvetica Bold", size: 14.0) // The paragraph style of the text. let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle // The alignment of the paragraph. textStyle.alignment = NSTextAlignment.Left if let actualFont = font { let textFontAttributes = [ NSFontAttributeName: actualFont, NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: textStyle ] // Draw the text in a rect. text.drawInRect(CGRect(x:50, y:320, width:125, height:18), withAttributes: textFontAttributes) } } }
mit
eb141e9b08deb79d3f245ef83094a0ab
35.847826
113
0.546608
4.849785
false
false
false
false
dvaughn1712/perfect-routing
PerfectLib/NetTCPSSL.swift
1
13613
// // NetTCPSSL.swift // PerfectLib // // Created by Kyle Jessup on 2015-09-23. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import OpenSSL private typealias passwordCallbackFunc = @convention(c) (UnsafeMutablePointer<Int8>, Int32, Int32, UnsafeMutablePointer<Void>) -> Int32 public class NetTCPSSL : NetTCP { public static var opensslVersionText : String { return OPENSSL_VERSION_TEXT } public static var opensslVersionNumber : Int { return OPENSSL_VERSION_NUMBER } public class X509 { private let ptr: UnsafeMutablePointer<OpenSSL.X509> init(ptr: UnsafeMutablePointer<OpenSSL.X509>) { self.ptr = ptr } deinit { X509_free(self.ptr) } public var publicKeyBytes: [UInt8] { let pk = X509_get_pubkey(self.ptr) let len = Int(i2d_PUBKEY(pk, nil)) var mp = UnsafeMutablePointer<UInt8>.init(nilLiteral: ()) defer { free(mp) EVP_PKEY_free(pk) } i2d_PUBKEY(pk, &mp) var ret = [UInt8]() ret.reserveCapacity(len) for b in 0..<len { ret.append(mp[b]) } return ret } } static var dispatchOnce = Threading.ThreadOnce() private var sharedSSLCtx = true private var sslCtx: UnsafeMutablePointer<SSL_CTX>? private var ssl: UnsafeMutablePointer<SSL>? public var keyFilePassword: String = "" { didSet { if !self.keyFilePassword.isEmpty { self.initSocket() let opaqueMe = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self).toOpaque()) let callback: passwordCallbackFunc = { (buf, size, rwflag, userData) -> Int32 in let crl = Unmanaged<NetTCPSSL>.fromOpaque(COpaquePointer(userData)).takeUnretainedValue() return crl.passwordCallback(buf, size: size, rwflag: rwflag) } SSL_CTX_set_default_passwd_cb_userdata(self.sslCtx!, opaqueMe) SSL_CTX_set_default_passwd_cb(self.sslCtx!, callback) } } } public var peerCertificate: X509? { guard let ssl = self.ssl else { return nil } let cert = SSL_get_peer_certificate(ssl) if cert != nil { return X509(ptr: cert) } return nil } public var cipherList: [String] { get { var a = [String]() guard let ssl = self.ssl else { return a } var i = Int32(0) while true { let n = SSL_get_cipher_list(ssl, i) if n != nil { a.append(String.fromCString(n)!) } else { break } i += 1 } return a } set(list) { let listStr = list.joinWithSeparator(",") if let ctx = self.sslCtx { if 0 == SSL_CTX_set_cipher_list(ctx, listStr) { print("SSL_CTX_set_cipher_list failed: \(self.errorStr(Int32(self.errorCode())))") } } if let ssl = self.ssl { if 0 == SSL_set_cipher_list(ssl, listStr) { print("SSL_CTX_set_cipher_list failed: \(self.errorStr(Int32(self.errorCode())))") } } } } public func setTmpDH(path: String) -> Bool { guard let ctx = self.sslCtx else { return false } let bio = BIO_new_file(path, "r") if bio == nil { return false } let dh = PEM_read_bio_DHparams(bio, nil, nil, nil) SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_DH, 0, dh) DH_free(dh) BIO_free(bio) return true } public var usingSSL: Bool { return self.ssl != nil } public override init() { super.init() Threading.once(&NetTCPSSL.dispatchOnce) { SSL_library_init() ERR_load_crypto_strings() SSL_load_error_strings() } } deinit { if let ssl = self.ssl { SSL_shutdown(ssl) SSL_free(ssl) } if let sslCtx = self.sslCtx where self.sharedSSLCtx == false { SSL_CTX_free(sslCtx) } } func passwordCallback(buf:UnsafeMutablePointer<Int8>, size:Int32, rwflag:Int32) -> Int32 { let chars = self.keyFilePassword.utf8 memmove(buf, self.keyFilePassword, chars.count + 1) return Int32(chars.count) } override public func initSocket() { super.initSocket() guard self.sslCtx == nil else { return } self.sslCtx = SSL_CTX_new(TLSv1_2_method()) guard let sslCtx = self.sslCtx else { return } self.sharedSSLCtx = false SSL_CTX_ctrl(sslCtx, SSL_CTRL_SET_ECDH_AUTO, 1, nil) SSL_CTX_ctrl(sslCtx, SSL_CTRL_MODE, SSL_MODE_AUTO_RETRY, nil) SSL_CTX_ctrl(sslCtx, SSL_CTRL_OPTIONS, SSL_OP_ALL, nil) } public func errorCode() -> UInt { let err = ERR_get_error() return err } public func sslErrorCode(resultCode: Int32) -> Int32 { if let ssl = self.ssl { let err = SSL_get_error(ssl, resultCode) return err } return -1 } public func errorStr(errorCode: Int32) -> String { let maxLen = 1024 let buf = UnsafeMutablePointer<Int8>.alloc(maxLen) defer { buf.destroy() ; buf.dealloc(maxLen) } ERR_error_string_n(UInt(errorCode), buf, maxLen) let ret = String.fromCString(buf) ?? "" return ret } public func reasonErrorStr(errorCode: Int32) -> String { let buf = ERR_reason_error_string(UInt(errorCode)) let ret = String.fromCString(buf) ?? "" return ret } override func isEAgain(err: Int) -> Bool { if err == -1 && self.usingSSL { let sslErr = SSL_get_error(self.ssl!, Int32(err)) if sslErr != SSL_ERROR_SYSCALL { return sslErr == SSL_ERROR_WANT_READ || sslErr == SSL_ERROR_WANT_WRITE } } return super.isEAgain(err) } override func evWhatFor(operation: Int32) -> Int32 { if self.usingSSL { let sslErr = SSL_get_error(self.ssl!, -1) if sslErr == SSL_ERROR_WANT_READ { return EV_READ } else if sslErr == SSL_ERROR_WANT_WRITE { return EV_WRITE } } return super.evWhatFor(operation) } override func recv(buf: UnsafeMutablePointer<Void>, count: Int) -> Int { if self.usingSSL { let i = Int(SSL_read(self.ssl!, buf, Int32(count))) return i } return super.recv(buf, count: count) } override func send(buf: UnsafePointer<Void>, count: Int) -> Int { if self.usingSSL { let i = Int(SSL_write(self.ssl!, buf, Int32(count))) return i } return super.send(buf, count: count) } override func readBytesFullyIncomplete(into: ReferenceBuffer, read: Int, remaining: Int, timeoutSeconds: Double, completion: ([UInt8]?) -> ()) { guard usingSSL else { return super.readBytesFullyIncomplete(into, read: read, remaining: remaining, timeoutSeconds: timeoutSeconds, completion: completion) } var what = EV_WRITE let sslErr = SSL_get_error(self.ssl!, -1) if sslErr == SSL_ERROR_WANT_READ { what = EV_READ } let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: what, userData: nil) { (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_TIMEOUT) == 0 { self.readBytesFully(into, read: read, remaining: remaining, timeoutSeconds: timeoutSeconds, completion: completion) } else { completion(nil) // timeout or error } } event.add() } override func writeBytesIncomplete(nptr: UnsafeMutablePointer<UInt8>, wrote: Int, length: Int, completion: (Int) -> ()) { guard usingSSL else { return super.writeBytesIncomplete(nptr, wrote: wrote, length: length, completion: completion) } var what = EV_WRITE let sslErr = SSL_get_error(self.ssl!, -1) if sslErr == SSL_ERROR_WANT_READ { what = EV_READ } let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: what, userData: nil) { [weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in self?.writeBytes(nptr, wrote: wrote, length: length, completion: completion) } event.add() } public override func close() { if let ssl = self.ssl { SSL_shutdown(ssl) SSL_free(ssl) self.ssl = nil } if let sslCtx = self.sslCtx where self.sharedSSLCtx == false { SSL_CTX_free(sslCtx) } self.sslCtx = nil super.close() } public func beginSSL(closure: (Bool) -> ()) { self.beginSSL(5.0, closure: closure) } public func beginSSL(timeout: Double, closure: (Bool) -> ()) { guard self.fd.fd != invalidSocket else { closure(false) return } if self.ssl == nil { self.ssl = SSL_new(self.sslCtx!) SSL_set_fd(self.ssl!, self.fd.fd) } guard let ssl = self.ssl else { closure(false) return } let res = SSL_connect(ssl) switch res { case 1: closure(true) case 0: closure(false) case -1: let sslErr = SSL_get_error(ssl, res) if sslErr == SSL_ERROR_WANT_WRITE { let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_WRITE, userData: nil) { [weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_WRITE) != 0 { self?.beginSSL(timeout, closure: closure) } else { closure(false) } } event.add(timeout) return } else if sslErr == SSL_ERROR_WANT_READ { let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_READ, userData: nil) { [weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_READ) != 0 { self?.beginSSL(timeout, closure: closure) } else { closure(false) } } event.add(timeout) return } else { closure(false) } default: closure(false) } } public func endSSL() { if let ssl = self.ssl { SSL_free(ssl) self.ssl = nil } if let sslCtx = self.sslCtx { SSL_CTX_free(sslCtx) self.sslCtx = nil } } public func shutdown() { if let ssl = self.ssl { SSL_shutdown(ssl) } } public func setConnectState() { if let ssl = self.ssl { SSL_set_connect_state(ssl) } } public func setAcceptState() { if let ssl = self.ssl { SSL_set_accept_state(ssl) } } public func setDefaultVerifyPaths() -> Bool { self.initSocket() guard let sslCtx = self.sslCtx else { return false } let r = SSL_CTX_set_default_verify_paths(sslCtx) return r == 1 } public func setVerifyLocations(caFilePath: String, caDirPath: String) -> Bool { self.initSocket() guard let sslCtx = self.sslCtx else { return false } let r = SSL_CTX_load_verify_locations(sslCtx, caFilePath, caDirPath) return r == 1 } public func useCertificateFile(cert: String) -> Bool { self.initSocket() guard let sslCtx = self.sslCtx else { return false } let r = SSL_CTX_use_certificate_file(sslCtx, cert, SSL_FILETYPE_PEM) return r == 1 } public func useCertificateChainFile(cert: String) -> Bool { self.initSocket() guard let sslCtx = self.sslCtx else { return false } let r = SSL_CTX_use_certificate_chain_file(sslCtx, cert) return r == 1 } public func usePrivateKeyFile(cert: String) -> Bool { self.initSocket() guard let sslCtx = self.sslCtx else { return false } let r = SSL_CTX_use_PrivateKey_file(sslCtx, cert, SSL_FILETYPE_PEM) return r == 1 } public func checkPrivateKey() -> Bool { self.initSocket() guard let sslCtx = self.sslCtx else { return false } let r = SSL_CTX_check_private_key(sslCtx) return r == 1 } override func makeFromFd(fd: Int32) -> NetTCP { return NetTCPSSL(fd: fd) } override public func forEachAccept(callBack: (NetTCP?) -> ()) { super.forEachAccept { [unowned self] (net:NetTCP?) -> () in if let netSSL = net as? NetTCPSSL { netSSL.sslCtx = self.sslCtx netSSL.ssl = SSL_new(self.sslCtx!) SSL_set_fd(netSSL.ssl!, netSSL.fd.fd) self.finishAccept(-1, net: netSSL, callBack: callBack) } else { callBack(net) } } } override public func accept(timeoutSeconds: Double, callBack: (NetTCP?) -> ()) throws { try super.accept(timeoutSeconds, callBack: { [unowned self] (net:NetTCP?) -> () in if let netSSL = net as? NetTCPSSL { netSSL.sslCtx = self.sslCtx netSSL.ssl = SSL_new(self.sslCtx!) SSL_set_fd(netSSL.ssl!, netSSL.fd.fd) self.finishAccept(timeoutSeconds, net: netSSL, callBack: callBack) } else { callBack(net) } }) } func finishAccept(timeoutSeconds: Double, net: NetTCPSSL, callBack: (NetTCP?) -> ()) { let res = SSL_accept(net.ssl!) let sslErr = SSL_get_error(net.ssl!, res) if res == -1 { if sslErr == SSL_ERROR_WANT_WRITE { let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: net.fd.fd, what: EV_WRITE, userData: nil) { (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_TIMEOUT) != 0 { callBack(nil) } else { self.finishAccept(timeoutSeconds, net: net, callBack: callBack) } } event.add(timeoutSeconds) } else if sslErr == SSL_ERROR_WANT_READ { let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: net.fd.fd, what: EV_READ, userData: nil) { (fd:Int32, w:Int16, ud:AnyObject?) -> () in if (Int32(w) & EV_TIMEOUT) != 0 { callBack(nil) } else { self.finishAccept(timeoutSeconds, net: net, callBack: callBack) } } event.add(timeoutSeconds) } else { callBack(nil) } } else { callBack(net) } } // private func throwSSLNetworkError(err: Int32) throws { // if err != 0 { // let maxLen = 1024 // let buf = UnsafeMutablePointer<Int8>.alloc(maxLen) // defer { // buf.destroy() ; buf.dealloc(maxLen) // } // ERR_error_string_n(self.sslErrorCode, buf, maxLen) // let msg = String.fromCString(buf) ?? "" // // print("SSL NetworkError: \(err) \(msg)") // // throw PerfectError.NetworkError(err, msg) // } // } }
unlicense
2235db08147c4c7fee1bb12eb6fa73bb
23.439856
145
0.631749
2.940808
false
false
false
false
dansbastian/iOS-Swift-MVVM
iOS-Swift-MVVM/Core/API/Services.swift
1
1259
// // Services.swift // Research-UnitTest // // Created by Alfian on 9/23/16. // Copyright © 2016 Alfian. All rights reserved. // import Alamofire import SwiftyJSON import Foundation typealias callBackError = (Error) -> Void class Services { //MARK: ATTRIBUTES static let apiClient = AFApiClient() static let BASE_URL = "https://movies-v2.api-fetch.website/" static let API_MOVIE_PROVIDER = "movies/" //MARK: GET - //MARK: Movie List typealias callBackMovieData = ([MovieData]) -> Void static func getMovieList(intpage: Int? = nil, onSuccess: callBackMovieData? = nil, onError: callBackError? = nil){ var urlString = "\(BASE_URL)\(API_MOVIE_PROVIDER)" if let _intPage = intpage { urlString = "\(urlString)\(_intPage)" } self.apiClient.request(httpMethod: .get, urlString: urlString) { (result) in let (jsonData,error) = result var arrMovieData = [MovieData]() if let _jsonData = jsonData { for data in _jsonData.arrayValue { arrMovieData.append(MovieData(jsonData: data)) } onSuccess?(arrMovieData) }else { onError?(error!) } } } //MARK: TV Show List //MARK: - POST }
mit
b39e3f4e39058cfea69eab9b8a232738
20.689655
116
0.613672
3.919003
false
false
false
false
danielallsopp/Charts
Source/Charts/Charts/RadarChartView.swift
15
7200
// // RadarChartView.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/Charts // import Foundation import CoreGraphics /// Implementation of the RadarChart, a "spidernet"-like chart. It works best /// when displaying 5-10 entries per DataSet. public class RadarChartView: PieRadarChartViewBase { /// width of the web lines that come from the center. public var webLineWidth = CGFloat(1.5) /// width of the web lines that are in between the lines coming from the center public var innerWebLineWidth = CGFloat(0.75) /// color for the web lines that come from the center public var webColor = NSUIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0) /// color for the web lines in between the lines that come from the center. public var innerWebColor = NSUIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0) /// transparency the grid is drawn with (0.0 - 1.0) public var webAlpha: CGFloat = 150.0 / 255.0 /// flag indicating if the web lines should be drawn or not public var drawWeb = true /// modulus that determines how many labels and web-lines are skipped before the next is drawn private var _skipWebLineCount = 0 /// the object reprsenting the y-axis labels private var _yAxis: ChartYAxis! internal var _yAxisRenderer: ChartYAxisRendererRadarChart! internal var _xAxisRenderer: ChartXAxisRendererRadarChart! public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() _yAxis = ChartYAxis(position: .Left) _xAxis.spaceBetweenLabels = 0 renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) _yAxisRenderer = ChartYAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self) _xAxisRenderer = ChartXAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self) } internal override func calcMinMax() { super.calcMinMax() guard let data = _data else { return } // calculate / set x-axis range _xAxis._axisMaximum = Double(data.xVals.count) - 1.0 _xAxis.axisRange = Double(abs(_xAxis._axisMaximum - _xAxis._axisMinimum)) _yAxis.calculate(min: data.getYMin(.Left), max: data.getYMax(.Left)) } public override func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let angle = self.sliceAngle * CGFloat(entry.xIndex) + self.rotationAngle let val = CGFloat(entry.value) * self.factor let c = self.centerOffsets let p = CGPoint(x: c.x + val * cos(angle * ChartUtils.Math.FDEG2RAD), y: c.y + val * sin(angle * ChartUtils.Math.FDEG2RAD)) return p } public override func notifyDataSetChanged() { calcMinMax() _yAxis?._defaultValueFormatter = _defaultValueFormatter _yAxisRenderer?.computeAxis(yMin: _yAxis._axisMinimum, yMax: _yAxis._axisMaximum) _xAxisRenderer?.computeAxis(xValAverageLength: data?.xValAverageLength ?? 0, xValues: data?.xVals ?? []) if let data = _data, legend = _legend where !legend.isLegendCustom { _legendRenderer?.computeLegend(data) } calculateOffsets() setNeedsDisplay() } public override func drawRect(rect: CGRect) { super.drawRect(rect) if _data === nil { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } _xAxisRenderer?.renderAxisLabels(context: context) if (drawWeb) { renderer!.drawExtras(context: context) } _yAxisRenderer.renderLimitLines(context: context) renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHighlight) } _yAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) drawMarkers(context: context) } /// - returns: the factor that is needed to transform values into pixels. public var factor: CGFloat { let content = _viewPortHandler.contentRect return min(content.width / 2.0, content.height / 2.0) / CGFloat(_yAxis.axisRange) } /// - returns: the angle that each slice in the radar chart occupies. public var sliceAngle: CGFloat { return 360.0 / CGFloat(_data?.xValCount ?? 0) } public override func indexForAngle(angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) let sliceAngle = self.sliceAngle for i in 0 ..< (_data?.xValCount ?? 0) { if (sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0 > a) { return i } } return 0 } /// - returns: the object that represents all y-labels of the RadarChart. public var yAxis: ChartYAxis { return _yAxis } /// Sets the number of web-lines that should be skipped on chart web before the next one is drawn. This targets the lines that come from the center of the RadarChart. /// if count = 1 -> 1 line is skipped in between public var skipWebLineCount: Int { get { return _skipWebLineCount } set { _skipWebLineCount = max(0, newValue) } } internal override var requiredLegendOffset: CGFloat { return _legend.font.pointSize * 4.0 } internal override var requiredBaseOffset: CGFloat { return _xAxis.isEnabled && _xAxis.isDrawLabelsEnabled ? _xAxis.labelRotatedWidth : 10.0 } public override var radius: CGFloat { let content = _viewPortHandler.contentRect return min(content.width / 2.0, content.height / 2.0) } /// - returns: the maximum value this chart can display on it's y-axis. public override var chartYMax: Double { return _yAxis._axisMaximum; } /// - returns: the minimum value this chart can display on it's y-axis. public override var chartYMin: Double { return _yAxis._axisMinimum; } /// - returns: the range of y-values this chart can display. public var yRange: Double { return _yAxis.axisRange} }
apache-2.0
3dfffbb4aaae38b7c060fad039e489f1
30.308696
170
0.625694
4.74621
false
false
false
false
halawata13/Golf
Golf/model/config/Column.swift
1
780
import Foundation class Column: ConfigItem { static let title = "列の数" static let defaultNumber = 5 let min = 1 let max = 6 var number: Int { didSet { if number < min || number > max { number = Column.defaultNumber } UserDefaults.standard.set(number, forKey: String(describing: type(of: Column.self))) } } var isMax: Bool { return number == max } var isMin: Bool { return number == min } init() { self.number = Column.get() } static func get() -> Int { let number = UserDefaults.standard.integer(forKey: String(describing: type(of: Column.self))) return number != 0 ? number : Column.defaultNumber } }
mit
c7758e965cda26cd0f583eed20e7119e
19.918919
101
0.550388
4.206522
false
false
false
false
openxc/openxc-ios-app-demo
openXCenabler/CommandsViewController.swift
1
16317
// // CommandsViewController.swift // openXCenabler // // Created by Kanishka, Vedi (V.) on 27/04/17. // Copyright (c) 2016 Ford Motor Company Licensed under the BSD license. // import UIKit import openXCiOSFramework class CommandsViewController:UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate { // the VM var vm: VehicleManager! var bm: BluetoothManager! var cm: Command! var ObjectDic : NSMutableDictionary = NSMutableDictionary() @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var responseLab: UILabel! @IBOutlet weak var busSeg: UISegmentedControl! @IBOutlet weak var enabSeg: UISegmentedControl! @IBOutlet weak var bypassSeg: UISegmentedControl! @IBOutlet weak var pFormatSeg: UISegmentedControl! @IBOutlet weak var busLabel: UILabel! @IBOutlet weak var enabledLabel: UILabel! @IBOutlet weak var bypassLabel: UILabel! @IBOutlet weak var formatLabel: UILabel! @IBOutlet weak var sendCmndButton: UIButton! @IBOutlet weak var acitivityInd: UIActivityIndicatorView! @IBOutlet weak var customCommandTF : UITextField! let commands = ["Version","Device Id","Passthrough CAN Mode","Acceptance Filter Bypass","Payload Format", "Platform", "RTC Config", "SD Card Status","Custom Command"] var versionResp: String! var deviceIdResp: String! var passthroughResp: String! var accFilterBypassResp: String! var payloadFormatResp: String! var platformResp: String! var rtcConfigResp: String! var sdCardResp: String! var customCommandResp: String! var isJsonFormat:Bool! var selectedRowInPicker: Int! override func viewDidLoad() { super.viewDidLoad() hideAll() customCommandTF.delegate = self acitivityInd.center = self.view.center acitivityInd.hidesWhenStopped = true acitivityInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge acitivityInd.isHidden = true // grab VM instance vm = VehicleManager.sharedInstance bm = BluetoothManager.sharedInstance cm = Command.sharedInstance // vm.setCommandDefaultTarget(self, action: CommandsViewController.handle_cmd_response) vm.setCommandDefaultTarget(self, action: CommandsViewController.handle_cmd_response) //vm.cmdObj?.setCommandDefaultTarget(self, action: CommandsViewController.handle_cmd_response) selectedRowInPicker = pickerView.selectedRow(inComponent: 0) //populateCommandResponseLabel(rowNum: selectedRowInPicker) // busSeg.addTarget(self, action: #selector(busSegmentedControlValueChanged), for: .valueChanged) // enabSeg.addTarget(self, action: #selector(enabSegmentedControlValueChanged), for: .valueChanged) //bypassSeg.addTarget(self, action: #selector(bypassSegmentedControlValueChanged), for: .valueChanged) // pFormatSeg.addTarget(self, action: #selector(formatSegmentedControlValueChanged), for: .valueChanged) isJsonFormat = vm.jsonMode } override func viewDidAppear(_ animated: Bool) { if(!bm.isBleConnected){ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage:errorMsgBLE) } } // MARK: Commands Function @IBAction func sendCmnd() { let sRow = pickerView.selectedRow(inComponent: 0) if(bm.isBleConnected){ if (sRow == 8 ){ if !vm.jsonMode{ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage: errorMsgcustomCommand) return } if(customCommandTF.text == nil||customCommandTF.text == ""){ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage: errorMsgforText) return } let str = customCommandTF.text! let stringq = str.description.replacingOccurrences(of: "\"", with: "") self.convertToJson(string: stringq) let jsonString = self.createJSON() let value = validJson(strValue: jsonString) if value{ let cm1 = VehicleCommandRequest() cm1.command = .custom_command cm.customCommand(jsonString: jsonString) showActivityIndicator() }else{ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage: errorMsgCustomCommand) } }else{ self.sendCommandWithValue(sRow: sRow) } }else{ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage: errorMsgBLE) } } func validJson(strValue:String) -> Bool { if (JSONSerialization.isValidJSONObject(ObjectDic)) { // print("Valid Json") return true } else { // print("InValid Json") return false } } func createJSON() -> String{ let jsonData = try? JSONSerialization.data(withJSONObject: ObjectDic, options: []) let jsonString = String(data: jsonData!, encoding: .utf8) print(jsonString as Any) return jsonString! } func convertDict(cleanedstring:String){ let searchCharacter: Character = "," let searchCharacter1: Character = ":" if cleanedstring.lowercased().characters.contains(searchCharacter) { let fullNameArr = cleanedstring.components(separatedBy: ",") for dataValue in fullNameArr{ if dataValue.lowercased().characters.contains(searchCharacter1) { let badchar = CharacterSet(charactersIn: "\"{}[]") let cleanedstring = dataValue.components(separatedBy: badchar).joined() let newString3 = cleanedstring.replacingOccurrences(of: "\"", with: "") let fullNameArr2 = newString3.components(separatedBy: ":") ObjectDic[fullNameArr2[0]] = fullNameArr2[1] } } print(ObjectDic) }else{ let fullNameArr2 = cleanedstring.components(separatedBy: ":") ObjectDic[fullNameArr2[0]] = fullNameArr2[1] print(ObjectDic) } } func convertToJson(string:String){ let trimmedString = string.trimmingCharacters(in: CharacterSet(charactersIn: "{}")) self.convertDict(cleanedstring: trimmedString) } func sendCommandWithValue(sRow:NSInteger){ let vcm = VehicleCommandRequest() switch sRow { case 0: //responseLab.text = "" vcm.command = .version self.cm.sendCommand(vcm) // activity indicator showActivityIndicator() break case 1: //responseLab.text = "" //let cm = VehicleCommandRequest() vcm.command = .device_id self.cm.sendCommand(vcm) // activity indicator showActivityIndicator() break case 2: //let cm = VehicleCommandRequest() // look at segmented control for bus vcm.bus = busSeg.selectedSegmentIndex + 1 if enabSeg.selectedSegmentIndex==0 { vcm.enabled = true } else { vcm.enabled = false } vcm.command = .passthrough self.cm.sendCommand(vcm) // activity indicator showActivityIndicator() break case 3: //let cm = VehicleCommandRequest() // look at segmented control for bus vcm.bus = busSeg.selectedSegmentIndex + 1 if bypassSeg.selectedSegmentIndex==0 { vcm.bypass = true } else { vcm.bypass = false } vcm.command = .af_bypass self.cm.sendCommand(vcm) showActivityIndicator() break case 4: //let cm = VehicleCommandRequest() if pFormatSeg.selectedSegmentIndex==0 { vcm.format = "json" } else { vcm.format = "protobuf" } vcm.command = .payload_format if !vm.jsonMode && pFormatSeg.selectedSegmentIndex==0{ self.cm.sendCommand(vcm) showActivityIndicator() } if vm.jsonMode && pFormatSeg.selectedSegmentIndex==1{ self.cm.sendCommand(vcm) showActivityIndicator() } break case 5: //let cm = VehicleCommandRequest() vcm.command = .platform self.cm.sendCommand(vcm) showActivityIndicator() break case 6: //let cm = VehicleCommandRequest() vcm.command = .rtc_configuration self.cm.sendCommand(vcm) showActivityIndicator() break case 7: //let cm = VehicleCommandRequest() vcm.command = .sd_mount_status self.cm.sendCommand(vcm) showActivityIndicator() break case 8: //let cm = VehicleCommandRequest() vcm.command = .custom_command self.cm.sendCommand(vcm) showActivityIndicator() break default: break } } // this function handles all command responses // this function handles all command responses func handle_cmd_response(_ rsp:NSDictionary) { // extract the command response message let cr = rsp.object(forKey: "vehiclemessage") as! VehicleCommandResponse // update the UI depending on the command type- version,device_id works for JSON mode, not in protobuf - TODO if cr.command_response.isEqual(to: "version") || cr.command_response.isEqual(to: ".version") { versionResp = cr.message as String } if cr.command_response.isEqual(to: "device_id") || cr.command_response.isEqual(to: ".deviceid"){ deviceIdResp = cr.message as String } if cr.command_response.isEqual(to: "passthrough") || cr.command_response.isEqual(to: ".passthrough"){ passthroughResp = String(cr.status) } if cr.command_response.isEqual(to: "af_bypass") || cr.command_response.isEqual(to: ".acceptancefilterbypass") { accFilterBypassResp = String(cr.status) } if cr.command_response.isEqual(to: "payload_format") || cr.command_response.isEqual(to: ".payloadformat") { if(cr.status){ if !vm.jsonMode && !isJsonFormat{ vm.setProtobufMode(false) UserDefaults.standard.set(false, forKey:"protobufOn") } if vm.jsonMode && isJsonFormat{ vm.setProtobufMode(true) UserDefaults.standard.set(true, forKey:"protobufOn") payloadFormatResp = String(cr.status) } } payloadFormatResp = String(cr.status) isJsonFormat = vm.jsonMode } if cr.command_response.isEqual(to: "platform") || cr.command_response.isEqual(to: ".platform"){ platformResp = cr.message as String } if cr.command_response.isEqual(to: "rtc_configuration") || cr.command_response.isEqual(to: ".rtcconfiguration") { rtcConfigResp = String(cr.status) } if cr.command_response.isEqual(to: "sd_mount_status") || cr.command_response.isEqual(to: ".sdmountstatus"){ sdCardResp = String(cr.status) }else{ customCommandResp = String(cr.message) } // update the label DispatchQueue.main.async { self.populateCommandResponseLabel(rowNum: self.selectedRowInPicker) } } // MARK: Picker Delgate Function func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return commands.count } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { var rowTitle:NSAttributedString! rowTitle = NSAttributedString(string: commands[row], attributes: [NSForegroundColorAttributeName : UIColor.white]) return rowTitle } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedRowInPicker = row populateCommandResponseLabel(rowNum: row) responseLab.text = "---" if (row == 8){ customCommandTF.isHidden = false }else{ customCommandTF.isHidden = true } } // MARK: UI Function func populateCommandResponseLabel(rowNum: Int) { hideAll() hideActivityIndicator() switch rowNum { case 0: sendCmndButton.isHidden = false responseLab.text = versionResp break case 1: sendCmndButton.isHidden = false responseLab.text = deviceIdResp break case 2: sendCmndButton.isHidden = false responseLab.text = passthroughResp busLabel.isHidden = false busSeg.isHidden = false enabledLabel.isHidden = false enabSeg.isHidden = false break case 3: sendCmndButton.isHidden = false responseLab.text = accFilterBypassResp busLabel.isHidden = false busSeg.isHidden = false bypassLabel.isHidden = false bypassSeg.isHidden = false break case 4: sendCmndButton.isHidden = false responseLab.text = payloadFormatResp formatLabel.isHidden = false pFormatSeg.isHidden = false break case 5: sendCmndButton.isHidden = false responseLab.text = platformResp break case 6: sendCmndButton.isHidden = false responseLab.text = rtcConfigResp break case 7: sendCmndButton.isHidden = false responseLab.text = sdCardResp break case 8: sendCmndButton.isHidden = false responseLab.text = customCommandResp break default: sendCmndButton.isHidden = true responseLab.text = versionResp } } func hideAll() { busSeg.isHidden = true enabSeg.isHidden = true bypassSeg.isHidden = true pFormatSeg.isHidden = true busLabel.isHidden = true enabledLabel.isHidden = true bypassLabel.isHidden = true formatLabel.isHidden = true } func showActivityIndicator() { acitivityInd.startAnimating() self.view.alpha = 0.5 self.view.isUserInteractionEnabled = false } func hideActivityIndicator() { acitivityInd.stopAnimating() self.view.alpha = 1.0 self.view.isUserInteractionEnabled = true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { customCommandTF.resignFirstResponder() return true } }
bsd-3-clause
a675c1781fb6da19886a425008b3acd8
33.643312
170
0.575841
5.137594
false
false
false
false
yinhaofrancis/SBHud
hud/HudPlain.swift
1
17926
// // HudPlainView.swift // hud // // Created by hao yin on 24/03/2017. // Copyright © 2017 hao yin. All rights reserved. // import UIKit // MARK:- plain public enum HudLayoutStyle{ case center(size:CGSize) case bottom(height:CGFloat,VerticleOffset:CGFloat,horizonOffset:CGFloat) case top(height:CGFloat,VerticleOffset:CGFloat,horizonOffset:CGFloat) case middle(height:CGFloat,HorizonOffset:CGFloat) case centerAuto(max:CGSize,min:CGSize) case bottomAuto(max:CGFloat,min:CGFloat,VerticleOffset:CGFloat,horizonOffset:CGFloat) case topAuto(max:CGFloat,min:CGFloat,VerticleOffset:CGFloat,horizonOffset:CGFloat) case middleAuto(max:CGFloat,min:CGFloat,HorizonOffset:CGFloat) } public protocol hock{ func start(contain:HudPlain) func stop(contain:HudPlain) } extension UIView:hock{ public func stop(contain: HudPlain) {} public func start(contain: HudPlain) {} public func time(time: CGFloat) {} } public class HudPlain:UIViewController{ public var content:(HudPlain)->UIView = {(self) in return UIView() } public var Constrait:(HudPlain,UIView)->(forself:[NSLayoutConstraint],forcontent:[NSLayoutConstraint]) = { (self,content) in let x = NSLayoutConstraint(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: content, attribute: .centerX, multiplier: 1, constant: 0) let y = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: content, attribute: .centerY, multiplier: 1, constant: 0) let w = NSLayoutConstraint(item: content, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 64) let h = NSLayoutConstraint(item: content, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 64) return(forself:[x,y],forcontent:[w,h]) } public var layoutStyle:HudLayoutStyle? public var Style:(HudPlain,UIView)->Void = {(_,content) in content.backgroundColor = UIColor.clear } public var animationShow:(HudPlain,UIView,((Bool) -> Void)?)->Void = {(self,content,complete) in self.view.alpha = 0 content.layer.position.y = 10 UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: { self.view.alpha = 1 content.layer.position.y = 0 }, completion: complete) } public var animationClose:(HudPlain,UIView,((Bool) -> Void)?)->Void = {(self,content:UIView,complete) in self.view.alpha = 1 UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: { self.view.alpha = 0 }, completion: complete) } public var useDefaultAnimation:Bool = false var contentView:UIView? func layerOut(){ let v = self.content(self) contentView = v self.view.addSubview(v) v.translatesAutoresizingMaskIntoConstraints = false if self.layoutStyle == nil{ let c = self.Constrait(self,v) self.view.addConstraints(c.forself) self.contentView?.addConstraints(c.forcontent) }else{ let c = self.makeConstraint(ls: self.layoutStyle!) self.view.addConstraints(c.forself) self.contentView?.addConstraints(c.forcontent) } self.Style(self,v) if let a = self.backgroudView(self,self.contentView!){ self.view.addSubview(a) self.view.sendSubview(toBack: a) a.frame = self.view.bounds a.autoresizingMask = [.flexibleWidth,.flexibleHeight] }else{ if let img = self.backgroundImage(self,self.contentView!){ (self.view as! UIImageView).image = img } } } private func makeConstraint(ls:HudLayoutStyle)->(forself:[NSLayoutConstraint],forcontent:[NSLayoutConstraint]){ switch ls { case let .center(size: size): let x = NSLayoutConstraint(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0) let y = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0) let w = NSLayoutConstraint(item: contentView!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: size.width) let h = NSLayoutConstraint(item: contentView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: size.height) return(forself:[x,y],forcontent:[w,h]) case let.bottom(height: he, VerticleOffset: v, horizonOffset: h): let t = NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: h) let h = NSLayoutConstraint(item: self.contentView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: h) let b = NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: self.contentView!, attribute: .bottom, multiplier: 1, constant: v) let height = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: he) return (forself:[t,h,b],forcontent:[height]) case let .top(height: he, VerticleOffset: v, horizonOffset: h): let t = NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: h) let h = NSLayoutConstraint(item: self.contentView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: h) let b = NSLayoutConstraint(item: self.contentView!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: v) let height = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: he) return (forself:[t,h,b],forcontent:[height]) case let .middle(height: height, HorizonOffset: h): let y = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: self.contentView!, attribute: .centerY, multiplier: 1, constant: 0) let l = NSLayoutConstraint(item: self.contentView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: h) let t = NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: h) let h = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: height) return ([y,l,t],[h]) case let .centerAuto(max: max, min: min): let x = NSLayoutConstraint(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0) let y = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0) let minw = NSLayoutConstraint(item: self.contentView!, attribute: .width, relatedBy:.greaterThanOrEqual, toItem: nil, attribute: .width, multiplier: 1, constant: min.width) let minh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: min.height) let maxw = NSLayoutConstraint(item: self.contentView!, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .width, multiplier: 1, constant: max.width) let maxh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: max.height) self.contentView?.setContentHuggingPriority(200, for: .horizontal) self.contentView?.setContentHuggingPriority(200, for: .vertical) return ([x,y],[minw,minh,maxh,maxw]) case let .bottomAuto(max: max, min: min, VerticleOffset: v, horizonOffset: h): let t = NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: h) let h = NSLayoutConstraint(item: self.contentView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: h) let b = NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: self.contentView!, attribute: .bottom, multiplier: 1, constant: v) let maxh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: max) let minh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: min) self.contentView?.setContentHuggingPriority(200, for: .vertical) return ([t,h,b],[maxh,minh]) case let .topAuto(max: max, min: min,VerticleOffset: v, horizonOffset: h): let t = NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: h) let h = NSLayoutConstraint(item: self.contentView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: h) let b = NSLayoutConstraint(item: self.contentView!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: v) let maxh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: max) let minh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: min) self.contentView?.setContentHuggingPriority(200, for: .vertical) return ([t,h,b],[maxh,minh]) case let .middleAuto(max: max, min: min,HorizonOffset: h): let y = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: self.contentView!, attribute: .centerY, multiplier: 1, constant: 0) let l = NSLayoutConstraint(item: self.contentView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: h) let t = NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: h) let maxh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: max) let minh = NSLayoutConstraint(item: self.contentView!, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .height, multiplier: 1, constant: min) self.contentView?.setContentHuggingPriority(200, for: .vertical) return([y,l,t],[maxh,minh]) } } override public func viewDidLoad() { super.viewDidLoad() self.layerOut() } public func showHud(from:UIViewController,delay:TimeInterval?,modal:Bool = true,completion: (() -> Void)? = nil){ guard (self.view.window == nil) else { return } self.modalPresentationStyle = modal ? .overFullScreen :.fullScreen from.present(self, animated: useDefaultAnimation) { self.contentView?.start(contain: self) completion?() } if let d = delay{ Timer.scheduledTimer(timeInterval: d, target: self, selector: #selector(innnerClose), userInfo: nil, repeats: false) } } public func showHud(from:UIViewController,completion: (() -> Void)? = nil){ showHud(from: from, delay: nil, modal: true, completion:completion) } public var backgroudView:(HudPlain,UIView)->UIView? = {hud,content in return nil } public var backgroundImage:(HudPlain,UIView)->UIImage? = {hud,content in return nil } func innnerClose() { closeHud() } public func closeHud(completion: (() -> Void)? = nil){ self.dismiss(animated: useDefaultAnimation) { self.contentView?.stop(contain: self) completion?() } } override public func viewWillAppear(_ animated: Bool) { self.animationShow(self,self.contentView!,nil) super.viewDidAppear(animated) } override public func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { self.animationClose(self, self.contentView!) { (i) in super.dismiss(animated: flag, completion: completion) } } public override func loadView() { self.view = UIImageView(); self.view.frame = UIScreen.main.bounds } init() { super.init(nibName: nil, bundle: nil) self.modalTransitionStyle = .crossDissolve } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public enum ProcessStyle{ case cirle case water } public class HudProcess:HudPlain{ public var process:CGFloat = 0{ didSet{ (self.contentView as! IndicateContainerView).CircleView.time(time: process) if process >= 1{ self.dismiss(animated: false) } } } } // MARK:- Maker public class HudPlainMaker:NSObject{ public func makeCenter(color:UIColor,stype:HudStyle)->HudPlain{ let hud = HudPlain() func make(style:HudStyle)->CenterHudContainerView{ switch style { case .warnning: return CenterHudContainerView(indicate: WarnningIndicateView.self) case .waitting: return CenterHudContainerView(indicate: CircleIndicateView.self) case .failure: return CenterHudContainerView(indicate: FailureIndicateView.self) case .success: return CenterHudContainerView(indicate: SuccessIndicateView.self) } } let c = make(style: stype) c.CircleView.color = color hud.content = {(_) in return c} hud.layoutStyle = HudLayoutStyle.center(size: CGSize(width: 96, height: 96)) c.image = makeImage return hud } public func makeMiddle(text:String,color:UIColor,style:HudStyle)->HudPlain{ let hud = HudPlain() func make(style:HudStyle)->MiddleHudContainerView{ switch style { case .warnning: return MiddleHudContainerView(indicate: WarnningIndicateView.self) case .waitting: return MiddleHudContainerView(indicate: CircleIndicateView.self) case .success: return MiddleHudContainerView(indicate: SuccessIndicateView.self) case .failure: return MiddleHudContainerView(indicate: FailureIndicateView.self) } } let c = make(style: style) c.CircleView.color = color c.label.text = text hud.content = { (_) in c} hud.Style = {$0.0.view.backgroundColor = UIColor.gray.withAlphaComponent(0.4)} hud.layoutStyle = HudLayoutStyle.middleAuto(max: 320, min: 80, HorizonOffset: 20) c.image = makeImage return hud } public func makeProcess(color:UIColor,style:ProcessStyle)->HudProcess{ let hud = HudProcess() func make(style:ProcessStyle)->baseIndicateView.Type{ switch style { case .cirle: return CircleProcessIndicateView.self case .water: return WaterProcessIndicateView.self } } let c = CenterHudContainerView(indicate: make(style: style)) hud.content = {(_) in return c} c.CircleView.color = color hud.layoutStyle = HudLayoutStyle.center(size: CGSize(width: 96, height: 96)) c.image = makeImage return hud } lazy var makeImage:UIImage = { UIGraphicsBeginImageContextWithOptions(CGSize(width:40,height:40), false, UIScreen.main.scale) let rect = CGRect(x: 4, y: 4, width: 32, height: 32) let p = UIBezierPath(roundedRect:rect , cornerRadius: 4) UIColor.white.setFill() let context = UIGraphicsGetCurrentContext() context?.setShadow(offset: CGSize(width:0,height:0), blur: 3, color: UIColor.black.withAlphaComponent(0.8).cgColor) p.fill() var image = UIGraphicsGetImageFromCurrentImageContext() image = image?.resizableImage(withCapInsets: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)) UIGraphicsEndImageContext() return image! }() public func makeTest()->HudPlain{ let hud = HudPlain() let l = UILabel() l.numberOfLines = 0 hud.content = {_ in l} l.text = "asdasdasdasdasdasdj asjd " hud.layoutStyle = HudLayoutStyle.centerAuto(max: CGSize(width:320,height:320), min: CGSize(width: 32, height: 32)) return hud } }
mit
844c9b984135c735935c040a7041c261
53.154079
188
0.653222
4.264811
false
false
false
false
AstronautSloth/Ultimate-Tic-Tac-Toe
Quantum Tic-Tac-Toe/ViewController.swift
1
5697
// // ViewController.swift // Quantum Tic-Tac-Toe // // Created by Colin Thompson on 9/19/15. // Copyright © 2015 Colin Thompson. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var matrix0: buttonMatrix! @IBOutlet weak var matrix1: buttonMatrix! @IBOutlet weak var matrix2: buttonMatrix! @IBOutlet weak var matrix3: buttonMatrix! @IBOutlet weak var matrix4: buttonMatrix! @IBOutlet weak var matrix5: buttonMatrix! @IBOutlet weak var matrix6: buttonMatrix! @IBOutlet weak var matrix7: buttonMatrix! @IBOutlet weak var matrix8: buttonMatrix! @IBOutlet weak var box0: NSBox! @IBOutlet weak var box1: NSBox! @IBOutlet weak var box2: NSBox! @IBOutlet weak var box3: NSBox! @IBOutlet weak var box4: NSBox! @IBOutlet weak var box5: NSBox! @IBOutlet weak var box6: NSBox! @IBOutlet weak var box7: NSBox! @IBOutlet weak var box8: NSBox! var turnNum = 0 var winner = "" override func viewDidLoad() { super.viewDidLoad() } override var representedObject: AnyObject? { didSet { } } func matrixArr() -> [buttonMatrix!] { let arr = [matrix0,matrix1,matrix2,matrix3,matrix4,matrix5,matrix6,matrix7,matrix8] return arr } func boxArr() -> [NSBox!] { let arr = [box0,box1,box2,box3,box4,box5,box6,box7,box8] return arr } @IBAction func buttonClicked(sender: buttonMatrix) { let selcell: NSButtonCell = sender.selectedCell() as! NSButtonCell if(turnNum % 2 == 0){ selcell.title = "X" selcell.enabled = false }else{ selcell.title = "O" selcell.enabled = false } turnNum++; let index = selcell.tag; sender.calculatewinner() let boxes = self.boxArr() if(sender.winner == "X"){ boxes[sender.tag].fillColor = NSColor(red: 0, green: 1, blue: 0, alpha: 0.25) boxes[sender.tag].transparent = false }else if(sender.winner == "O"){ boxes[sender.tag].fillColor = NSColor(red: 1, green: 0, blue: 0, alpha: 0.25) boxes[sender.tag].transparent = false } let arr = self.matrixArr() for matrix in arr{ if(matrix.tag == index){ matrix.enableButtons() }else{ matrix.disableButtons() } } if(arr[index].allButtonsDisabled()){ for matrix in arr{ matrix.enableButtons() } } self.isThereAWinner() if(self.isTie()){ let tieAlert = NSAlert() tieAlert.messageText = "It's a Draw!" tieAlert.informativeText = "Would you like to play again?" tieAlert.alertStyle = NSAlertStyle.WarningAlertStyle tieAlert.addButtonWithTitle("Restart") tieAlert.addButtonWithTitle("Quit") let res = tieAlert.runModal() if(res == NSAlertFirstButtonReturn){ self.restart() }else{ exit(0) } } if(winner != ""){ let winAlert = NSAlert() winAlert.messageText = "The winner is " + winner + "!" winAlert.informativeText = "Would you like to play again?" winAlert.alertStyle = NSAlertStyle.WarningAlertStyle winAlert.addButtonWithTitle("Restart") winAlert.addButtonWithTitle("Quit") let result = winAlert.runModal() if(result == NSAlertFirstButtonReturn){ self.restart() }else{ exit(0) } } } func isThereAWinner(){ if(matrix0.winner == matrix1.winner && matrix0.winner == matrix2.winner && matrix0.winner != ""){ winner = matrix0.winner; }else if(matrix3.winner == matrix4.winner && matrix3.winner == matrix5.winner && matrix3.winner != ""){ winner = matrix3.winner; }else if(matrix6.winner == matrix7.winner && matrix6.winner == matrix8.winner && matrix6.winner != ""){ winner = matrix6.winner; }else if(matrix0.winner == matrix3.winner && matrix0.winner == matrix6.winner && matrix0.winner != ""){ winner = matrix0.winner; }else if(matrix1.winner == matrix4.winner && matrix1.winner == matrix7.winner && matrix1.winner != ""){ winner = matrix1.winner; }else if(matrix2.winner == matrix5.winner && matrix2.winner == matrix8.winner && matrix2.winner != ""){ winner = matrix2.winner; }else if(matrix0.winner == matrix4.winner && matrix0.winner == matrix8.winner && matrix0.winner != ""){ winner = matrix0.winner; }else if(matrix2.winner == matrix4.winner && matrix2.winner == matrix6.winner && matrix2.winner != ""){ winner = matrix2.winner; } } func isTie() -> Bool { if(matrix0.winner != "" && matrix1.winner != "" && matrix2.winner != "" && matrix3.winner != "" && matrix4.winner != "" && matrix5.winner != "" && matrix6.winner != "" && matrix7.winner != "" && matrix8.winner != "" && self.winner == ""){ return true; }else{ return false } } func restart() { let matrices = matrixArr() let boxes = boxArr() self.turnNum = 0 self.winner = "" for(var i = 0; i < 9; i++){ boxes[i].transparent = true matrices[i].reset() } } }
mit
d1d1dafd4b29822f0a1eb41dd6856032
32.910714
246
0.552844
4.213018
false
false
false
false
practicalswift/swift
test/Driver/Dependencies/fail-interface-hash.swift
8
1524
/// main ==> depends-on-main | bad ==> depends-on-bad // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-interface-hash/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled main.swift // CHECK-FIRST: Handled bad.swift // CHECK-FIRST: Handled depends-on-main.swift // CHECK-FIRST: Handled depends-on-bad.swift // Reset the .swiftdeps files. // RUN: cp -r %S/Inputs/fail-interface-hash/*.swiftdeps %t // RUN: touch -t 201401240006 %t/bad.swift %t/main.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps // CHECK-SECOND: Handled main.swift // CHECK-SECOND-NOT: Handled depends // CHECK-SECOND: Handled bad.swift // CHECK-SECOND-NOT: Handled depends // CHECK-RECORD-DAG: "./bad.swift": !dirty [ // CHECK-RECORD-DAG: "./main.swift": [ // CHECK-RECORD-DAG: "./depends-on-main.swift": !dirty [ // CHECK-RECORD-DAG: "./depends-on-bad.swift": [
apache-2.0
de038524a9da90f0723bf2e83eabb5d5
49.8
303
0.694882
3.011858
false
false
true
false
martinschilliger/SwissGrid
SwissGrid/SettingsView.swift
1
6041
// // SettingsView.swift // SwissGrid // // Created by Martin Schilliger on 20.09.17. // Copyright © 2017 Martin Apps. All rights reserved. // import Foundation import UIKit class SettingsViewController: UITableViewController { @IBOutlet var settingsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Makes the title large (iOS11) => https://stackoverflow.com/a/44410330/1145706 if #available(iOS 11.0, *) { self.navigationController?.navigationBar.prefersLargeTitles = true // self.navigationItem.largeTitleDisplayMode = .always } } // Close the settings modal @IBOutlet var closeButton: UIBarButtonItem! @IBAction func closeButtonTriggered(_: Any) { navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } // MARK: - Settings content var savedMapProvider: String = UserDefaults.standard.object(forKey: "savedMapProvider") as? String ?? "Apple" override func numberOfSections(in _: UITableView) -> Int { return 2 } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return AvailableMap.count case 1: return BooleanSetting.count default: return 4 } } override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return NSLocalizedString("Map providers", comment: "Title for the list of available map apps a user can open") case 1: return NSLocalizedString("Behavior", comment: "Title for the list of behavior options") default: return "Section \(section)" } } override func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } var lastCheckedIndexPath: IndexPath? = IndexPath(row: 0, section: 0) override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsCell", for: indexPath) as UITableViewCell switch indexPath.section { case 0: cell.textLabel?.text = AvailableMap.maps[indexPath.row] if cell.textLabel?.text == savedMapProvider { cell.accessoryType = .checkmark lastCheckedIndexPath = indexPath } else { cell.accessoryType = .none } let cellUrl = AvailableMap.getCase(map: AvailableMap.maps[indexPath.row]).urlBase(test: true) if !UIApplication.shared.canOpenURL(URL(string: cellUrl)!) { cell.textLabel?.isEnabled = false } break case 1: // add a Switch to the cell let cellSwitch = UISwitch(frame: CGRect.zero) as UISwitch cellSwitch.isOn = UserDefaults.standard.object(forKey: BooleanSetting.id(indexPath.row).getName()) as? Bool ?? BooleanSetting.id(indexPath.row).getDefaults() cellSwitch.addTarget(self, action: #selector(switchTriggered), for: .valueChanged) cellSwitch.tag = indexPath.row cell.accessoryView = cellSwitch cell.tag = 5000 // from now on this means this is a UITableViewCell with a UISwitch in it cell.selectionStyle = UITableViewCellSelectionStyle.none cell.textLabel?.text = BooleanSetting.id(indexPath.row).getDescription() break default: cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)" } return cell } @objc func switchTriggered(sender: UISwitch) { let name = BooleanSetting.id(sender.tag).getName() UserDefaults.standard.set(sender.isOn, forKey: name) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // deselect the cell, because trigger is now received by this function tableView.deselectRow(at: indexPath, animated: true) // Prevent selection of maps not available if tableView.cellForRow(at: indexPath)?.textLabel?.isEnabled == false { return } // find the new cell let newCell = tableView.cellForRow(at: indexPath) if newCell?.tag == 5000 { // this is a UITableViewCell with a UISwitch in it return } // check if it was already checked if indexPath.row != lastCheckedIndexPath?.row { // ok, a new cell is checked. remove checkmark at the old cell if let lastCheckedIndexPath = lastCheckedIndexPath { let oldCell = tableView.cellForRow(at: lastCheckedIndexPath) oldCell?.accessoryType = .none } // place checkmark on the new cell newCell?.accessoryType = .checkmark // save the indexPath of the new cell for later comparing lastCheckedIndexPath = indexPath // save the new selected map provider to user settings savedMapProvider = (newCell?.textLabel?.text)! // change the map provider to user settings UserDefaults.standard.set(savedMapProvider, forKey: "savedMapProvider") } } override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? { // TODO: Make the mail link clickable! return SectionFooter.getText(section: section) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
61b09a1ee9419949fd7be5b9aec8c136
37.227848
169
0.639901
5.202412
false
false
false
false
convergeeducacao/Charts
Source/Charts/Highlight/BarHighlighter.swift
4
3791
// // BarHighlighter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(BarChartHighlighter) open class BarHighlighter: ChartHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight? { let high = super.getHighlight(x: x, y: y) if high == nil { return nil } if let barData = (self.chart as? BarChartDataProvider)?.barData { let pos = getValsForTouch(x: x, y: y) if let set = barData.getDataSetByIndex(high!.dataSetIndex) as? IBarChartDataSet, set.isStacked { return getStackedHighlight(high: high!, set: set, xValue: Double(pos.x), yValue: Double(pos.y)) } return high } return nil } internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { return abs(x1 - x2) } internal override var data: ChartData? { return (chart as? BarChartDataProvider)?.barData } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. /// - parameter high: the Highlight to work with looking for stacked values /// - parameter set: /// - parameter xIndex: /// - parameter yValue: /// - returns: open func getStackedHighlight(high: Highlight, set: IBarChartDataSet, xValue: Double, yValue: Double) -> Highlight? { guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider, let entry = set.entryForXValue(xValue) as? BarChartDataEntry else { return nil } // Not stacked if entry.yValues == nil { return high } if let ranges = entry.ranges, ranges.count > 0 { let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue) let pixel = chart .getTransformer(forAxis: set.axisDependency) .pixelForValues(x: high.x, y: ranges[stackIndex].to) return Highlight(x: entry.x, y: entry.y, xPx: pixel.x, yPx: pixel.y, dataSetIndex: high.dataSetIndex, stackIndex: stackIndex, axis: high.axis) } return nil } /// - returns: The index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter. /// - parameter entry: /// - parameter value: /// - returns: open func getClosestStackIndex(ranges: [Range]?, value: Double) -> Int { if ranges == nil { return 0 } var stackIndex = 0 for range in ranges! { if range.contains(value) { return stackIndex } else { stackIndex += 1 } } let length = max(ranges!.count - 1, 0) return (value > ranges![length].to) ? length : 0 } }
apache-2.0
15007b1c7e15142e2a59246cff2b8540
28.617188
136
0.488262
5.302098
false
false
false
false
usharif/GrapeVyne
Pods/AsyncSwift/Sources/Async.swift
8
25499
// // Async.swift // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation // MARK: - DSL for GCD queues /** `GCD` is a convenience enum with cases to get `DispatchQueue` of different quality of service classes, as provided by `DispatchQueue.global` or `DispatchQueue` for main thread or a specific custom queue. let mainQueue = GCD.main let utilityQueue = GCD.utility let customQueue = GCD.custom(queue: aDispatchQueue) - SeeAlso: Grand Central Dispatch */ private enum GCD { case main, userInteractive, userInitiated, utility, background, custom(queue: DispatchQueue) var queue: DispatchQueue { switch self { case .main: return .main case .userInteractive: return .global(qos: .userInteractive) case .userInitiated: return .global(qos: .userInitiated) case .utility: return .global(qos: .utility) case .background: return .global(qos: .background) case .custom(let queue): return queue } } } // MARK: - Async – Struct /** The **Async** struct is the main part of the Async.framework. Handles an internally `@convention(block) () -> Swift.Void`. Chainable dispatch blocks with GCD: Async.background { // Run on background queue }.main { // Run on main queue, after the previous block } All moderns queue classes: Async.main {} Async.userInteractive {} Async.userInitiated {} Async.utility {} Async.background {} Custom queues: let customQueue = dispatch_queue_create("Label", DISPATCH_QUEUE_CONCURRENT) Async.customQueue(customQueue) {} Dispatch block after delay: let seconds = 0.5 Async.main(after: seconds) {} Cancel blocks not yet dispatched let block1 = Async.background { // Some work } let block2 = block1.background { // Some other work } Async.main { // Cancel async to allow block1 to begin block1.cancel() // First block is NOT cancelled block2.cancel() // Second block IS cancelled } Wait for block to finish: let block = Async.background { // Do stuff } // Do other stuff // Wait for "Do stuff" to finish block.wait() // Do rest of stuff - SeeAlso: Grand Central Dispatch */ private class Reference<T> { var value: T? } public typealias Async = AsyncBlock<Void, Void> public struct AsyncBlock<In, Out> { // MARK: - Private properties and init /** Private property to hold internally on to a `@convention(block) () -> Swift.Void` */ private let block: DispatchWorkItem private let input: Reference<In>? private let output_: Reference<Out> public var output: Out? { return output_.value } /** Private init that takes a `@convention(block) () -> Swift.Void` */ private init(_ block: DispatchWorkItem, input: Reference<In>? = nil, output: Reference<Out> = Reference()) { self.block = block self.input = input self.output_ = output } // MARK: - Static methods /** Sends the a block to be run asynchronously on the main thread. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the main queue - returns: An `Async` struct - SeeAlso: Has parity with non-static method */ @discardableResult public static func main<O>(after seconds: Double? = nil, _ block: @escaping (Void) -> O) -> AsyncBlock<Void, O> { return AsyncBlock.async(after: seconds, block: block, queue: .main) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with non-static method */ @discardableResult public static func userInteractive<O>(after seconds: Double? = nil, _ block: @escaping (Void) -> O) -> AsyncBlock<Void, O> { return AsyncBlock.async(after: seconds, block: block, queue: .userInteractive) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INITIATED. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with non-static method */ @discardableResult public static func userInitiated<O>(after seconds: Double? = nil, _ block: @escaping (Void) -> O) -> AsyncBlock<Void, O> { return Async.async(after: seconds, block: block, queue: .userInitiated) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_UTILITY. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on queue - returns: An `Async` struct - SeeAlso: Has parity with non-static method */ @discardableResult public static func utility<O>(after seconds: Double? = nil, _ block: @escaping (Void) -> O) -> AsyncBlock<Void, O> { return Async.async(after: seconds, block: block, queue: .utility) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_BACKGROUND. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with non-static method */ @discardableResult public static func background<O>(after seconds: Double? = nil, _ block: @escaping (Void) -> O) -> AsyncBlock<Void, O> { return Async.async(after: seconds, block: block, queue: .background) } /** Sends the a block to be run asynchronously on a custom queue. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with non-static method */ @discardableResult public static func custom<O>(queue: DispatchQueue, after seconds: Double? = nil, _ block: @escaping (Void) -> O) -> AsyncBlock<Void, O> { return Async.async(after: seconds, block: block, queue: .custom(queue: queue)) } // MARK: - Private static methods /** Convenience for dispatch_async(). Encapsulates the block in a "true" GCD block using DISPATCH_BLOCK_INHERIT_QOS_CLASS. - parameters: - block: The block that is to be passed to be run on the `queue` - queue: The queue on which the `block` is run. - returns: An `Async` struct which encapsulates the `@convention(block) () -> Swift.Void` */ private static func async<O>(after seconds: Double? = nil, block: @escaping (Void) -> O, queue: GCD) -> AsyncBlock<Void, O> { let reference = Reference<O>() let block = DispatchWorkItem(block: { reference.value = block() }) if let seconds = seconds { let time = DispatchTime.now() + seconds queue.queue.asyncAfter(deadline: time, execute: block) } else { queue.queue.async(execute: block) } // Wrap block in a struct since @convention(block) () -> Swift.Void can't be extended return AsyncBlock<Void, O>(block, output: reference) } // MARK: - Instance methods (matches static ones) /** Sends the a block to be run asynchronously on the main thread, after the current block has finished. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the main queue - returns: An `Async` struct - SeeAlso: Has parity with static method */ @discardableResult public func main<O>(after seconds: Double? = nil, _ chainingBlock: @escaping (Out) -> O) -> AsyncBlock<Out, O> { return chain(after: seconds, block: chainingBlock, queue: .main) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE, after the current block has finished. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with static method */ @discardableResult public func userInteractive<O>(after seconds: Double? = nil, _ chainingBlock: @escaping (Out) -> O) -> AsyncBlock<Out, O> { return chain(after: seconds, block: chainingBlock, queue: .userInteractive) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INITIATED, after the current block has finished. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with static method */ @discardableResult public func userInitiated<O>(after seconds: Double? = nil, _ chainingBlock: @escaping (Out) -> O) -> AsyncBlock<Out, O> { return chain(after: seconds, block: chainingBlock, queue: .userInitiated) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_UTILITY, after the current block has finished. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with static method */ @discardableResult public func utility<O>(after seconds: Double? = nil, _ chainingBlock: @escaping (Out) -> O) -> AsyncBlock<Out, O> { return chain(after: seconds, block: chainingBlock, queue: .utility) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_BACKGROUND, after the current block has finished. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with static method */ @discardableResult public func background<O>(after seconds: Double? = nil, _ chainingBlock: @escaping (Out) -> O) -> AsyncBlock<Out, O> { return chain(after: seconds, block: chainingBlock, queue: .background) } /** Sends the a block to be run asynchronously on a custom queue, after the current block has finished. - parameters: - after: After how many seconds the block should be run. - block: The block that is to be passed to be run on the queue - returns: An `Async` struct - SeeAlso: Has parity with static method */ @discardableResult public func custom<O>(queue: DispatchQueue, after seconds: Double? = nil, _ chainingBlock: @escaping (Out) -> O) -> AsyncBlock<Out, O> { return chain(after: seconds, block: chainingBlock, queue: .custom(queue: queue)) } // MARK: - Instance methods /** Convenience function to call `dispatch_block_cancel()` on the encapsulated block. Cancels the current block, if it hasn't already begun running to GCD. Usage: let block1 = Async.background { // Some work } let block2 = block1.background { // Some other work } Async.main { // Cancel async to allow block1 to begin block1.cancel() // First block is NOT cancelled block2.cancel() // Second block IS cancelled } */ public func cancel() { block.cancel() } /** Convenience function to call `dispatch_block_wait()` on the encapsulated block. Waits for the current block to finish, on any given thread. - parameters: - seconds: Max seconds to wait for block to finish. If value is 0.0, it uses DISPATCH_TIME_FOREVER. Default value is 0. - SeeAlso: dispatch_block_wait, DISPATCH_TIME_FOREVER */ @discardableResult public func wait(seconds: Double? = nil) -> DispatchTimeoutResult { let timeout = seconds .flatMap { DispatchTime.now() + $0 } ?? .distantFuture return block.wait(timeout: timeout) } // MARK: Private instance methods /** Convenience for `dispatch_block_notify()` to - parameters: - block: The block that is to be passed to be run on the `queue` - queue: The queue on which the `block` is run. - returns: An `Async` struct which encapsulates the `@convention(block) () -> Swift.Void`, which is called when the current block has finished. - SeeAlso: dispatch_block_notify, dispatch_block_create */ private func chain<O>(after seconds: Double? = nil, block chainingBlock: @escaping (Out) -> O, queue: GCD) -> AsyncBlock<Out, O> { let reference = Reference<O>() let dispatchWorkItem = DispatchWorkItem(block: { reference.value = chainingBlock(self.output_.value!) }) let queue = queue.queue if let seconds = seconds { block.notify(queue: queue) { let time = DispatchTime.now() + seconds queue.asyncAfter(deadline: time, execute: dispatchWorkItem) } } else { block.notify(queue: queue, execute: dispatchWorkItem) } // See Async.async() for comments return AsyncBlock<Out, O>(dispatchWorkItem, input: self.output_, output: reference) } } // MARK: - Apply - DSL for `dispatch_apply` /** `Apply` is an empty struct with convenience static functions to parallelize a for-loop, as provided by `dispatch_apply`. Apply.background(100) { i in // Calls blocks in parallel } `Apply` runs a block multiple times, before returning. If you want run the block asynchronously from the current thread, wrap it in an `Async` block: Async.background { Apply.background(100) { i in // Calls blocks in parallel asynchronously } } - SeeAlso: Grand Central Dispatch, dispatch_apply */ public struct Apply { /** Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE. The block is being passed an index parameter. - parameters: - iterations: How many times the block should be run. Index provided to block goes from `0..<iterations` - block: The block that is to be passed to be run on a . */ public static func userInteractive(_ iterations: Int, block: @escaping (Int) -> ()) { GCD.userInteractive.queue.async { DispatchQueue.concurrentPerform(iterations: iterations, execute: block) } } /** Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_USER_INITIATED. The block is being passed an index parameter. - parameters: - iterations: How many times the block should be run. Index provided to block goes from `0..<iterations` - block: The block that is to be passed to be run on a . */ public static func userInitiated(_ iterations: Int, block: @escaping (Int) -> ()) { GCD.userInitiated.queue.async { DispatchQueue.concurrentPerform(iterations: iterations, execute: block) } } /** Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_UTILITY. The block is being passed an index parameter. - parameters: - iterations: How many times the block should be run. Index provided to block goes from `0..<iterations` - block: The block that is to be passed to be run on a . */ public static func utility(_ iterations: Int, block: @escaping (Int) -> ()) { GCD.utility.queue.async { DispatchQueue.concurrentPerform(iterations: iterations, execute: block) } } /** Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_BACKGROUND. The block is being passed an index parameter. - parameters: - iterations: How many times the block should be run. Index provided to block goes from `0..<iterations` - block: The block that is to be passed to be run on a . */ public static func background(_ iterations: Int, block: @escaping (Int) -> ()) { GCD.background.queue.async { DispatchQueue.concurrentPerform(iterations: iterations, execute: block) } } /** Block is run any given amount of times on a custom queue. The block is being passed an index parameter. - parameters: - iterations: How many times the block should be run. Index provided to block goes from `0..<iterations` - block: The block that is to be passed to be run on a . */ public static func custom(queue: DispatchQueue, iterations: Int, block: @escaping (Int) -> ()) { queue.async { DispatchQueue.concurrentPerform(iterations: iterations, execute: block) } } } // MARK: - AsyncGroup – Struct /** The **AsyncGroup** struct facilitates working with groups of asynchronous blocks. Handles a internally `dispatch_group_t`. Multiple dispatch blocks with GCD: let group = AsyncGroup() group.background { // Run on background queue } group.utility { // Run on untility queue, after the previous block } group.wait() All moderns queue classes: group.main {} group.userInteractive {} group.userInitiated {} group.utility {} group.background {} Custom queues: let customQueue = dispatch_queue_create("Label", DISPATCH_QUEUE_CONCURRENT) group.customQueue(customQueue) {} Wait for group to finish: let group = AsyncGroup() group.background { // Do stuff } group.background { // Do other stuff in parallel } // Wait for both to finish group.wait() // Do rest of stuff - SeeAlso: Grand Central Dispatch */ public struct AsyncGroup { // MARK: - Private properties and init /** Private property to internally on to a `dispatch_group_t` */ private var group: DispatchGroup /** Private init that takes a `dispatch_group_t` */ public init() { group = DispatchGroup() } /** Convenience for `dispatch_group_async()` - parameters: - block: The block that is to be passed to be run on the `queue` - queue: The queue on which the `block` is run. - SeeAlso: dispatch_group_async, dispatch_group_create */ private func async(block: @escaping @convention(block) () -> Swift.Void, queue: GCD) { queue.queue.async(group: group, execute: block) } /** Convenience for `dispatch_group_enter()`. Used to add custom blocks to the current group. - SeeAlso: dispatch_group_enter, dispatch_group_leave */ public func enter() { group.enter() } /** Convenience for `dispatch_group_leave()`. Used to flag a custom added block is complete. - SeeAlso: dispatch_group_enter, dispatch_group_leave */ public func leave() { group.leave() } // MARK: - Instance methods /** Sends the a block to be run asynchronously on the main thread, in the current group. - parameters: - block: The block that is to be passed to be run on the main queue */ public func main(_ block: @escaping @convention(block) () -> Swift.Void) { async(block: block, queue: .main) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE, in the current group. - parameters: - block: The block that is to be passed to be run on the queue */ public func userInteractive(_ block: @escaping @convention(block) () -> Swift.Void) { async(block: block, queue: .userInteractive) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INITIATED, in the current group. - parameters: - block: The block that is to be passed to be run on the queue */ public func userInitiated(_ block: @escaping @convention(block) () -> Swift.Void) { async(block: block, queue: .userInitiated) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_UTILITY, in the current block. - parameters: - block: The block that is to be passed to be run on the queue */ public func utility(_ block: @escaping @convention(block) () -> Swift.Void) { async(block: block, queue: .utility) } /** Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_BACKGROUND, in the current block. - parameters: - block: The block that is to be passed to be run on the queue */ public func background(_ block: @escaping @convention(block) () -> Swift.Void) { async(block: block, queue: .background) } /** Sends the a block to be run asynchronously on a custom queue, in the current group. - parameters: - queue: Custom queue where the block will be run. - block: The block that is to be passed to be run on the queue */ public func custom(queue: DispatchQueue, block: @escaping @convention(block) () -> Swift.Void) { async(block: block, queue: .custom(queue: queue)) } /** Convenience function to call `dispatch_group_wait()` on the encapsulated block. Waits for the current group to finish, on any given thread. - parameters: - seconds: Max seconds to wait for block to finish. If value is nil, it uses DISPATCH_TIME_FOREVER. Default value is nil. - SeeAlso: dispatch_group_wait, DISPATCH_TIME_FOREVER */ @discardableResult public func wait(seconds: Double? = nil) -> DispatchTimeoutResult { let timeout = seconds .flatMap { DispatchTime.now() + $0 } ?? .distantFuture return group.wait(timeout: timeout) } } // MARK: - Extension for `qos_class_t` /** Extension to add description string for each quality of service class. */ public extension qos_class_t { /** Description of the `qos_class_t`. E.g. "Main", "User Interactive", etc. for the given Quality of Service class. */ var description: String { get { switch self { case qos_class_main(): return "Main" case DispatchQoS.QoSClass.userInteractive.rawValue: return "User Interactive" case DispatchQoS.QoSClass.userInitiated.rawValue: return "User Initiated" case DispatchQoS.QoSClass.default.rawValue: return "Default" case DispatchQoS.QoSClass.utility.rawValue: return "Utility" case DispatchQoS.QoSClass.background.rawValue: return "Background" case DispatchQoS.QoSClass.unspecified.rawValue: return "Unspecified" default: return "Unknown" } } } } // MARK: - Extension for `DispatchQueue.GlobalAttributes` /** Extension to add description string for each quality of service class. */ public extension DispatchQoS.QoSClass { var description: String { get { switch self { case DispatchQoS.QoSClass(rawValue: qos_class_main())!: return "Main" case .userInteractive: return "User Interactive" case .userInitiated: return "User Initiated" case .default: return "Default" case .utility: return "Utility" case .background: return "Background" case .unspecified: return "Unspecified" } } } }
mit
1835ecbc75385ca1005a8437577526d6
32.196615
204
0.644872
4.346233
false
false
false
false
ayudasystems/funnel
Pod/Classes/FunnelChart.swift
1
17570
// // FunnelChart.swift // funnel-chart // // Created by Pierre-Yves Troël on 12/17/15. // Copyright © 2015 Ayuda Media Systems. All rights reserved. // import UIKit public class FunnelChart : UIView { // // MARK: Private members // private var _animateIntoViewWhenPropertiesChange = false private var _drawCount = 0 private var _coneLipHeightAsFractionOfViewHeight: CGFloat = 0.03 private var _stemHeightAsFractionOfViewHeight: CGFloat = 0.5 private var _stemWidthAsFractionOfViewWidth: CGFloat = 0.15 private var _sliceSpacingAsFractionOfViewHeight: CGFloat = 0.002 private var _drawHorizontalLines = true private var _horizontalLinesColor = UIColor(red:0.80, green:0.80, blue:0.80, alpha:1.0) private var _horizontalLinesThickness: CGFloat = 1.0 private var _horizontalLinesDashStyle: [CGFloat] = [0.0, 4.0] private var _drawFunnelLeftShadow = true private var _funnelLeftShadowWidthAsFractionOfViewWidth: CGFloat = 0.15 private var _textShadowColor = UIColor.blackColor().colorWithAlphaComponent(0.25) private var _textShadowOffset = CGSize(width:0, height:1); private var _drawLabels = true private var _font = UIFont.boldSystemFontOfSize(14.0) private var _labelsWidthAsFractionOfStemWidth: CGFloat = 0.75 private var _textColor = UIColor.whiteColor() private var _values: [Double] = [6, 5, 4, 3, 2] private var _colorPalette: [UIColor] = [ UIColor(red:0.95, green:0.77, blue:0.06, alpha:1.0), // #f1c40f UIColor(red:0.90, green:0.49, blue:0.13, alpha:1.0), // #e67e22 UIColor(red:0.91, green:0.30, blue:0.24, alpha:1.0), // #e74c3c UIColor(red:0.10, green:0.74, blue:0.61, alpha:1.0), // #1abc9c UIColor(red:0.18, green:0.80, blue:0.44, alpha:1.0), // #2ecc71 UIColor(red:0.20, green:0.60, blue:0.86, alpha:1.0), // #3498db UIColor(red:0.61, green:0.35, blue:0.71, alpha:1.0), // #9b59b6 UIColor(red:0.20, green:0.29, blue:0.37, alpha:1.0), // #34495e UIColor(red:0.93, green:0.94, blue:0.95, alpha:1.0), // #ecf0f1 UIColor(red:0.58, green:0.65, blue:0.65, alpha:1.0) // #95a5a6 ] // // MARK: Public properties // public var values : [Double] { set (newVal) { _values = newVal self.setNeedsDisplay() } get{ return _values } } public var coneLipHeightAsFractionOfViewHeight: CGFloat { set (newVal) { _coneLipHeightAsFractionOfViewHeight = newVal self.setNeedsDisplay() } get{ return _coneLipHeightAsFractionOfViewHeight } } public var stemHeightAsFractionOfViewHeight: CGFloat { set (newVal) { _stemHeightAsFractionOfViewHeight = newVal self.setNeedsDisplay() } get{ return _stemHeightAsFractionOfViewHeight } } public var stemWidthAsFractionOfViewWidth : CGFloat { set (newVal) { _stemWidthAsFractionOfViewWidth = newVal self.setNeedsDisplay() } get{ return _stemWidthAsFractionOfViewWidth } } public var sliceSpacingAsFractionOfViewHeight: CGFloat { set (newVal) { _sliceSpacingAsFractionOfViewHeight = newVal self.setNeedsDisplay() } get{ return _sliceSpacingAsFractionOfViewHeight } } public var drawHorizontalLines : Bool { set (newVal) { _drawHorizontalLines = newVal self.setNeedsDisplay() } get{ return _drawHorizontalLines } } public var horizontalLinesColor : UIColor { set (newVal) { _horizontalLinesColor = newVal self.setNeedsDisplay() } get{ return _horizontalLinesColor } } public var horizontalLinesThickness : CGFloat { set (newVal) { _horizontalLinesThickness = newVal self.setNeedsDisplay() } get{ return _horizontalLinesThickness } } public var horizontalLinesDashStyle : [CGFloat] { set (newVal) { _horizontalLinesDashStyle = newVal self.setNeedsDisplay() } get{ return _horizontalLinesDashStyle } } public var drawFunnelLeftShadow: Bool { set (newVal) { _drawFunnelLeftShadow = newVal self.setNeedsDisplay() } get{ return _drawFunnelLeftShadow } } public var funnelLeftShadowWidthAsFractionOfViewWidth: CGFloat { set (newVal) { _funnelLeftShadowWidthAsFractionOfViewWidth = newVal self.setNeedsDisplay() } get{ return _funnelLeftShadowWidthAsFractionOfViewWidth } } public var textShadowColor : UIColor { set (newVal) { _textShadowColor = newVal self.setNeedsDisplay() } get{ return _textShadowColor } } public var textShadowOffset : CGSize { set (newVal) { _textShadowOffset = newVal self.setNeedsDisplay() } get{ return _textShadowOffset } } public var drawLabels : Bool { set (newVal) { _drawLabels = newVal self.setNeedsDisplay() } get{ return _drawLabels } } public var font : UIFont { set (newVal) { _font = newVal self.setNeedsDisplay() } get{ return _font } } public var labelsWidthAsFractionOfStemWidth : CGFloat { set (newVal) { _labelsWidthAsFractionOfStemWidth = newVal self.setNeedsDisplay() } get{ return _labelsWidthAsFractionOfStemWidth } } public var textColor : UIColor { set (newVal) { _textColor = newVal self.setNeedsDisplay() } get{ return _textColor } } public var colorPalette : [UIColor] { set (newVal) { _colorPalette = newVal self.setNeedsDisplay() } get{ return _colorPalette } } public var animateIntoViewWhenPropertiesChange: Bool { set (newVal) { _animateIntoViewWhenPropertiesChange = newVal self.setNeedsDisplay() } get{ return _animateIntoViewWhenPropertiesChange } } // // MARK: Initialization // override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.contentMode = UIViewContentMode.Redraw } // // MARK: Drawing // override public func drawRect(rect: CGRect) { // Cleanup self.layer.sublayers?.removeAll() // // Setup a graphics context to draw horizontal lines. // let ctx = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(ctx, _horizontalLinesColor.CGColor) CGContextSetLineWidth(ctx, _horizontalLinesThickness) CGContextSetLineCap(ctx, .Round) CGContextSetLineDash(ctx, 0.0, _horizontalLinesDashStyle, 2) // // Calculating pixel dimensions... // let stemWidth = self._stemWidthAsFractionOfViewWidth * rect.size.width let stemHeight = self._stemHeightAsFractionOfViewHeight * rect.size.height let coneLipHeight = self._coneLipHeightAsFractionOfViewHeight * rect.size.height let coneHeight = rect.size.height - stemHeight - coneLipHeight let slopeWidth = (rect.size.width - stemWidth) / 2 let slopeAngle = atan2(slopeWidth, coneHeight) let slopeTan = tan(slopeAngle) let totalValues = _values.reduce(0, combine: +) var cumulativeValue: Double = 0 if abs(totalValues) < 1e-7 { return } var index = 0 // // Draw each slice of the funnel based on values. // for val in _values { let shape = CAShapeLayer() self.layer.addSublayer(shape) shape.fillColor = self._colorPalette[index % self._colorPalette.count].CGColor let shapeShadow = CAShapeLayer() self.layer.addSublayer(shapeShadow) shapeShadow.fillColor = UIColor.blackColor().colorWithAlphaComponent(0.1).CGColor let startY = (CGFloat(cumulativeValue / totalValues) + (index == 0 ? 0 : _sliceSpacingAsFractionOfViewHeight)) * rect.height let endY = (CGFloat((cumulativeValue + val) / totalValues) - (index == (_values.count - 1) ? 0 : _sliceSpacingAsFractionOfViewHeight)) * rect.height let endYNoSpacing = CGFloat((cumulativeValue + val) / totalValues) * rect.height let percentLabel = UILabel() percentLabel.text = String.localizedStringWithFormat("%.0f%@", (val / totalValues * 100.0), "%") percentLabel.frame = CGRect(x: slopeWidth + ((stemWidth - stemWidth * _labelsWidthAsFractionOfStemWidth) / 2), y: startY, width: stemWidth * _labelsWidthAsFractionOfStemWidth, height: endY - startY) percentLabel.font = self._font percentLabel.textColor = self._textColor percentLabel.shadowColor = self._textShadowColor percentLabel.shadowOffset = self._textShadowOffset percentLabel.textAlignment = .Center percentLabel.adjustsFontSizeToFitWidth = true percentLabel.numberOfLines = 1 percentLabel.minimumScaleFactor = 0.5 var points = [CGPoint]() if endY < coneLipHeight { // The section is above the lip of the cone. let startX1: CGFloat = 0 let endX1: CGFloat = rect.width let startX2: CGFloat = 0 let endX2: CGFloat = rect.width points.append(CGPoint(x: startX1, y: startY)) points.append(CGPoint(x: startX2, y: endY)) points.append(CGPoint(x: endX2, y: endY)) points.append(CGPoint(x: endX1, y: startY)) } else if startY < coneLipHeight && endY > coneLipHeight && endY < (coneHeight + coneLipHeight) { // The section is above the lip of the cone and above the junction of the cone and the stem. let startX1: CGFloat = 0 let endX1: CGFloat = rect.width let startX2 = startX1 let endX2 = rect.width - startX2 let startX3 = slopeTan * (endY - coneLipHeight) let endX3 = rect.width - startX3 points.append(CGPoint(x: startX1, y: startY)) points.append(CGPoint(x: startX2, y: coneLipHeight)) points.append(CGPoint(x: startX3, y: endY)) points.append(CGPoint(x: endX3, y: endY)) points.append(CGPoint(x: endX2, y: coneLipHeight)) points.append(CGPoint(x: endX1, y: startY)) } else if startY < coneLipHeight && endY > coneLipHeight && endY >= (coneHeight + coneLipHeight) { // The section is above the lip of the cone and below the junction of the cone and the stem let startX1: CGFloat = 0 let endX1: CGFloat = rect.width let startX2 = startX1 let endX2 = rect.width - startX2 let startX3 = slopeTan * coneHeight let endX3 = rect.width - startX3 let startX4 = slopeWidth let endX4 = rect.width - startX4 points.append(CGPoint(x: startX1, y: startY)) points.append(CGPoint(x: startX2, y: coneLipHeight)) points.append(CGPoint(x: startX3, y: coneHeight + coneLipHeight)) points.append(CGPoint(x: startX4, y: endY)) points.append(CGPoint(x: endX4, y: endY)) points.append(CGPoint(x: endX3, y: coneHeight + coneLipHeight)) points.append(CGPoint(x: endX2, y: coneLipHeight)) points.append(CGPoint(x: endX1, y: startY)) } else if endY < (coneHeight + coneLipHeight) { // The section is below the lip of the cone and above the junction of the cone and the stem let startX1 = slopeTan * (startY - coneLipHeight) let endX1 = rect.width - startX1 let startX2 = slopeTan * (endY - coneLipHeight) let endX2 = rect.width - startX2 points.append(CGPoint(x: startX1, y: startY)) points.append(CGPoint(x: startX2, y: endY)) points.append(CGPoint(x: endX2, y: endY)) points.append(CGPoint(x: endX1, y: startY)) } else if startY >= (coneHeight + coneLipHeight) { // The section is part of the stem only. let startX1 = slopeWidth let endX1 = slopeWidth + stemWidth let startX2 = slopeWidth let endX2 = slopeWidth + stemWidth points.append(CGPoint(x: startX1, y: startY)) points.append(CGPoint(x: startX2, y: endY)) points.append(CGPoint(x: endX2, y: endY)) points.append(CGPoint(x: endX1, y: startY)) } else { // The section is above the junction of the cone and the stem and below the junction of the cone and the stem. let startX1 = slopeTan * (startY - coneLipHeight) let endX1 = rect.width - startX1 let startX2 = slopeWidth let endX2 = rect.width - startX2 let startX3 = slopeWidth let endX3 = rect.width - startX3 points.append(CGPoint(x: startX1, y: startY)) points.append(CGPoint(x: startX2, y: coneHeight + coneLipHeight)) points.append(CGPoint(x: startX3, y: endY)) points.append(CGPoint(x: endX3, y: endY)) points.append(CGPoint(x: endX2, y: coneHeight + coneLipHeight)) points.append(CGPoint(x: endX1, y: startY)) } if self._drawHorizontalLines { CGContextMoveToPoint(ctx, 0, endYNoSpacing) CGContextAddLineToPoint(ctx, rect.width, endYNoSpacing) CGContextStrokePath(ctx) } let path = UIBezierPath() var first = true for pt in points { if first { path.moveToPoint(pt) } else{ path.addLineToPoint(pt) } first = false } path.closePath() shape.path = path.CGPath if _drawFunnelLeftShadow { let pathShadow = UIBezierPath() var pointIndex = 0 for pt in points { if pointIndex == 0 { pathShadow.moveToPoint(pt) } else { if pointIndex < points.count / 2 { pathShadow.addLineToPoint(pt) } else { pathShadow.addLineToPoint(CGPoint(x: points[points.count - pointIndex - 1].x + stemWidth * _funnelLeftShadowWidthAsFractionOfViewWidth, y: pt.y)) } } pointIndex++ } pathShadow.closePath() shapeShadow.path = pathShadow.CGPath } if _drawCount == 0 || _animateIntoViewWhenPropertiesChange { CATransaction.begin() CATransaction.setCompletionBlock({ shape.position.x = 0 shapeShadow.position.x = 0 // Add % label if self._drawLabels { self.addSubview(percentLabel) } }) let animation = CABasicAnimation() animation.keyPath = "position.x" animation.fromValue = -rect.width animation.toValue = 0 animation.duration = 0.50 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false animation.beginTime = CACurrentMediaTime() + (Double(index) * 0.05) animation.timingFunction = CAMediaTimingFunction(controlPoints: 1.0, 0, 0, 1.0) shape.addAnimation(animation, forKey: "basic") shape.position.x = -rect.width shapeShadow.addAnimation(animation, forKey: "basic") shapeShadow.position.x = -rect.width CATransaction.commit() } else{ self.addSubview(percentLabel) } cumulativeValue += val index++ } _drawCount++ } }
mit
e02407a7a5012b27b5f20a9d7f40bdde
33.790099
210
0.550148
4.565489
false
false
false
false
ShyPhinehas/AngPlayer
AngPlayer/Classes/AngPlayerVC.swift
1
4387
// // ViewController.swift // AngPlayer // // Created by [email protected] on 08/04/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import AVFoundation /** 1. file in Resaurce angPlayer.url = FileLocation.bundle.url(filePath: "001.mp4") 2. web angPlayer.url = URL(string: "http://www.littlefox.net/app/api/m3u8/MDAwMDcwNDQ1MDA4MTAxMjAxNjAyMDIxNDA3MzQ5OTY0NTAyMDE3MTQzOHwzNzE0MTAzOHw1MjU5OTM5OXxXfDY0MCoxMTM2fGtvfEtSfDR8MTg") 3. files let urls : [URL?] = [ URL(string: "https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8"), URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8"), URL(string: "https://mnmedias.api.telequebec.tv/m3u8/29880.m3u8"), FileLocation.bundle.url(filePath: "001.mp4"), ] angPlayer.urls = urls */ open class AngPlayerVC: UIViewController, AngPlayerViewDelegate { var angPlayer: AngPlayer! var spinner : UIActivityIndicatorView? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) angPlayer = AngPlayer(frame: UIScreen.main.bounds) angPlayer.delegate = self self.view.addSubview(angPlayer) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func viewDidLoad() { super.viewDidLoad() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } public func angPlayerCallback(loadStart player: AngPlayer){ self.addSpinner() } public func angPlayerCallback(loadFinshied player: AngPlayer, isLoadSuccess: Bool, error: Error?){ self.removeSpinner() if isLoadSuccess{ self.angPlayer.play() }else{ print("load error : \(String(describing: error?.localizedDescription))") } } public func angPlayerCallback(player: AngPlayer, statusPlayer: AVPlayer.Status, error: Error?){} public func angPlayerCallback(player: AngPlayer, statusItemPlayer: AVPlayerItem.Status, error: Error?){} public func angPlayerCallback(player: AngPlayer, loadedTimeRanges: [CMTimeRange]){ //set loaded range value to loaded Slide /* let durationTotal = loadedTimeRanges.reduce(0) { (actual, range) -> Double in return actual + range.end.seconds } let dur2 = Float(durationTotal) loadedPlaySlider?.value = dur2 */ } public func angPlayerCallback(player: AngPlayer, duration: Double){ //set play slide maxValue and load slile maxValue /* playSlider?.maximumValue = Float(duration) loadedPlaySlider?.maximumValue = Float(duration) */ } public func angPlayerCallback(player: AngPlayer, currentTime: Double){ //edit slide value by changing currentTime //playSlider?.value = Float(currentTime) } public func angPlayerCallback(player: AngPlayer, rate: Float){ if rate == 0.0 { //change play buton state to pause }else{ //change play buton state to play } } public func angPlayerCallback(player: AngPlayer, isLikelyKeepUp: Bool){ if isLikelyKeepUp{ self.removeSpinner() }else{ self.addSpinner() } } public func angPlayerCallback(playerFinished player: AngPlayer){} public func angPlayerCallback(pangestureLocation touchLocation: CGPoint, valueLength: CGPoint){ self.angPlayer.changeVolumeByGesture(by: touchLocation) } @IBAction func nextBtnCallback(_ sender: Any) { angPlayer.next() } @IBAction func prevBtnCallback(_ sender: Any) { angPlayer.prev() } } extension AngPlayerVC{ public func addSpinner(isPreventouch: Bool = false) { removeSpinner() self.view.isUserInteractionEnabled = !isPreventouch spinner = UIActivityIndicatorView(frame: UIScreen.main.bounds) spinner?.activityIndicatorViewStyle = .white spinner?.startAnimating() self.view.addSubview(spinner!) } public func removeSpinner() { spinner?.stopAnimating() spinner?.removeFromSuperview() spinner = nil } }
mit
70d75703989a8c31965f718ca3c840ae
32.48855
181
0.668338
3.804857
false
false
false
false
OMTS/NavigationAppRouter
Example/NavigationAppRouter/ViewController.swift
1
5937
// // ViewController.swift // NavigationAppRouter // // Created by fpoisson on 01/11/2016. // Copyright (c) 2016 fpoisson. All rights reserved. // import UIKit import MapKit import NavigationAppRouter class ViewController: UIViewController { @IBOutlet var mapView: MKMapView! @IBOutlet var gotoButton: UIButton! @IBOutlet var activityLabel: UILabel! @IBOutlet var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var addressTF: UITextField! lazy var locationManager: CLLocationManager? = CLLocationManager() var placeAnnotation: MKPointAnnotation! lazy var geocoder = CLGeocoder() var didInitialZoom = false override func viewDidLoad() { super.viewDidLoad() self.activityIndicator.isHidden = true; self.setupMapView() self.askForLocationAccessPermissions() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupMapView() { self.mapView.delegate = self self.mapView.showsUserLocation = true; let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userDidTapMapView(tapGesture:))) tapGesture.numberOfTapsRequired = 1; tapGesture.numberOfTouchesRequired = 1; self.mapView.addGestureRecognizer(tapGesture); let tapGesture2 = UITapGestureRecognizer(target: self, action: nil) tapGesture2.numberOfTapsRequired = 2; tapGesture2.numberOfTouchesRequired = 1; self.mapView.addGestureRecognizer(tapGesture2); tapGesture.require(toFail: tapGesture2) tapGesture.delegate = self } func askForLocationAccessPermissions() { // Ask for location permission access let locationAuthorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus() if locationAuthorizationStatus == CLAuthorizationStatus.notDetermined { if let locationManager = self.locationManager { locationManager.delegate = self locationManager.requestWhenInUseAuthorization() } } } func displaySearchActivity(displayed: Bool) { self.gotoButton.isHidden = displayed self.activityLabel.isHidden = !displayed; self.activityIndicator.isHidden = !displayed; if displayed { self.activityIndicator.startAnimating() } else { self.activityIndicator.stopAnimating() } } @objc func userDidTapMapView(tapGesture: UITapGestureRecognizer) { let location: CGPoint = tapGesture.location(in: self.mapView) // Update place annotation if self.placeAnnotation == nil { self.placeAnnotation = MKPointAnnotation() self.mapView.addAnnotation(self.placeAnnotation) } self.placeAnnotation.coordinate = self.mapView.convert(location, toCoordinateFrom: self.mapView) } @IBAction func goToButtonTapped() { if self.placeAnnotation == nil { return } // Setup address search display self.displaySearchActivity(displayed: true) // Search for location address let placeLocaton = CLLocation(latitude: self.placeAnnotation.coordinate.latitude, longitude: self.placeAnnotation.coordinate.longitude) self.geocoder.reverseGeocodeLocation(placeLocaton) { [weak self] (placemarks, _) -> Void in if (self == nil) { return } self!.displaySearchActivity(displayed: false) if placemarks != nil && placemarks!.count > 0 { let place = MKPlacemark(placemark: placemarks![0]); DispatchQueue.main.async { // Navigation app routing // ---------------------- NavigationAppRouter.goToPlace(place, fromViewController: self!) } } } } @IBAction func gotToWithAddresButtonTapped(_ sender: UIButton) { guard addressTF.text?.count ?? 0 > 0 else{ return } NavigationAppRouter.goToPlacefromASimpleAddress(address: addressTF.text!, fromViewController: self) } } // MARK: - CLLocationManager delegate extension ViewController: CLLocationManagerDelegate { private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if (status != CLAuthorizationStatus.notDetermined) { // Location manager instance not needed anymore self.locationManager = nil } } } // MARK: - MKMapView delegate extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { // Center map on user when his location is available if didInitialZoom == false { if let userCoordinate: CLLocationCoordinate2D = userLocation.location?.coordinate { let region = MKCoordinateRegion(center: userCoordinate, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)) didInitialZoom = true self.mapView.setRegion(region, animated: true) } } } } // MARK: - UIGestureRecognizer delegate extension ViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { // Discard touch if in annotation view if touch.view is MKAnnotationView { return false } return true } } extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
mit
4de52f9e2d407e79141f81800d1d438c
32.353933
143
0.651844
5.648906
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Scenes/Open mobile scene (scene package)/OpenMobileSceneViewController.swift
1
2058
// // Copyright © 2019 Esri. // // 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 UIKit import ArcGIS /// A view controller that manages the interface of the Open Mobile Scene (Scene /// Package) sample. class OpenMobileSceneViewController: UIViewController { /// The mobile scene package used by the view controller. let mobileScenePackage: AGSMobileScenePackage = { let mobileScenePackageURL = Bundle.main.url(forResource: "philadelphia", withExtension: "mspk")! return AGSMobileScenePackage(fileURL: mobileScenePackageURL) }() /// The scene view managed by the view controller. @IBOutlet weak var sceneView: AGSSceneView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) mobileScenePackage.load { [weak self] _ in self?.mobileScenePackageDidLoad() } } /// Called in response to the mobile scene package load operation /// completing. func mobileScenePackageDidLoad() { loadViewIfNeeded() if let error = mobileScenePackage.loadError { presentAlert(error: error) } else { sceneView.scene = mobileScenePackage.scenes.first } } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["OpenMobileSceneViewController"] } }
apache-2.0
d1f3382693577f6c1d2919c59020adf4
33.864407
123
0.68595
4.707094
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Views/MeFooterView.swift
1
2586
// // MeFooterView.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/25. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit fileprivate let LabelColor = UIColor(red: 180.0/255.0, green: 180.0/255.0, blue: 180.0/255.0, alpha: 1.0) class MeFooterView: UIView { //MARK: 属性 var viewModel:MeFooterViewModel? { didSet{ tipLabel.text = viewModel?.tipLabelText if let image = viewModel?.iconImage { iconView.image = image iconView.isHidden = false } else{ iconView.isHidden = true } } } weak var delegate:MeFooterViewDelegate? //MARK 懒加载 lazy var iconView:UIImageView = UIImageView(image: #imageLiteral(resourceName: "me_blank")) lazy var tipLabel:UILabel = { () -> UILabel in let label = UILabel() label.textColor = LabelColor label.font = fontSize16 return label }() lazy var loginButton:UIButton = { let button = UIButton(type: .custom) button.backgroundColor = UIColor.clear return button }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupMeFooterView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupMeFooterViewSubView() } //MARK: 私有方法 private func setupMeFooterView() { backgroundColor = UIColor.white addSubview(iconView) addSubview(tipLabel) addSubview(loginButton) loginButton.addTarget(self, action: #selector(loginButtonClick), for: .touchUpInside) } private func setupMeFooterViewSubView() { iconView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(80) make.centerX.equalToSuperview() } tipLabel.snp.makeConstraints { (make) in make.top.equalTo(iconView.snp.bottom).offset(margin) make.centerX.equalToSuperview() } loginButton.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } //MARK: 内部响应 @objc private func loginButtonClick() { delegate?.meFooterViewLoginButtonClick() } } //MARK: 协议 protocol MeFooterViewDelegate:NSObjectProtocol { func meFooterViewLoginButtonClick() }
mit
9a30310af9211115a5eca1b093618ae2
25.882979
105
0.603087
4.577899
false
false
false
false
jpaffrath/mpd-ios
mpd-ios/ViewControllerMusic.swift
1
3100
// // ViewControllerMusic.swift // mpd-ios // // Created by Julius Paffrath on 16.12.16. // Copyright © 2016 Julius Paffrath. All rights reserved. // import UIKit class ViewControllerMusic: UITableViewController { private let TAG_LABEL_ARTIST: Int = 100 private let COLOR_BLUE = UIColor.init(colorLiteralRed: Float(55.0/255), green: Float(111.0/255), blue: Float(165.0/255), alpha: 1) private var artists: [String] = [] // MARK: Init override func viewDidLoad() { self.refreshControl = UIRefreshControl.init() self.refreshControl?.backgroundColor = self.COLOR_BLUE self.refreshControl?.tintColor = UIColor.white self.refreshControl?.addTarget(self, action: #selector(ViewControllerMusic.reloadArtists), for: UIControlEvents.valueChanged) } override func viewWillAppear(_ animated: Bool) { self.reloadArtists() } // MARK: Private Methods func reloadArtists() { MPD.sharedInstance.getArtistnames { (artists: [String]) in self.artists = artists self.tableView.reloadData() self.refreshControl?.endRefreshing() } } // MARK: TableView Delegates override func numberOfSections(in tableView: UITableView) -> Int { if self.artists.count > 0 { self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine self.tableView.backgroundView = nil return 1 } else { let size = self.view.bounds.size let labelMsg = UILabel.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height))) labelMsg.text = "No artists available! Pull to refresh" labelMsg.textColor = self.COLOR_BLUE labelMsg.numberOfLines = 0 labelMsg.textAlignment = NSTextAlignment.center labelMsg.font = UIFont.init(name: "Avenir", size: 20) labelMsg.sizeToFit() self.tableView.backgroundView = labelMsg self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none } return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.artists.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) let labelArtist: UILabel = cell.viewWithTag(self.TAG_LABEL_ARTIST) as! UILabel labelArtist.text = self.artists[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerAlbums") as! ViewControllerAlbums viewController.artist = self.artists[indexPath.row] self.navigationController?.pushViewController(viewController, animated: true) } }
gpl-3.0
97a273236beffe74d3686b81cf144472
35.892857
137
0.65989
4.849765
false
false
false
false
yanagiba/swift-transform
Tests/GeneratorTests/TokenizerTests.swift
1
3775
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import Parser @testable import Transform class TokenizerTests : XCTestCase { func testTokenizer() { let resourceName = "Resources" let testNames = [ // primary expressions "IdentifierExpression", "LiteralExpression", "SelfExpression", "SuperclassExpression", "ClosureExpression", "ParenthesizedExpression", "TupleExpression", "ImplicitMemberExpression", "WildcardExpression", "SelectorExpression", "KeyPathExpression", "KeyPathStringExpression", // postfix expressions "PostfixOperatorExpression", "FunctionCallExpression", "InitializerExpression", "ExplicitMemberExpression", "PostfixSelfExpression", "SubscriptExpression", "ForcedValueExpression", "OptionalChainingExpression", // prefix expressions "PrefixOperatorExpression", "InOutExpression", // binary expressions "BinaryOperatorExpression", "AssignmentOperatorExpression", "TernaryConditionalOperatorExpression", "TypeCastingOperatorExpression", "SequenceExpression", // try expression "TryOperatorExpression", // statements "BreakStatement", "CompilerControlStatement", "ContinueStatement", "DeferStatement", "DoStatement", "FallthroughStatement", "ForInStatement", "GuardStatement", "IfStatement", "LabeledStatement", "RepeatWhileStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "WhileStatement", // declarations "ClassDeclaration", "ConstantDeclaration", "DeinitializerDeclaration", "EnumDeclaration", "ExtensionDeclaration", "FunctionDeclaration", "ImportDeclaration", "InitializerDeclaration", "OperatorDeclaration", "PrecedenceGroupDeclaration", "ProtocolDeclaration", "StructDeclaration", "SubscriptDeclaration", "TypealiasDeclaration", "VariableDeclaration", // attributes "Attribute", // types "Type", ] for testName in testNames { runTest(resourceName, testName) { source -> String in let parser = Parser(source: source) guard let topLevelDecl = try? parser.parse() else { return "error: failed in parsing the source \(source.identifier)." } let tokenizer = Tokenizer() return tokenizer.tokenize(topLevelDecl).joinedValues() } } } static var allTests = [ ("testGenerator", testTokenizer), ] }
apache-2.0
9e661c0a871da694929c438ca104e725
30.722689
86
0.573775
6.270764
false
true
false
false
codePrincess/playgrounds
Play with Cognitive Services.playgroundbook/Contents/Chapters/Faces.playgroundchapter/Pages/WhoIsThis.playgroundpage/Contents.swift
1
2596
//#-hidden-code import PlaygroundSupport import UIKit import Foundation guard #available(iOS 9, OSX 10.11, *) else { fatalError("Life? Don't talk to me about life. Here I am, brain the size of a planet, and they tell me to run a 'playground'. Call that job satisfaction? I don't.") } func detectFaces () { let page = PlaygroundPage.current if let proxy = page.liveView as? PlaygroundRemoteLiveViewProxy { proxy.send(.string("showFaceLandmarks")) proxy.send(.string("detectFace")) } } func chooseImage (_ imageData: Data) { let page = PlaygroundPage.current if let proxy = page.liveView as? PlaygroundRemoteLiveViewProxy { proxy.send(.data(imageData)) } } //#-end-hidden-code /*: # Who's on that picture? As we already saw in the Emotions demo we are capable of getting some facial features from the API, like the face rectangle or the emotion. But is there more? Like getting *coordinates* of e.g. the eyes and the nose. The answer is **YES**! We can do this. The Cognitive Services provide an API called **Face API**. With this API we can analyse the features of a human face. We can determine where the eyes are, where the pupil is currently located, how "big" or "small" a nose is and if the face is currently smiling because it's mouth and lip coordinates indicates it :) But let's dive in and see, what the **Face API** sees for us. */ /*: * experiment: So let's get the face analysis started. As you will see in a moment we get the facial landmarks (dots in the image), the face rectangle and general infos like age, gender, glasses and facial hair for the selected picture. Cool huh? */ let image = /*#-editable-code*/#imageLiteral(resourceName: "beach.png")/*#-end-editable-code*/ let dataImage = UIImagePNGRepresentation(image) chooseImage(dataImage!) detectFaces() /*: * callout(What did we learn?): The wonderful thing about this **Face API** is especially the retrieval of the landmarks of the face. We can do fun things with it, like pinning things into the face :D But we can identify this face, as soon as we added it to a PersonGroup, on other images. So we don't have to analyse the image itself and compare it to other faces to "find" persons on images. We can let the Face API do the work for us. Just have a look at the [Faces documentation](https://www.microsoft.com/cognitive-services/en-us/face-api/documentation/overview) and the way how to use [Persons and PersonGroups](https://www.microsoft.com/cognitive-services/en-us/face-api/documentation/face-api-how-to-topics/howtoidentifyfacesinimage) */
mit
4ef0a7cec552b48b01ceffb9fb0fa003
55.434783
713
0.736903
3.903759
false
false
false
false
kzaher/RxSwift
RxCocoa/iOS/UIGestureRecognizer+Rx.swift
7
2048
// // UIGestureRecognizer+Rx.swift // RxCocoa // // Created by Carlos García on 10/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift // This should be only used from `MainScheduler` final class GestureTarget<Recognizer: UIGestureRecognizer>: RxTarget { typealias Callback = (Recognizer) -> Void let selector = #selector(ControlTarget.eventHandler(_:)) weak var gestureRecognizer: Recognizer? var callback: Callback? init(_ gestureRecognizer: Recognizer, callback: @escaping Callback) { self.gestureRecognizer = gestureRecognizer self.callback = callback super.init() gestureRecognizer.addTarget(self, action: selector) let method = self.method(for: selector) if method == nil { fatalError("Can't find method") } } @objc func eventHandler(_ sender: UIGestureRecognizer) { if let callback = self.callback, let gestureRecognizer = self.gestureRecognizer { callback(gestureRecognizer) } } override func dispose() { super.dispose() self.gestureRecognizer?.removeTarget(self, action: self.selector) self.callback = nil } } extension Reactive where Base: UIGestureRecognizer { /// Reactive wrapper for gesture recognizer events. public var event: ControlEvent<Base> { let source: Observable<Base> = Observable.create { [weak control = self.base] observer in MainScheduler.ensureRunningOnMainThread() guard let control = control else { observer.on(.completed) return Disposables.create() } let observer = GestureTarget(control) { control in observer.on(.next(control)) } return observer }.take(until: deallocated) return ControlEvent(events: source) } } #endif
mit
7337becb40500741948443b2f9dac348
26.28
97
0.613392
5.140704
false
false
false
false
pyromobile/nubomedia-ouatclient-src
ios/LiveTales/uoat/LanguageViewController.swift
2
5303
// // LanguageViewController.swift // uoat // // Created by Pyro User on 9/5/16. // Copyright © 2016 Zed. All rights reserved. // import UIKit class LanguageViewController: UIViewController { weak var delegate:ExitDelegate?; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //Load resources //Arrow image (flipped). let leftArrowActiveImage:UIImage = Utils.flipImage(named: "btn_next_available", orientation: .Down) //Close button (header) let closeButton = UIButton() closeButton.frame = CGRectMake( 10, 10, leftArrowActiveImage.size.width, leftArrowActiveImage.size.height ) closeButton.addTarget( self, action: #selector(LanguageViewController.closeDialog(_:)), forControlEvents: .TouchUpInside ) closeButton.setBackgroundImage( leftArrowActiveImage, forState: .Normal ) closeButton.setBackgroundImage( leftArrowActiveImage, forState: .Highlighted ) self.view.subviews.first?.addSubview( closeButton ) //Title header. let mutableAttrString = NSMutableAttributedString(string: headerLabel.text!, attributes: [NSStrokeWidthAttributeName: -7.0, NSFontAttributeName: UIFont(name: "ArialRoundedMTBold", size: 20)!, NSStrokeColorAttributeName: UIColor.whiteColor(), NSForegroundColorAttributeName: headerLabel.textColor ]) headerLabel.attributedText! = mutableAttrString //Tick selector let tickImg:UIImage = UIImage(named: "img_tick")! self.currentLanguageImage = UIImageView( image:tickImg ) self.currentLanguageImage!.frame = CGRectMake( 25, 74, tickImg.size.width, tickImg.size.height ) self.view.subviews.first?.addSubview(self.currentLanguageImage!) let checkPosX:CGFloat = (self.view.subviews.first?.bounds.width)! - tickImg.size.width - tickImg.size.width*0.5 print("Current language:\(LanguageMgr.getInstance.getId())") for chkPos in self.checkPositions { if( chkPos.id == LanguageMgr.getInstance.getId() ) { self.currentLanguageImage!.frame = CGRectMake( checkPosX, CGFloat(chkPos.y), tickImg.size.width, tickImg.size.height ) break } } self.view.subviews.first?.addSubview(self.currentLanguageImage!) //Add blur efect to hide the last view. let blurEffectView:UIVisualEffectView = Utils.blurEffectView(self.view, radius: 10) self.view.addSubview(blurEffectView) self.view.sendSubviewToBack(blurEffectView) } override func viewDidLayoutSubviews() { let x:Int = Int(self.view.bounds.width)/2 - Int(self.dialogView.bounds.width)/2 let y:Int = Int(self.view.bounds.height)/2 - Int(self.dialogView.bounds.height)/2 self.dialogView.frame = CGRect(x: x, y: y, width: Int(self.dialogView.frame.width), height: Int(self.dialogView.frame.height)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { return true } func closeDialog(sender: UIButton) { dismissViewControllerAnimated( true, completion: nil ); delegate?.onCancel(); } /* // 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. } */ //dismissViewControllerAnimated( true, completion: nil ); /*=============================================================*/ /* UI Section */ /*=============================================================*/ @IBOutlet weak var dialogView: UIView! @IBOutlet weak var headerLabel: UILabel! @IBAction func spanish() { self.notifyChangeLanguage("es"); } @IBAction func english() { self.notifyChangeLanguage("en"); } @IBAction func german() { self.notifyChangeLanguage("de"); } /*=============================================================*/ /* Private Section */ /*=============================================================*/ private func notifyChangeLanguage( langId:String ) { LanguageMgr.getInstance.setId( langId ); dismissViewControllerAnimated( true, completion: nil ); delegate?.onCancel(); let message = Message( type:MessageType.changeLanguage, data:["langId":langId] ); Observer.getInstance.sendMessage( message ); } private var currentLanguageImage:UIImageView? = nil private let checkPositions:[(id:String,y:Int)] = [(id:"en",y:88),(id:"es",y:136),(id:"de",y:186)] }
apache-2.0
e5dd54e8248b93ee2180f2762756d658
34.824324
134
0.597322
5.122705
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Comments/CommentDetailViewController.swift
1
12171
import UIKit class CommentDetailViewController: UITableViewController { // MARK: Properties private var comment: Comment private var rows = [RowType]() // MARK: Views private var headerCell = CommentHeaderTableViewCell() private lazy var replyIndicatorCell: UITableViewCell = { let cell = UITableViewCell() // display the replied icon using attributed string instead of using the default image view. // this is because the default image view is displayed beyond the separator line (within the layout margin area). let iconAttachment = NSTextAttachment() iconAttachment.image = Style.ReplyIndicator.iconImage let attributedString = NSMutableAttributedString() attributedString.append(.init(attachment: iconAttachment, attributes: Style.ReplyIndicator.textAttributes)) attributedString.append(.init(string: " " + .replyIndicatorLabelText, attributes: Style.ReplyIndicator.textAttributes)) // reverse the attributed strings in RTL direction. if view.effectiveUserInterfaceLayoutDirection == .rightToLeft { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.baseWritingDirection = .rightToLeft attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: .init(location: 0, length: attributedString.length)) } cell.textLabel?.attributedText = attributedString cell.textLabel?.numberOfLines = 0 // setup constraints for textLabel to match the spacing specified in the design. if let textLabel = cell.textLabel { textLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ textLabel.leadingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leadingAnchor), textLabel.trailingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.trailingAnchor), textLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: Constants.replyIndicatorVerticalSpacing), textLabel.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -Constants.replyIndicatorVerticalSpacing) ]) } return cell }() // MARK: Initialization @objc required init(comment: Comment) { self.comment = comment super.init(style: .plain) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() configureNavigationBar() configureTable() configureRows() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // when an orientation change is triggered, recalculate the content cell's height. guard let contentRowIndex = rows.firstIndex(where: { $0 == .content }) else { return } tableView.reloadRows(at: [.init(row: contentRowIndex, section: .zero)], with: .fade) } // MARK: Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rows.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = rows[indexPath.row] switch row { case .header: configureHeaderCell() return headerCell case .content: guard let cell = tableView.dequeueReusableCell(withIdentifier: CommentContentTableViewCell.defaultReuseID) as? CommentContentTableViewCell else { return .init() } cell.configure(with: comment) { _ in self.tableView.performBatchUpdates({}) } return cell case .replyIndicator: return replyIndicatorCell case .text: return configuredTextCell(for: row) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch rows[indexPath.row] { case .header: navigateToPost() case .replyIndicator: // TODO: Navigate to the comment reply. break case .text(let title, _, _) where title == .webAddressLabelText: visitAuthorURL() default: break } } } // MARK: - Private Helpers private extension CommentDetailViewController { typealias Style = WPStyleGuide.CommentDetail enum RowType: Equatable { case header case content case replyIndicator case text(title: String, detail: String, image: UIImage? = nil) } struct Constants { static let tableLeadingInset: CGFloat = 20.0 static let replyIndicatorVerticalSpacing: CGFloat = 14.0 } func configureNavigationBar() { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editButtonTapped)) } func configureTable() { // get rid of the separator line for the last cell. tableView.tableFooterView = UIView(frame: .init(x: 0, y: 0, width: tableView.frame.size.width, height: 1)) // assign 20pt leading inset to the table view, as per the design. // note that by default, the system assigns 16pt inset for .phone, and 20pt for .pad idioms. if UIDevice.current.userInterfaceIdiom == .phone { tableView.directionalLayoutMargins.leading = Constants.tableLeadingInset } tableView.register(CommentContentTableViewCell.defaultNib, forCellReuseIdentifier: CommentContentTableViewCell.defaultReuseID) } func configureRows() { rows = [ .header, .content, .replyIndicator, // TODO: Conditionally add this when user has replied to the comment. .text(title: .webAddressLabelText, detail: comment.authorUrlForDisplay(), image: Style.externalIconImage), .text(title: .emailAddressLabelText, detail: comment.author_email), .text(title: .ipAddressLabelText, detail: comment.author_ip) ] } // MARK: Cell configuration func configureHeaderCell() { // TODO: detect if the comment is a reply. headerCell.textLabel?.text = .postCommentTitleText headerCell.detailTextLabel?.text = comment.titleForDisplay() } func configuredTextCell(for row: RowType) -> UITableViewCell { guard case let .text(title, detail, image) = row else { return .init() } let cell = tableView.dequeueReusableCell(withIdentifier: .textCellIdentifier) ?? .init(style: .subtitle, reuseIdentifier: .textCellIdentifier) cell.tintColor = Style.tintColor cell.textLabel?.font = Style.secondaryTextFont cell.textLabel?.textColor = Style.secondaryTextColor cell.textLabel?.text = title cell.detailTextLabel?.font = Style.textFont cell.detailTextLabel?.textColor = Style.textColor cell.detailTextLabel?.numberOfLines = 0 cell.detailTextLabel?.text = detail.isEmpty ? " " : detail // prevent the cell from collapsing due to empty label text. cell.accessoryView = { guard let image = image else { return nil } return UIImageView(image: image) }() return cell } // MARK: Actions and navigations func navigateToPost() { guard let blog = comment.blog, let siteID = blog.dotComID, blog.supports(.wpComRESTAPI) else { let postPermalinkURL = URL(string: comment.post?.permaLink ?? "") openWebView(for: postPermalinkURL) return } let readerViewController = ReaderDetailViewController.controllerWithPostID(NSNumber(value: comment.postID), siteID: siteID, isFeed: false) navigationController?.pushFullscreenViewController(readerViewController, animated: true) } func openWebView(for url: URL?) { guard let url = url else { DDLogError("\(Self.classNameWithoutNamespaces()): Attempted to open an invalid URL [\(url?.absoluteString ?? "")]") return } let viewController = WebViewControllerFactory.controllerAuthenticatedWithDefaultAccount(url: url) let navigationControllerToPresent = UINavigationController(rootViewController: viewController) present(navigationControllerToPresent, animated: true, completion: nil) } @objc func editButtonTapped() { let editCommentTableViewController = EditCommentTableViewController(comment: comment, completion: { [weak self] comment, commentChanged in guard commentChanged else { return } self?.comment = comment self?.tableView.reloadData() self?.updateComment() }) let navigationControllerToPresent = UINavigationController(rootViewController: editCommentTableViewController) navigationControllerToPresent.modalPresentationStyle = .fullScreen present(navigationControllerToPresent, animated: true) } func updateComment() { // Regardless of success or failure track the user's intent to save a change. CommentAnalytics.trackCommentEdited(comment: comment) let context = ContextManager.sharedInstance().mainContext let commentService = CommentService(managedObjectContext: context) commentService.uploadComment(comment, success: { [weak self] in // The comment might have changed its approval status self?.tableView.reloadData() }, failure: { [weak self] error in let message = NSLocalizedString("There has been an unexpected error while editing your comment", comment: "Error displayed if a comment fails to get updated") self?.displayNotice(title: message) }) } func visitAuthorURL() { guard let authorURL = comment.authorURL() else { return } openWebView(for: authorURL) } } // MARK: - Strings private extension String { // MARK: Constants static let replyIndicatorCellIdentifier = "replyIndicatorCell" static let textCellIdentifier = "textCell" // MARK: Localization static let postCommentTitleText = NSLocalizedString("Comment on", comment: "Provides hint that the current screen displays a comment on a post. " + "The title of the post will displayed below this string. " + "Example: Comment on \n My First Post") static let replyIndicatorLabelText = NSLocalizedString("You replied to this comment.", comment: "Informs that the user has replied to this comment.") static let webAddressLabelText = NSLocalizedString("Web address", comment: "Describes the web address section in the comment detail screen.") static let emailAddressLabelText = NSLocalizedString("Email address", comment: "Describes the email address section in the comment detail screen.") static let ipAddressLabelText = NSLocalizedString("IP address", comment: "Describes the IP address section in the comment detail screen.") }
gpl-2.0
c67c60e88f99329945825ea338a5f16a
38.26129
157
0.649166
5.619114
false
false
false
false
dvl/imagefy-ios
imagefy/Classes/Extensions/Extesions.swift
1
2202
// // Extesions.swift // // // Created by Alan Magalhães Lira on 21/05/16. // // import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = rgba.startIndex.advancedBy(1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix", terminator: "") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit
aff5e421a504dd34ddb923ba4731d892
39.777778
125
0.457519
4.045956
false
false
false
false
eBay/NMessenger
nMessengerTests/UI Components/Chat/BubbleConfigurationTests.swift
3
2084
// // BubbleConfigurationTests.swift // nMessenger // // Created by Tainter, Aaron on 8/23/16. // Copyright © 2016 Ebay Inc. All rights reserved. // import XCTest @testable import nMessenger class BubbleConfigurationTests: XCTestCase { func testStandardConfig() { let bc = StandardBubbleConfiguration() XCTAssertNotNil(bc.getBubble()) XCTAssertNotNil(bc.getSecondaryBubble()) XCTAssertNotNil(bc.getIncomingColor()) XCTAssertNotNil(bc.getOutgoingColor()) bc.isMasked = true XCTAssertNotNil(bc.getBubble()) XCTAssertNotNil(bc.getSecondaryBubble()) XCTAssertNotNil(bc.getIncomingColor()) XCTAssertNotNil(bc.getOutgoingColor()) XCTAssertTrue(bc.getBubble().hasLayerMask) XCTAssertTrue(bc.getSecondaryBubble().hasLayerMask) } func testSimpleBubbleConfig() { let bc = SimpleBubbleConfiguration() XCTAssertNotNil(bc.getBubble()) XCTAssertNotNil(bc.getSecondaryBubble()) XCTAssertNotNil(bc.getIncomingColor()) XCTAssertNotNil(bc.getOutgoingColor()) bc.isMasked = true XCTAssertNotNil(bc.getBubble()) XCTAssertNotNil(bc.getSecondaryBubble()) XCTAssertNotNil(bc.getIncomingColor()) XCTAssertNotNil(bc.getOutgoingColor()) XCTAssertTrue(bc.getBubble().hasLayerMask) XCTAssertTrue(bc.getSecondaryBubble().hasLayerMask) } func testImageBubbleConfiguration() { let bc = ImageBubbleConfiguration() XCTAssertNotNil(bc.getBubble()) XCTAssertNotNil(bc.getSecondaryBubble()) XCTAssertNotNil(bc.getIncomingColor()) XCTAssertNotNil(bc.getOutgoingColor()) bc.isMasked = true XCTAssertNotNil(bc.getBubble()) XCTAssertNotNil(bc.getSecondaryBubble()) XCTAssertNotNil(bc.getIncomingColor()) XCTAssertNotNil(bc.getOutgoingColor()) XCTAssertTrue(bc.getBubble().hasLayerMask) XCTAssertTrue(bc.getSecondaryBubble().hasLayerMask) } }
mit
6e1dad68918fde94a6cbd81e49dc8406
30.104478
59
0.670667
4.995204
false
true
false
false